content
stringlengths 7
2.61M
|
---|
<filename>utils/schema-doc-generator/script.py
import fileinput
import glob
from pathlib import Path
import sys
from json_schema_for_humans.generation_configuration import GenerationConfiguration
from json_schema_for_humans.generate import generate_from_filename
def reword_footer(file_path):
with fileinput.input(files=(file_path), inplace=True) as f:
for line in f:
search_string = "Generated using [json-schema-for-humans](https://github.com/coveooss/json-schema-for-humans)"
if search_string in line:
# this strips off the timestamp part of the line and should result in less doc commits since the file should be changing less frequently -- as opposed to every time the action runs.
line = search_string
sys.stdout.write(line)
config = GenerationConfiguration(template_name="md", show_toc=False)
schema_paths = glob.glob('utils/schemas/*.json')
for path in schema_paths:
# stem is filename without extension
stem = Path(path).stem
print(f'generating doc for: {path}')
generate_from_filename(path, f'docs/{stem}.md', config=config)
reword_footer(f'docs/{stem}.md')
|
/**
* a class that contains utility methods for {@link ItemStack}.
*/
@UtilityClass
public class ItemStackUtil {
/**
* parses the given material string into a new material.
*
* @param materialString the material string to parse.
*
* @return parsed material.
*/
@NotNull
public Optional<Material> parseMaterial(@NotNull final String materialString) {
if (BukkitVersion.MAJOR <= 7) {
return Optional.ofNullable(Material.getMaterial(materialString));
}
final var xMaterial = XMaterial.matchXMaterial(materialString);
if (xMaterial.isEmpty()) {
return Optional.empty();
}
final var material = Optional.ofNullable(xMaterial.get().parseMaterial());
if (material.isEmpty()) {
return Optional.empty();
}
return material;
}
} |
#include <stdlib.h>
#include <stdio.h>
#include "pilha.h"
STACK* createStack(){
STACK* p = (STACK*) malloc(sizeof(STACK));
p->stack = (dataType*) malloc(sizeofstack * sizeof(dataType));
p->top = -1;
p->size = 0;
return p;
}
int isStackEmpty(STACK* p) {
if (p->top == -1)
return 1;
return 0;
}
int isStackFull(STACK* p) {
if (p->top == sizeofstack -1)
return 1;
return 0;
}
//adiciona elementos a pilha
dataType stackPush(STACK* p, dataType elem) {
if (isStackFull(p) == 0) {
p->top++;
p->size++;
p->stack[p->top] = elem;
return 0;
}
else return -1;
}
//retorna o ultimo elemento da pilha
dataType stackPull(STACK* p) {
if (isStackEmpty(p) == 0)
return p->stack[p->top];
else return -1;
}
//remove elementos da pilha
dataType stackPop(STACK* p) {
if (isStackEmpty(p) == 0) {
p->top--;
p->size--;
return p->stack[p->top + 1];
}
else return -1;
}
int getStackSize(STACK* p){
if(p == NULL || p->stack == NULL) return -1;
return p->size;
}
void freeStack (STACK* p) {
free(p->stack);
}
|
Tackling Poverty Through Panel Data: Rural Poverty in India 1970-1998 The distinction between transitory and chronic poverty has been highlighted in the research conducted by the Chronic Poverty Research Centre. While estimates of the incidence of poverty obtained from sample based studies provide insights into the prevalence of poverty and its severity at a point of time, estimates of persistence of poverty need to be examined through use of a panel data set. In this paper we report some of the findings from analysis of extension of the earlier two-wave panel data set for the years 1970-71 and 1981-82 to a third wave for 1998-99. We therefore have three points at which data was collected for the same households, i.e., the years 1970-71, 1981-82 and 1998-99. The question of how persistent is poverty is important, because policies to alleviate transitory poverty may not be effective in addressing chronic or persistent poverty. Persistence of poverty suggests that there is failure of the economic system in integrating different sections of society in the growth process. The purpose of this paper is descriptive. We examine the extent of persistence of poverty in rural India based on the 3 surveys conducted by NCAER to track the same households over the period from 1970-71 and 1998-99. |
Mother-and-daughter Realtor team Karen Cunningham and Sonya Cunningham know that real estate is a 24/7 business, so having two agents is definitely better than one.
Karen, who moved to Austin in 1974 and has been a Realtor since 1990, specializes in waterfront properties and custom homes. Sonya focuses on the downtown area, a territory that the native Austinite, a Realtor since 2003, is more than comfortable with. Before entering the real estate industry, Karen worked as a registered nurse, where she learned that listening and putting others' needs first creates positive and lasting partnerships. Sonya shares these values, which has helped them establish a loyal clientele.
Both are licensed brokers, with Karen a Certified Luxury Home Marketing Specialist and Sonya a Certified Negotiation Expert. In 2016 alone, the pair sold $19.5 million worth of real estate.
We chatted with Karen and Sonya to find out more about their work and what drives them.
CultureMap: What’s one piece of advice you’d give to people looking for their dream home?
Karen Cunningham: To be patient. Take the time to really think about what your priorities are, create a list of must-haves, and we also recommend that you make a second list of “wants that can be negotiable.” Just like with most things, there are often compromises that need to be made and it’s great to know what you can live with, or without, when starting the process of finding your dream home.
Sonya Cunningham: We understand that selling a home is often an emotional process, so once you’ve made the decision to do so, we find it best to try and take off your owner’s hat and put on a seller’s hat. It’s a subtle shift, but take a moment to consider how a buyer will view your home.
KC: Fun, thriving, and accepting.
CM: What do you consider your best attribute?
SC: The fact that we are partners. We work together on every deal and are in constant communication. This means that our clients get two experienced agents for the price of one. With real estate, there are deadlines that need to be met and you often have to be in two places at once, so this allows us to be extremely available and attentive to our clients.
KC: Both of us love to cook when we have the time. Sonya even worked in the food industry for a couple of years.
Contact Karen at 512-413-2635 or karen.cunningham@sothebysrealty.com. Contact Sonya at 512-633-4619 or sonya.cunningham@sothebysrealty.com. |
Dedication
To Alexander Woolcott of Castleton Township, Rutland County, Vermont
Contents
Dedication
Foreword by Donald Margulies
Addendum to the Foreword of the 75th Anniversary Edition
Our Town: A play in three acts
Act I
Act II
Act III
Afterword by Tappan Wilder
Overview
Readings
Pre–Our Town
1. A Wedding: Wilder Encounters a Superstition
2. Life, Death, and Understanding in Wilder's Earlier Fiction and Drama
Fiction: "Once Upon a Time . . ."
Drama: "Good-by, Emerson Grammar School"
3. Our Town in the Making: Four Drafts
"M Marries N": The Birth of the Play (1935)
Grover's Corners, New Hampshire, "Latitude 71° 37´, Longitude 42° 40´" (1937)
"Good Night to You All, and Thank You" (1937)
"I'll Run for Something": George Gibbs's Political Aspirations (1938)
4. The Writing of Our Town: Here and Abroad
Our Town on the Boards
5. In Production: Sample Images
The McCarter Theatre, Princeton, New Jersey (1938)
The Broadway Program (1938–39)
Two Original Cast Photographs (1938)
6. The Playwright Discusses His Play "Sense of the Whole"
"A Village Against the Life of the Stars": Our Town's first Preface
"Take Your Pencil . . ."
7. Wilder vs. Harris: Before and After
Before: Wilder's Critical Response to Harris's Directing Choices
After: Wilder's Notes to Harris Regarding Subsequent Productions of Our Town
Special Features and Legacy
8. Wilder as Actor
9. Wilder as Adviser
10. Wilder Abroad
News from Abroad: Letter to Amos
L'Envoi
11. Final Thoughts: "Value above All Price . . ."
Acknowledgments
Source Material and Subsidiary Works
About the Author
Books by Thornton Wilder
Back Ad
Copyright
About the Publisher
Foreword
You are holding in your hands a great American play. Possibly, the great American play.
If you think you're already familiar with Our Town, chances are you read it long ago, in sixth or seventh grade, when it was lumped in a tasting portion of slim, palatable volumes of American literature along with The Red Pony by John Steinbeck and Edith Wharton's Ethan Frome. You were compelled to read it, like nasty medicine force-fed for your own good, when you were too young to appreciate how enriching it might be. Or perhaps you saw one too many amateur productions that, to put it kindly, failed to persuade you of the play's greatness. You sneered at the domestic activities of the citizenry of Grover's Corners, New Hampshire, and rolled your eyes at the quaint-seeming romance between George Gibbs and Emily Webb. You dismissed Our Town as a corny relic of Americana and relegated Thornton Wilder to the kitsch bin along with Norman Rockwell and Frank Capra.
You may have come around on Capra (It's a Wonderful Life actually owes a great deal to Our Town), and you may now be able to credit Rockwell for being a fine illustrator even if you can't quite bring yourself to call him an artist, but Wilder is another story. In your mind he remains the eternal schoolmaster preaching old-fashioned values to a modern public that knows far more than he does, and you remain steadfast in your skepticism of his importance to American literature.
You are not alone.
I have a confession to make: I didn't always appreciate the achievement of Thornton Wilder, either. Like many of you, I had read Our Town when I was too young and had seen it a few times. I thought I knew it and, frankly, didn't think much of it; I didn't get what was so great about it. That is, until I happened to see the 1988 Lincoln Center Theater production, directed by Gregory Mosher, an experience which remains one of the most memorable of my theatergoing life. I was so mesmerized by its subversive power, so warmed by its wisdom, so shattered by its third act, that I couldn't believe it was the same play I thought I had known since childhood. I went home and reread the masterpiece that had been on my shelf all along, and pored over the text to see what Mosher and his troupe of actors (led by Spalding Gray as the Stage Manager) had done differently. As far as I could tell, they had changed very little. I was the one who had changed. By the late eighties, I had entered my thirties and had a foothold in life; I had buried both my parents; I had protested a devastating war; and I had fallen in love. In other words, I had lived enough of a life to finally understand what was so great about Our Town.
"The response we make when we 'believe' a work of the imagination," Wilder wrote, "is that of saying: 'This is the way things are. I have always known it without being fully aware that I knew it. Now in the presence of this play or novel or poem (or picture or piece of music) I know that I know it.' "
Wilder was right: I believed every word of it.
One of the many joys of teaching is that you get to introduce students to work you admire. Since you can never relive the experience of seeing or hearing or reading a work of art for the first time, you can do the next best thing: you can teach it. And, through the discoveries your students make, you can recapture, vicariously, some of the exhilaration that accompanied your own discovery of that work long ago.
I teach playwriting to undergraduates at Yale. In addition to weekly writing assignments and a term project, my students read, and together we dissect, a variety of contemporary American and English plays (all personal favorites)—Harold Pinter's Betrayal; David Mamet's Glengarry Glen Ross; John Guare's Six Degrees of Separation; three plays by Caryl Churchill: Fen, Top Girls, and Mad Forest; Tennessee Williams's Cat on a Hot Tin Roof; Wallace Shawn's Aunt Dan and Lemon; Chris Durang's Marriage of Bette and Boo; and Anna Deavere Smith's Fires in the Mirror among them—each of which provides rich areas for discussion about structure, character, event, theme, story, style.
A few years ago I added Our Town to the list. I schedule it at the end by devious design: after our semester-long exploration of What Makes a Good Play, I sneak in a truly great one. Only I don't tell them it's a great one. "Why did you assign this play?" they demand to know. "Nothing happens." "It's dated." "Simplistic." "Sentimental."
I have them where I want them. Now I can give myself the pleasure of persuading them that they've got it all wrong, that the opposite of their criticisms is true: Our Town is anything but dated, it is timeless; it is simple, but also profound; it is full of genuine sentiment, which is not the same as its being sentimental; and, as far as its being uneventful, well, the event of the play is huge: it's life itself.
Like many works of great art, its greatness can be deceptive: a bare stage, spare language, archetypal characters. "Our claim, our hope, our despair are in the mind," Wilder wrote, "not in 'scenery.' " Indeed, he begins the play with: "No curtain. No scenery." It is important to recognize the thunder-clap those words amounted to. Consider the context: The play was written in 1937, when stage directions like that were still largely unheard of in American dramaturgy. The season Our Town graced Broadway, the other notable plays were now-forgotten boulevard comedies by Philip Barry and Clare Boothe (Here Come the Clowns and Kiss the Boys Goodbye, respectively), and melodramas by now-forgotten playwrights E. P. Conkle and Paul Vincent Carroll (Prologue to Glory and Shadow and Substance). Wilder alone was challenging the potential of theater. An old-fashioned writer? Thornton Wilder was radical! A visionary!
In his 1957 introduction to Three Plays, Wilder wrote of the loss of theatergoing pleasure he began to experience in the decade before writing Our Town, when he "ceased to believe in the stories [he] saw presented there. . . . The theatre was not only inadequate, it was evasive. . . . I found the word for it: it aimed to be soothing. The tragic had no heat; the comic had no bite; the social criticism failed to indict us with responsibility." (Has our theater really changed all that much since Wilder wrote those words? The same claim could be made today, given the "soothing" fare that dominates a Broadway where the "serious" play is the anomaly.)
Stripping the stage of fancy artifice, Wilder set himself a formidable challenge. With two ladders, a few pieces of furniture, and a minimum of props, he attempted "to find a value above all price for the smallest events in our daily life." Actors mimed their stage business; a "stage manager" functioned as both omniscient narrator and player. These ideas were startlingly modern for American drama in 1937. True, Pirandello broke down the conventions of the play fifteen years earlier, in Europe, in Six Characters in Search of an Author (the world premiere of which Wilder attended), and in the United States in the decade before Our Town, O'Neill tested the bounds of theatrical storytelling, with mixed results, in Strange Interlude. But with Our Town, Wilder exploded the accepted notions of character and story, and catapulted the American drama into the twentieth century. He did for the stage what Picasso and Braque's experiments in cubism did for painting and Joyce's stream of consciousness did for the novel. To mistake him for a traditionalist is to do Thornton Wilder an injustice. He was, in fact, a modernist who translated European and Asian ideas about theater into the American idiom.
By 1930, Wilder, who started his writing career as a novelist, had begun experimenting with dramatic form. Influenced by the economy of storytelling of Noh drama, he boldly compressed ninety years of a family's history into twenty minutes of stage time in The Long Christmas Dinner. His 1931 one-act, Pullman Car Hiawatha, which brings to life with a minimum of scenery a section of a train car and some of its passengers, reads as a marvelous rehearsal for many of the ideas he put to confident use in Our Town; it is also a fascinating play in its own right. In it, Wilder is in remarkably fertile fettle: chairs serve as berths in the Pullman car; actors represent the planets and passing fields and towns (including a Grover's Corners, Ohio); a stage manager is present (there's one in The Happy Journey to Trenton and Camden, too); a ghost makes an appearance, that of a German immigrant worker who perished while helping to build a trestle the train crosses; and, perhaps most strikingly, a young woman—a prototype for Emily—dies unexpectedly on the journey. The woman cries to the archangels Gabriel and Michael, who have arrived to escort her to her final destination, "I haven't done anything with my life . . . I haven't realized anything," before accepting her fate. "I see now," she says finally. "I see now. I understand everything now."
Anyone who dismisses Our Town as an idealized view of American life has failed to see the impieties and hypocrisies depicted in Wilder's vision. "Oh, Mama, you never tell us the truth about anything," Emily bemoans to her mother.
Simon Stimson, the alcoholic choirmaster, is a brilliant creation, buffoon and tragic figure all at once. He is not a stumbling town drunk designed for easy laughs; rather, he is a tortured, self-destructive soul whose cries for help are ignored by a provincial people steeped in denial. In the tragedy of Simon Stimson—a suicide, we learn in Act III—Wilder illustrates the failure of society to help its own and the insidiousness of systematic ignorance. "The only thing the rest of us can do," Mrs. Gibbs opines about Stimson's public drunkenness, "is just not to notice it." We may laugh at her Yankee pragmatism but it is also chilling.
The perfection of the play starts with its title. Grover's Corners belongs to all of us; it is indeed our town, a microcosm of the human family, genus American. But in that specificity it becomes all towns. Everywhere. Indeed, the play's success across cultural borders around the world attests to its being something much greater than an American play: it is a play that captures the universal experience of being alive.
The Stage Manager tells us the play's action begins on May 7, 1901, but it is as specific to that time as it was, no doubt, to 1937, and as it is to the time in which we're living. The three-act structure is a marvel of economy: Act I is dubbed "Daily Life," Act II, "Love and Marriage," and Act III, "I reckon you can guess what that's about."
The simultaneity of life and death, past, present, and future pervades Our Town. As soon as we are introduced to Doc and Mrs. Gibbs, the Stage Manager informs us of their deaths. Minutes into the play and already the long shadow of death is cast, ironizing all that follows. With the specter of mortality hovering, the quotidian business of the people of Grover's Corners attains a kind of grandeur.
When eleven-year-old Joe Crowell, the newsboy, enters, making his rounds, he and Doc Gibbs chat about the weather, the boy's teacher's impending marriage, and the condition of his pesky knee. The prosaic turns suddenly wrenching when the Stage Manager casually fills us in on young Joe's future, his scholarship to MIT, his graduating at the top of his class. "Goin' to be a great engineer, Joe was. But the war broke out and he died in France.—All that education for nothing." How could anyone accuse Wilder of sentimentality when he, like life, is capable of such cruelty? In just a few eloquent sentences he captures both the capriciousness of life and the futility of war. The war Wilder referred to, of course, was the Great War—the world was between wars when he wrote Our Town—but the poignancy of the news-boy's fate is felt perhaps even more exquisitely today, in light of all the death and destruction the world has endured since.
Note the audacious and surprising ways in which Wilder has structured his acts; he interrupts the narrative flow of each with a stylistic departure. In Act I, Professor Willard and Editor Webb offer discursive sidebars about the geography and sociology of Grover's Corners, a device reminiscent of the collagist technique of newsreel and newspaper snippets employed by his contemporary, the novelist John Dos Passos, in his U.S.A. trilogy.
At the start of the second act, it is three years later, George and Emily's wedding day. The Stage Manager interrupts the frantic preparations to show us "how all this began. . . . I'm awfully interested in how big things like that begin." And he takes us back in time to the drugstore-counter conversation the couple had "when they first knew that . . . they were meant for one another." Once that seminal event is re-created, we return to the wedding itself. Emily, the bride with cold feet, plaintively asks her father, "Why can't I stay for a while just as I am," expressing the ageless, heartbreaking, child's wish to prolong the charmed state of childhood and stave off the harshness of the adult world.
The passage from Love and Marriage to Death is as abrupt and wrenching as it is in real life. The people whose vitality moved and amused us before intermission are now coolly seated in rows in the town cemetery. Mrs. Gibbs, Simon Stimson, and Mrs. Soames, "who enjoyed the wedding so," are all dead now, as is Wally Webb, whose young life was cut short by a burst appendix while on a Boy Scout camping trip.
Much as the soda-fountain flashback is the centerpiece of the second act, Emily's posthumous visit to the past in the middle of Act III provides the emotional climax of the play. Newly deceased while giving birth to her second child, Emily wishes to go back to a happy day and chooses her twelfth birthday. The dead warn her that such a return can only be painful. The job of the dead, they tell her, is to forget the living. Emily learns all too quickly that they are right and decides to join the indifferent dead. Her farewell is one of the immortal moments in all of American drama:
Good-by, Good-by, world. Good-by, Grover's Corners . . . Mama and Papa. Good-by to clocks ticking . . . and Mama's sunflowers. And food and coffee. And new-ironed dresses and hot baths . . . and sleeping and waking up. Oh, earth, you're too wonderful for anybody to realize you.
Wilder modestly wrote, "I am not one of the new dramatists we are looking for. I wish I were. I hope I have played a part in preparing the way for them." He was wrong about not being one of the "new dramatists." In some respects he was the first American playwright. The part he played in preparing those who followed—Williams, Miller, Albee, Wilson (Lanford), Wilson (August), Vogel, to list a few—is incalculable.
"The cottage, the go-cart, the Sunday-afternoon drives in the Ford, the first rheumatism, the grandchildren, the second rheumatism, the deathbed, the reading of the will,"—it's all here, all in Our Town, all the passages of life.
If you are new to Our Town, I envy you. A joyous discovery awaits you.
Welcome—or welcome back—to Our Town.
—Donald Margulies
New Haven, Connecticut
Addendum to the Foreword of the 75th Anniversary Edition
A little more than ten years ago, when I first approached the daunting task of writing a foreword to Our Town, the aftershocks of 9/11 were still being felt; my reading of the play at that time was very much colored by that calamitous event. Thornton Wilder's 1938 meditation on life, love and marriage, and death in a small New Hampshire town in the early part of the twentieth century seemed to illuminate uncannily the experience of being alive in the twenty-first. (Indeed, there was a resurgence of interest in the play and a spate of productions worldwide, including David Cromer's revelatory mounting in 2009.)
Today, as I contemplate the play anew for this addendum, a different horror casts its shadow over the pages of Our Town: the massacre of twenty children and six adults at the Sandy Hook Elementary School in Newtown, Connecticut. When that terrible incident occurred, just a few weeks prior to this writing, I couldn't help but think of Our Town. Maybe it was the New England setting with the universal-sounding Newtown standing in for Grover's Corners. I imagined a typical, tranquil town, peopled with decent citizens, suddenly seeing their world shattered and their beloved children brutally, inexplicably, taken away from them. The simple truths about family and community Wilder wrote about seventy-five years ago seemed to articulate the enormity of this contemporary tragedy.
Our Town celebrates life in all its mundane profundity. Something as seemingly inconsequential as Mrs. Gibbs's exasperated call to her children to come down to breakfast can produce tears of identification. A Boy Scout camping trip is tragically cut short. A trip to Paris is never taken. Childbirth ends in death.
"Do any human beings ever realize life while they live it?—every, every minute?" Emily asks through her tears. "No," the Stage Manager curtly replies. "The saints and poets, maybe—they do some."
—Donald Margulies
New Haven, Connecticut
January 3, 2013
Donald Margulies won the 2000 Pulitzer Prize for Drama for Dinner with Friends and was a finalist twice before with Sight Unseen and Collected Stories. His other plays include The Country House, Coney Island Christmas, Time Stands Still, Shipwrecked! An Entertainment, Brooklyn Boy, and The Loman Family Picnic. Mr. Margulies is an adjunct professor of English and Theatre Studies at Yale University.
The first performance of this play took place at the McCarter Theatre, Princeton, New Jersey, on January 22, 1938. The first New York performance was at Henry Miller's Theatre, February 4, 1938. It was produced and directed by Jed Harris. The technical drirector was Raymond Sovey; the costumes were designed by Madame Hélène Pons. The role of the Stage Manager was played by Frank Craven. The Gibbs family were played by Jay Fassett, Evelyn Varden, John Craven and Marilyn Erskine; the Webb family by Thomas Ross, Helen Carew, Martha Scott (as Emily), and Charles Wiley, Jr.; Mrs. Soames was played by Doro Merande; Simon Stimson by Philip Coolidge.
CHARACTERS (in the order of their appearance)
STAGE MANAGER
DR. GIBBS
JOE CROWELL
HOWIE NEWSOME
MRS. GIBBS
MRS. WEBB
GEORGE GIBBS
REBECCA GIBBS
WALLY WEBB
EMILY WEBB
PROFESSOR WILLARD
MR. WEBB
WOMAN IN THE BALCONY
MAN IN THE AUDITORIUM
LADY IN THE BOX
SIMON STIMSON
MRS. SOAMES
CONSTABLE WARREN
SI CROWELL
THREE BASEBALL PLAYERS
SAM CRAIG
JOE STODDARD
The entire play takes place in Grover's Corners,
New Hampshire.
Act I
No curtain.
No scenery.
The audience, arriving, sees an empty stage in half-light. Presently the STAGE MANAGER, hat on and pipe in mouth,
enters and begins placing a table and three chairs downstage left, and a table and three chairs downstage right.
He also places a low bench at the corner of what will be the Webb house, left.
"Left" and "right" are from the point of view of the actor facing the audience. "Up" is toward the back wall.
As the house lights go down he has finished setting the stage and leaning against the right proscenium pillar watches the late arrivals in the audience.
When the auditorium is in complete darkness he speaks:
STAGE MANAGER:
This play is called "Our Town." It was written by Thornton Wilder; produced and directed by A. . . . (or: produced by A. . . . ; directed by B. . . . ). In it you will see Miss C. . . . ; Miss D. . . . ; Miss E. . . . ; and Mr. F. . . . ; Mr. G. . . . ;
Mr. H. . . . ; and many others. The name of the town is Grover's Corners, New Hampshire—just across the Massachusetts line: latitude 42 degrees 40 minutes; longitude 70 degrees 37 minutes. The First Act shows a day in our town. The day is May 7, 1901. The time is just before dawn.
A rooster crows.
The sky is beginning to show some streaks of light over in the East there, behind our mount'in.
The morning star always gets wonderful bright the minute before it has to go,—doesn't it?
He stares at it for a moment, then goes upstage.
Well, I'd better show you how our town lies. Up here—
That is: parallel with the back wall.
is Main Street. Way back there is the railway station; tracks go that way. Polish Town's across the tracks, and some Canuck families.
Toward the left.
Over there is the Congregational Church; across the street's the Presbyterian.
Methodist and Unitarian are over there.
Baptist is down in the holla' by the river.
Catholic Church is over beyond the tracks.
Here's the Town Hall and Post Office combined; jail's in the basement.
Bryan once made a speech from these very steps here.
Along here's a row of stores. Hitching posts and horse blocks in front of them. First automobile's going to come along in about five years—belonged to Banker Cartwright, our richest citizen . . . lives in the big white house up on the hill.
Here's the grocery store and here's Mr. Morgan's drugstore. Most everybody in town manages to look into those two stores once a day.
Public School's over yonder. High School's still farther over. Quarter of nine mornings, noontimes, and three o'clock afternoons, the hull town can hear the yelling and screaming from those schoolyards.
He approaches the table and chairs downstage right.
This is our doctor's house,—Doc Gibbs'. This is the back door.
Two arched trellises, covered with vines and flowers, are pushed out, one by each proscenium pillar.
There's some scenery for those who think they have to have scenery.
This is Mrs. Gibbs' garden. Corn . . . peas . . . beans . . . hollyhocks . . . heliotrope . . . and a lot of burdock.
Crosses the stage.
In those days our newspaper come out twice a week—the Grover's Corners Sentinel—and this is Editor Webb's house.
And this is Mrs. Webb's garden.
Just like Mrs. Gibbs', only it's got a lot of sunflowers, too.
He looks upward, center stage.
Right here . . .'s a big butternut tree.
He returns to his place by the right proscenium pillar and looks at the audience for a minute.
Nice town, y'know what I mean?
Nobody very remarkable ever come out of it, s'far as we know.
The earliest tombstones in the cemetery up there on the mountain say 1670–1680—they're Grovers and Cartwrights and Gibbses and Herseys—same names as are around here now.
Well, as I said: it's about dawn.
The only lights on in town are in a cottage over by the tracks where a Polish mother's just had twins. And in the Joe Crow-ell house, where Joe Junior's getting up so as to deliver the paper. And in the depot, where Shorty Hawkins is gettin' ready to flag the 5:45 for Boston.
A train whistle is heard. The STAGE MANAGER takes out his watch and nods.
Naturally, out in the country—all around—there've been lights on for some time, what with milkin's and so on. But town people sleep late.
So—another day's begun.
There's Doc Gibbs comin' down Main Street now, comin' back from that baby case. And here's his wife comin' downstairs to get breakfast.
MRS. GIBBS, a plump, pleasant woman in the middle thirties, comes "downstairs" right. She pulls up an imaginary window shade in her kitchen and starts to make a fire in her stove.
Doc Gibbs died in 1930. The new hospital's named after him.
Mrs. Gibbs died first—long time ago, in fact. She went out to visit her daughter, Rebecca, who married an insurance man in Canton, Ohio, and died there—pneumonia—but her body was brought back here. She's up in the cemetery there now—in with a whole mess of Gibbses and Herseys—she was Julia Hersey 'fore she married Doc Gibbs in the Congregational Church over there.
In our town we like to know the facts about everybody.
There's Mrs. Webb, coming downstairs to get her breakfast, too.
—That's Doc Gibbs. Got that call at half past one this morning.
And there comes Joe Crowell, Jr., delivering Mr. Webb's Sentinel.
DR. GIBBS has been coming along Main Street from the left. At the point where he would turn to approach his house, he stops, sets down his—imaginary—black bag, takes off his hat, and rubs his face with fatigue, using an enormous handkerchief.
MRS. WEBB, a thin, serious, crisp woman, has entered her kitchen, left, tying on an apron. She goes through the motions of putting wood into a stove, lighting it, and preparing breakfast.
Suddenly, JOE CROWELL, JR., eleven, starts down Main Street from the right, hurling imaginary newspapers into doorways.
JOE CROWELL, JR.:
Morning, Doc Gibbs.
DR. GIBBS:
Morning, Joe.
JOE CROWELL, JR.:
Somebody been sick, Doc?
DR. GIBBS:
No. Just some twins born over in Polish Town.
JOE CROWELL, JR.:
Do you want your paper now?
DR. GIBBS:
Yes, I'll take it.—Anything serious goin' on in the world since Wednesday?
JOE CROWELL, JR.:
Yessir. My schoolteacher, Miss Foster, 's getting married to a fella over in Concord.
DR. GIBBS:
I declare.—How do you boys feel about that?
JOE CROWELL, JR.:
Well, of course, it's none of my business—but I think if a person starts out to be a teacher, she ought to stay one.
DR. GIBBS:
How's your knee, Joe?
JOE CROWELL, JR.:
Fine, Doc, I never think about it at all. Only like you said, it always tells me when it's going to rain.
DR. GIBBS:
What's it telling you today? Goin' to rain?
JOE CROWELL, JR.:
No, sir.
DR. GIBBS:
Sure?
JOE CROWELL, JR.:
Yessir.
DR. GIBBS:
Knee ever make a mistake?
JOE CROWELL, JR.:
No, sir.
JOE goes off. DR. GIBBS stands reading his paper.
STAGE MANAGER:
Want to tell you something about that boy Joe Crowell there. Joe was awful bright—graduated from high school here, head of his class. So he got a scholarship to Massachusetts Tech. Graduated head of his class there, too. It was all wrote up in the Boston paper at the time. Goin' to be a great engineer, Joe was. But the war broke out and he died in France.—All that education for nothing.
HOWIE NEWSOME:
Off left.
Giddap, Bessie! What's the matter with you today?
STAGE MANAGER:
Here comes Howie Newsome, deliverin' the milk.
HOWIE NEWSOME, about thirty, in overalls, comes along Main Street from the left, walking beside an invisible horse and wagon and carrying an imaginary rack with milk bottles. The sound of clinking milk bottles is heard. He leaves some bottles at Mrs. Webb's trellis, then, crossing the stage to Mrs. Gibbs', he stops center to talk to Dr. Gibbs.
HOWIE NEWSOME:
Morning, Doc.
DR. GIBBS:
Morning, Howie.
HOWIE NEWSOME:
Somebody sick?
DR. GIBBS:
Pair of twins over to Mrs. Goruslawski's.
HOWIE NEWSOME:
Twins, eh? This town's gettin' bigger every year.
DR. GIBBS:
Goin' to rain, Howie?
HOWIE NEWSOME:
No, no. Fine day—that'll burn through. Come on, Bessie.
DR. GIBBS:
Hello Bessie.
He strokes the horse, which has remained up center.
How old is she, Howie?
HOWIE NEWSOME:
Going on seventeen. Bessie's all mixed up about the route ever since the Lockharts stopped takin' their quart of milk every day. She wants to leave 'em a quart just the same—keeps scolding me the hull trip.
He reaches Mrs. Gibbs' back door. She is waiting for him.
MRS. GIBBS:
Good morning, Howie.
HOWIE NEWSOME:
Morning, Mrs. Gibbs. Doc's just comin' down the street.
MRS. GIBBS:
Is he? Seems like you're late today.
HOWIE NEWSOME:
Yes. Somep'n went wrong with the separator. Don't know what 'twas.
He passes Dr. Gibbs up center.
Doc!
DR. GIBBS:
Howie!
MRS. GIBBS:
Calling upstairs.
Children! Children! Time to get up.
HOWIE NEWSOME:
Come on, Bessie!
He goes off right.
MRS. GIBBS:
George! Rebecca!
DR. GIBBS arrives at his back door and passes through the trellis into his house.
MRS. GIBBS:
Everything all right, Frank?
DR. GIBBS:
Yes. I declare—easy as kittens.
MRS. GIBBS:
Bacon'll be ready in a minute. Set down and drink your coffee. You can catch a couple hours' sleep this morning, can't you?
DR. GIBBS:
Hm! . . . Mrs. Wentworth's coming at eleven. Guess I know what it's about, too. Her stummick ain't what it ought to be.
MRS. GIBBS:
All told, you won't get more'n three hours' sleep. Frank Gibbs, I don't know what's goin' to become of you. I do wish I could get you to go away someplace and take a rest. I think it would do you good.
MRS. WEBB:
Emileeee! Time to get up! Wally! Seven o'clock!
MRS. GIBBS:
I declare, you got to speak to George. Seems like something's come over him lately. He's no help to me at all. I can't even get him to cut me some wood.
DR. GIBBS:
Washing and drying his hands at the sink. MRS. GIBBS is busy at the stove.
Is he sassy to you?
MRS. GIBBS:
No. He just whines! All he thinks about is that baseball—George! Rebecca! You'll be late for school.
DR. GIBBS:
M-m-m . . .
MRS. GIBBS:
George!
DR. GIBBS:
George, look sharp!
GEORGE'S VOICE:
Yes, Pa!
DR. GIBBS:
As he goes off the stage.
Don't you hear your mother calling you? I guess I'll go upstairs and get forty winks.
MRS. WEBB:
Walleee! Emileee! You'll be late for school! Walleee! You wash yourself good or I'll come up and do it myself.
REBECCA GIBBS' VOICE:
Ma! What dress shall I wear?
MRS. GIBBS:
Don't make a noise. Your father's been out all night and needs his sleep. I washed and ironed the blue gingham for you special.
REBECCA:
Ma, I hate that dress.
MRS. GIBBS:
Oh, hush-up-with-you.
REBECCA:
Every day I go to school dressed like a sick turkey.
MRS. GIBBS:
Now, Rebecca, you always look very nice.
REBECCA:
Mama, George's throwing soap at me.
MRS. GIBBS:
I'll come and slap the both of you,—that's what I'll do.
A factory whistle sounds.
The CHILDREN dash in and take their places at the tables. Right, GEORGE, about sixteen, and REBECCA, eleven. Left, EMILY and WALLY, same ages. They carry strapped schoolbooks.
STAGE MANAGER:
We've got a factory in our town too—hear it? Makes blankets. Cartwrights own it and it brung 'em a fortune.
MRS. WEBB:
Children! Now I won't have it. Breakfast is just as good as any other meal and I won't have you gobbling like wolves. It'll stunt your growth,—that's a fact. Put away your book, Wally.
WALLY:
Aw, Ma! By ten o'clock I got to know all about Canada.
MRS. WEBB:
You know the rule's well as I do—no books at table. As for me, I'd rather have my children healthy than bright.
EMILY:
I'm both, Mama: you know I am. I'm the brightest girl in school for my age. I have a wonderful memory.
MRS. WEBB:
Eat your breakfast.
WALLY:
I'm bright, too, when I'm looking at my stamp collection.
MRS. GIBBS:
I'll speak to your father about it when he's rested. Seems to me twenty-five cents a week's enough for a boy your age. I declare I don't know how you spend it all.
GEORGE:
Aw, Ma,—I gotta lotta things to buy.
MRS. GIBBS:
Strawberry phosphates—that's what you spend it on.
GEORGE:
I don't see how Rebecca comes to have so much money. She has more'n a dollar.
REBECCA:
Spoon in mouth, dreamily.
I've been saving it up gradual.
MRS. GIBBS:
Well, dear, I think it's a good thing to spend some every now and then.
REBECCA:
Mama, do you know what I love most in the world—do you?—Money.
MRS. GIBBS:
Eat your breakfast.
THE CHILDREN:
Mama, there's first bell.—I gotta hurry.—I don't want any more.—I gotta hurry.
The CHILDREN rise, seize their books and dash out through the trellises. They meet, down center, and chattering, walk to Main Street, then turn left.
The STAGE MANAGER goes off, unobtrusively, right.
MRS. WEBB:
Walk fast, but you don't have to run. Wally, pull up your pants at the knee. Stand up straight, Emily.
MRS. GIBBS:
Tell Miss Foster I send her my best congratulations—can you remember that?
REBECCA: MRS. GIBBS:
You look real nice, Rebecca. Pick up your feet.
ALL:
Good-by.
MRS. GIBBS fills her apron with food for the chickens and comes down to the footlights.
MRS. GIBBS:
Here, chick, chick, chick.
No, go away, you. Go away.
Here, chick, chick, chick.
What's the matter with you? Fight, fight, fight,—that's all you do.
Hm . . . you don't belong to me. Where'd you come from?
She shakes her apron.
Oh, don't be so scared. Nobody's going to hurt you.
MRS. WEBB is sitting on the bench by her trellis, stringing beans.
Good morning, Myrtle. How's your cold?
MRS. WEBB:
Well, I still get that tickling feeling in my throat. I told Charles I didn't know as I'd go to choir practice tonight. Wouldn't be any use.
MRS. GIBBS:
Have you tried singing over your voice?
Yes, Ma.
MRS. WEBB:
Yes, but somehow I can't do that and stay on the key. While I'm resting myself I thought I'd string some of these beans.
MRS. GIBBS:
Rolling up her sleeves as she crosses the stage for a chat.
Let me help you. Beans have been good this year.
MRS. WEBB:
I've decided to put up forty quarts if it kills me. The children say they hate 'em, but I notice they're able to get 'em down all winter.
Pause. Brief sound of chickens cackling.
MRS. GIBBS:
Now, Myrtle. I've got to tell you something, because if I don't tell somebody I'll burst.
MRS. WEBB:
Why, Julia Gibbs!
MRS. GIBBS:
Here, give me some more of those beans. Myrtle, did one of those secondhand-furniture men from Boston come to see you last Friday?
MRS. WEBB:
No-o.
MRS. GIBBS:
Well, he called on me. First I thought he was a patient wantin' to see Dr. Gibbs. 'N he wormed his way into my parlor, and, Myrtle Webb, he offered me three hundred and fifty dollars for Grandmother Wentworth's highboy, as I'm sitting here!
MRS. WEBB:
Why, Julia Gibbs!
MRS. GIBBS:
He did! That old thing! Why, it was so big I didn't know where to put it and I almost give it to Cousin Hester Wilcox.
MRS. WEBB:
Well, you're going to take it, aren't you?
MRS. GIBBS:
I don't know.
MRS. WEBB:
You don't know—three hundred and fifty dollars! What's come over you?
MRS. GIBBS:
Well, if I could get the Doctor to take the money and go away someplace on a real trip, I'd sell it like that.—Y'know, Myrtle, it's been the dream of my life to see Paris, France.—Oh, I don't know. It sounds crazy, I suppose, but for years I've been promising myself that if we ever had the chance—
MRS. WEBB:
How does the Doctor feel about it?
MRS. GIBBS:
Well, I did beat about the bush a little and said that if I got a legacy—that's the way I put it—I'd make him take me somewhere.
MRS. WEBB:
M-m-m . . . What did he say?
MRS. GIBBS:
You know how he is. I haven't heard a serious word out of him since I've known him. No, he said, it might make him discontented with Grover's Corners to go traipsin' about Europe; better let well enough alone, he says. Every two years he makes a trip to the battlefields of the Civil War and that's enough treat for anybody, he says.
MRS. WEBB:
Well, Mr. Webb just admires the way Dr. Gibbs knows everything about the Civil War. Mr. Webb's a good mind to give up Napoleon and move over to the Civil War, only Dr. Gibbs being one of the greatest experts in the country just makes him despair.
MRS. GIBBS:
It's a fact! Dr. Gibbs is never so happy as when he's at Antietam or Gettysburg. The times I've walked over those hills, Myrtle, stopping at every bush and pacing it all out, like we were going to buy it.
MRS. WEBB:
Well, if that secondhand man's really serious about buyin' it, Julia, you sell it. And then you'll get to see Paris, all right. Just keep droppin' hints from time to time—that's how I got to see the Atlantic Ocean, y'know.
MRS. GIBBS:
Oh, I'm sorry I mentioned it. Only it seems to me that once in your life before you die you ought to see a country where they don't talk in English and don't even want to.
The STAGE MANAGER enters briskly from the right. He tips his hat to the ladies, who nod their heads.
STAGE MANAGER:
Thank you, ladies. Thank you very much.
MRS. GIBBS and MRS. WEBB gather up their things, return into their homes and disappear.
Now we're going to skip a few hours.
But first we want a little more information about the town, kind of a scientific account, you might say.
So I've asked Professor Willard of our State University to sketch in a few details of our past history here.
Is Professor Willard here?
PROFESSOR WILLARD, a rural savant, pince-nez on a wide satin ribbon, enters from the right with some notes in his hand.
May I introduce Professor Willard of our State University.
A few brief notes, thank you, Professor,—unfortunately our time is limited.
PROFESSOR WILLARD:
Grover's Corners . . . let me see . . . Grover's Corners lies on the old Pleistocene granite of the Appalachian range. I may say it's some of the oldest land in the world. We're very proud of that. A shelf of Devonian basalt crosses it with vestiges of Mesozoic shale, and some sandstone outcroppings; but that's all more recent: two hundred, three hundred million years old.
Some highly interesting fossils have been found . . . I may say: unique fossils . . . two miles out of town, in Silas Peck-ham's cow pasture. They can be seen at the museum in our University at any time—that is, at any reasonable time. Shall I read some of Professor Gruber's notes on the meteorological situation—mean precipitation, et cetera?
STAGE MANAGER:
Afraid we won't have time for that, Professor. We might have a few words on the history of man here.
PROFESSOR WILLARD:
Yes . . . anthropological data: Early Amerindian stock. Cotahatchee tribes . . . no evidence before the tenth century of this era . . . hm . . . now entirely disappeared . . . possible traces in three families. Migration toward the end of the seventeenth century of English brachiocephalic blue-eyed stock . . . for the most part. Since then some Slav and Mediterranean—
STAGE MANAGER:
And the population, Professor Willard?
PROFESSOR WILLARD:
Within the town limits: 2,640.
STAGE MANAGER:
Just a moment, Professor.
He whispers into the professor's ear.
PROFESSOR WILLARD:
Oh, yes, indeed?—The population, at the moment, is 2,642. The Postal District brings in 507 more, making a total of 3,149.—Mortality and birth rates: constant.—By MacPherson's gauge: 6.032.
STAGE MANAGER:
Thank you very much, Professor. We're all very much obliged to you, I'm sure.
PROFESSOR WILLARD:
Not at all, sir; not at all.
STAGE MANAGER:
This way, Professor, and thank you again.
Exit PROFESSOR WILLARD.
Now the political and social report: Editor Webb.—Oh, Mr. Webb?
MRS. WEBB appears at her back door.
MRS. WEBB:
He'll be here in a minute. . . . He just cut his hand while he was eatin' an apple.
STAGE MANAGER:
Thank you, Mrs. Webb.
MRS. WEBB:
Charles! Everybody's waitin'.
Exit MRS. WEBB.
STAGE MANAGER:
Mr. Webb is Publisher and Editor of the Grover's Corners Sentinel. That's our local paper, y'know.
MR. WEBB enters from his house, pulling on his coat. His finger is bound in a handkerchief.
MR. WEBB:
Well . . . I don't have to tell you that we're run here by a Board of Selectmen.—All males vote at the age of twenty-one. Women vote indirect. We're lower middle class: sprinkling of professional men . . . ten per cent illiterate laborers. Politically, we're eighty-six per cent Republicans; six per cent Democrats; four per cent Socialists; rest, indifferent.
Religiously, we're eighty-five per cent Protestants; twelve per cent Catholics; rest, indifferent.
STAGE MANAGER:
Have you any comments, Mr. Webb?
MR. WEBB:
Very ordinary town, if you ask me. Little better behaved than most. Probably a lot duller.
But our young people here seem to like it well enough. Ninety per cent of 'em graduating from high school settle down right here to live—even when they've been away to college.
STAGE MANAGER:
Now, is there anyone in the audience who would like to ask Editor Webb anything about the town?
WOMAN IN THE BALCONY:
Is there much drinking in Grover's Corners?
MR. WEBB:
Well, ma'am, I wouldn't know what you'd call much. Satiddy nights the farmhands meet down in Ellery Greenough's stable and holler some. We've got one or two town drunks, but they're always having remorses every time an evangelist comes to town. No, ma'am, I'd say likker ain't a regular thing in the home here, except in the medicine chest. Right good for snake bite, y'know—always was.
BELLIGERENT MAN AT BACK OF AUDITORIUM:
Is there no one in town aware of—
STAGE MANAGER:
Come forward, will you, where we can all hear you—What were you saying?
BELLIGERENT MAN:
Is there no one in town aware of social injustice and industrial inequality?
MR. WEBB:
Oh, yes, everybody is—somethin' terrible. Seems like they spend most of their time talking about who's rich and who's poor.
BELLIGERENT MAN:
Then why don't they do something about it?
He withdraws without waiting for an answer.
MR. WEBB:
Well, I dunno. . . . I guess we're all hunting like everybody else for a way the diligent and sensible can rise to the top and the lazy and quarrelsome can sink to the bottom. But it ain't easy to find. Meanwhile, we do all we can to help those that can't help themselves and those that can we leave alone.—Are there any other questions?
LADY IN A BOX:
Oh, Mr. Webb? Mr. Webb, is there any culture or love of beauty in Grover's Corners?
MR. WEBB:
Well, ma'am, there ain't much—not in the sense you mean. Come to think of it, there's some girls that play the piano at High School Commencement; but they ain't happy about it. No, ma'am, there isn't much culture; but maybe this is the place to tell you that we've got a lot of pleasures of a kind here: we like the sun comin' up over the mountain in the morning, and we all notice a good deal about the birds. We pay a lot of attention to them. And we watch the change of the seasons; yes, everybody knows about them. But those other things—you're right, ma'am,—there ain't much.—Robinson Crusoe and the Bible; and Handel's "Largo," we all know that; and Whistler's "Mother"—those are just about as far as we go.
LADY IN A BOX:
So I thought. Thank you, Mr. Webb.
STAGE MANAGER:
Thank you, Mr. Webb.
MR. WEBB retires.
Now, we'll go back to the town. It's early afternoon. All 2,642 have had their dinners and all the dishes have been washed.
MR. WEBB, having removed his coat, returns and starts pushing a lawn mower to and fro beside his house.
There's an early-afternoon calm in our town: a buzzin' and a hummin' from the school buildings; only a few buggies on Main Street—the horses dozing at the hitching posts; you all remember what it's like. Doc Gibbs is in his office, tapping people and making them say "ah." Mr. Webb's cuttin' his lawn over there; one man in ten thinks it's a privilege to push his own lawn mower.
No, sir. It's later than I thought. There are the children coming home from school already.
Shrill girls' voices are heard, off left. EMILY comes along Main Street, carrying some books. There are some signs that she is imagining herself to be a lady of startling elegance.
EMILY:
I can't, Lois. I've got to go home and help my mother. I promised.
MR. WEBB:
Emily, walk simply. Who do you think you are today?
EMILY:
Papa, you're terrible. One minute you tell me to stand up straight and the next minute you call me names. I just don't listen to you.
She gives him an abrupt kiss.
MR. WEBB:
Golly, I never got a kiss from such a great lady before.
He goes out of sight. EMILY leans over and picks some flowers by the gate of her house.
GEORGE GIBBS comes careening down Main Street. He is throwing a ball up to dizzying heights, and waiting to catch it again. This sometimes requires his taking six steps backward. He bumps into an OLD LADY invisible to us.
GEORGE:
Excuse me, Mrs. Forrest.
STAGE MANAGER:
As Mrs. Forrest.
Go out and play in the fields, young man. You got no business playing baseball on Main Street.
GEORGE:
Awfully sorry, Mrs. Forrest.—Hello, Emily.
EMILY:
H'lo.
GEORGE:
You made a fine speech in class.
EMILY:
Well . . . I was really ready to make a speech about the Monroe Doctrine, but at the last minute Miss Corcoran made me talk about the Louisiana Purchase instead. I worked an awful long time on both of them.
GEORGE:
Gee, it's funny, Emily. From my window up there I can just see your head nights when you're doing your homework over in your room.
EMILY:
Why, can you?
GEORGE:
You certainly do stick to it, Emily. I don't see how you can sit still that long. I guess you like school.
EMILY:
Well, I always feel it's something you have to go through.
GEORGE:
Yeah.
EMILY:
I don't mind it really. It passes the time.
GEORGE:
Yeah.—Emily, what do you think? We might work out a kinda telegraph from your window to mine; and once in a while you could give me a kinda hint or two about one of those algebra problems. I don't mean the answers, Emily, of course not . . . just some little hint . . .
EMILY:
Oh, I think hints are allowed.—So—ah—if you get stuck, George, you whistle to me; and I'll give you some hints.
GEORGE:
Emily, you're just naturally bright, I guess.
EMILY:
I figure that it's just the way a person's born.
GEORGE:
Yeah. But, you see, I want to be a farmer, and my Uncle Luke says whenever I'm ready I can come over and work on his farm and if I'm any good I can just gradually have it.
EMILY:
You mean the house and everything?
Enter MRS. WEBB with a large bowl and sits on the bench by her trellis.
GEORGE:
Yeah. Well, thanks . . . I better be getting out to the baseball field. Thanks for the talk, Emily.—Good afternoon, Mrs. Webb.
MRS. WEBB:
Good afternoon, George.
GEORGE:
So long, Emily.
EMILY:
So long, George.
MRS. WEBB:
Emily, come and help me string these beans for the winter. George Gibbs let himself have a real conversation, didn't he? Why, he's growing up. How old would George be?
EMILY:
I don't know.
MRS. WEBB:
Let's see. He must be almost sixteen.
EMILY:
Mama, I made a speech in class today and I was very good.
MRS. WEBB:
You must recite it to your father at supper. What was it about?
EMILY:
The Louisiana Purchase. It was like silk off a spool. I'm going to make speeches all my life.—Mama, are these big enough?
MRS. WEBB:
Try and get them a little bigger if you can.
EMILY:
Mama, will you answer me a question, serious?
MRS. WEBB:
Seriously, dear—not serious.
EMILY:
Seriously,—will you?
MRS. WEBB:
Of course, I will.
EMILY:
Mama, am I good looking?
MRS. WEBB:
Yes, of course you are. All my children have got good features; I'd be ashamed if they hadn't.
EMILY:
Oh, Mama, that's not what I mean. What I mean is: am I pretty?
MRS. WEBB:
I've already told you, yes. Now that's enough of that. You have a nice young pretty face. I never heard of such foolishness.
EMILY:
Oh, Mama, you never tell us the truth about anything.
MRS. WEBB:
I am telling you the truth.
EMILY:
Mama, were you pretty?
MRS. WEBB:
Yes, I was, if I do say it. I was the prettiest girl in town next to Mamie Cartwright.
EMILY:
But, Mama, you've got to say something about me. Am I pretty enough . . . to get anybody . . . to get people interested in me?
MRS. WEBB:
Emily, you make me tired. Now stop it. You're pretty enough for all normal purposes.—Come along now and bring that bowl with you.
EMILY:
Oh, Mama, you're no help at all.
STAGE MANAGER:
Thank you. Thank you! That'll do. We'll have to interrupt again here. Thank you, Mrs. Webb; thank you, Emily.
MRS. WEBB and EMILY withdraw.
There are some more things we want to explore about this town.
He comes to the center of the stage. During the following speech the lights gradually dim to darkness, leaving only a spot on him.
I think this is a good time to tell you that the Cartwright interests have just begun building a new bank in Grover's Corners—had to go to Vermont for the marble, sorry to say. And they've asked a friend of mine what they should put in the cornerstone for people to dig up . . . a thousand years from now. . . . Of course, they've put in a copy of the New York Times and a copy of Mr. Webb's Sentinel. . . . We're kind of interested in this because some scientific fellas have found a way of painting all that reading matter with a glue—a silicate glue—that'll make it keep a thousand—two thousand years.
We're putting in a Bible . . . and the Constitution of the United States—and a copy of William Shakespeare's plays. What do you say, folks? What do you think?
Y'know—Babylon once had two million people in it, and all we know about 'em is the names of the kings and some copies of wheat contracts . . . and contracts for the sale of slaves. Yet every night all those families sat down to supper, and the father came home from his work, and the smoke went up the chimney,—same as here. And even in Greece and Rome, all we know about the real life of the people is what we can piece together out of the joking poems and the comedies they wrote for the theatre back then.
So I'm going to have a copy of this play put in the cornerstone and the people a thousand years from now'll know a few simple facts about us—more than the Treaty of Versailles and the Lindbergh flight.
See what I mean?
So—people a thousand years from now—this is the way we were in the provinces north of New York at the beginning of the twentieth century.—This is the way we were: in our growing up and in our marrying and in our living and in our dying.
A choir partially concealed in the orchestra pit has begun singing "Blessed Be the Tie That Binds."
SIMON STIMSON stands directing them.
Two ladders have been pushed onto the stage; they serve as indication of the second story in the Gibbs and Webb houses. GEORGE and EMILY mount them, and apply themselves to their schoolwork.
DR. GIBBS has entered and is seated in his kitchen reading.
Well!—good deal of time's gone by. It's evening.
You can hear choir practice going on in the Congregational Church.
The children are at home doing their schoolwork.
The day's running down like a tired clock.
SIMON STIMSON:
Now look here, everybody. Music come into the world to give pleasure.—Softer! Softer! Get it out of your heads that music's only good when it's loud. You leave loudness to the Methodists. You couldn't beat 'em, even if you wanted to. Now again. Tenors!
GEORGE:
Hssst! Emily!
EMILY:
Hello.
GEORGE:
Hello!
EMILY:
I can't work at all. The moonlight's so terrible.
GEORGE:
Emily, did you get the third problem?
EMILY:
Which?
GEORGE:
The third?
EMILY:
Why, yes, George—that's the easiest of them all.
GEORGE:
I don't see it. Emily, can you give me a hint?
EMILY:
I'll tell you one thing: the answer's in yards.
GEORGE:
!!! In yards? How do you mean?
EMILY:
In square yards.
GEORGE:
Oh . . . in square yards.
EMILY:
Yes, George, don't you see?
GEORGE:
Yeah.
EMILY:
In square yards of wallpaper.
GEORGE:
Wallpaper,—oh, I see. Thanks a lot, Emily.
EMILY:
You're welcome. My, isn't the moonlight terrible? And choir practice going on.—I think if you hold your breath you can hear the train all the way to Contoocook. Hear it?
GEORGE:
M-m-m—What do you know!
EMILY:
Well, I guess I better go back and try to work.
GEORGE:
Good night, Emily. And thanks.
EMILY:
Good night, George.
SIMON STIMSON:
Before I forget it: how many of you will be able to come in Tuesday afternoon and sing at Fred Hersey's wedding?—show your hands. That'll be fine; that'll be right nice. We'll do the same music we did for Jane Trowbridge's last month.
—Now we'll do: "Art Thou Weary; Art Thou Languid?" It's a question, ladies and gentlemen, make it talk. Ready.
DR. GIBBS:
Oh, George, can you come down a minute?
GEORGE:
Yes, Pa.
He descends the ladder.
DR. GIBBS:
Make yourself comfortable, George; I'll only keep you a minute. George, how old are you?
GEORGE:
I? I'm sixteen, almost seventeen.
DR. GIBBS:
What do you want to do after school's over?
GEORGE:
Why, you know, Pa. I want to be a farmer on Uncle Luke's farm.
DR. GIBBS:
You'll be willing, will you, to get up early and milk and feed the stock . . . and you'll be able to hoe and hay all day?
GEORGE:
Sure, I will. What are you . . . what do you mean, Pa?
DR. GIBBS:
Well, George, while I was in my office today I heard a funny sound . . . and what do you think it was? It was your mother chopping wood. There you see your mother—getting up early; cooking meals all day long; washing and ironing;—and still she has to go out in the back yard and chop wood. I suppose she just got tired of asking you. She just gave up and decided it was easier to do it herself. And you eat her meals, and put on the clothes she keeps nice for you, and you run off and play baseball,—like she's some hired girl we keep around the house but that we don't like very much. Well, I knew all I had to do was call your attention to it. Here's a handkerchief, son. George, I've decided to raise your spending money twenty-five cents a week. Not, of course, for chopping wood for your mother, because that's a present you give her, but because you're getting older—and I imagine there are lots of things you must find to do with it.
GEORGE:
Thanks, Pa.
DR. GIBBS:
Let's see—tomorrow's your payday. You can count on it—Hmm. Probably Rebecca'll feel she ought to have some more too. Wonder what could have happened to your mother. Choir practice never was as late as this before.
GEORGE:
It's only half past eight, Pa.
DR. GIBBS:
I don't know why she's in that old choir. She hasn't any more voice than an old crow. . . . Traipsin' around the streets at this hour of the night . . . Just about time you retired, don't you think?
GEORGE:
Yes, Pa.
GEORGE mounts to his place on the ladder.
Laughter and good nights can be heard on stage left and presently MRS. GIBBS, MRS. SOAMES and MRS. WEBB come down Main Street. When they arrive at the corner of the stage they stop.
MRS. SOAMES:
Good night, Martha. Good night, Mr. Foster.
MRS. WEBB:
I'll tell Mr. Webb; I know he'll want to put it in the paper.
MRS. GIBBS:
My, it's late!
MRS. SOAMES:
Good night, Irma.
MRS. GIBBS:
Real nice choir practice, wa'n't it? Myrtle Webb! Look at that moon, will you! Tsk-tsk-tsk. Potato weather, for sure.
They are silent a moment, gazing up at the moon.
MRS. SOAMES:
Naturally I didn't want to say a word about it in front of those others, but now we're alone—really, it's the worst scandal that ever was in this town!
MRS. GIBBS:
What?
MRS. SOAMES:
Simon Stimson!
MRS. GIBBS:
Now, Louella!
MRS. SOAMES:
But, Julia! To have the organist of a church drink and drunk year after year. You know he was drunk tonight.
MRS. GIBBS:
Now, Louella! We all know about Mr. Stimson, and we all know about the troubles he's been through, and Dr. Ferguson knows too, and if Dr. Ferguson keeps him on there in his job the only thing the rest of us can do is just not to notice it.
MRS. SOAMES:
Not to notice it! But it's getting worse.
MRS. WEBB:
No, it isn't, Louella. It's getting better. I've been in that choir twice as long as you have. It doesn't happen anywhere near so often. . . . My, I hate to go to bed on a night like this.—I better hurry. Those children'll be sitting up till all hours. Good night, Louella.
They all exchange good nights. She hurries downstage, enters her house and disappears.
MRS. GIBBS:
Can you get home safe, Louella?
MRS. SOAMES:
It's as bright as day. I can see Mr. Soames scowling at the window now. You'd think we'd been to a dance the way the menfolk carry on.
More good nights. MRS. GIBBS arrives at her home and passes through the trellis into the kitchen.
MRS. GIBBS:
Well, we had a real good time.
DR. GIBBS:
You're late enough.
MRS. GIBBS:
Why, Frank, it ain't any later 'n usual.
DR. GIBBS:
And you stopping at the corner to gossip with a lot of hens.
MRS. GIBBS:
Now, Frank, don't be grouchy. Come out and smell the heliotrope in the moonlight.
They stroll out arm in arm along the footlights.
Isn't that wonderful? What did you do all the time I was away?
DR. GIBBS:
Oh, I read—as usual. What were the girls gossiping about tonight?
MRS. GIBBS:
Well, believe me, Frank—there is something to gossip about.
DR. GIBBS:
Hmm! Simon Stimson far gone, was he?
MRS. GIBBS:
Worst I've ever seen him. How'll that end, Frank? Dr. Ferguson can't forgive him forever.
DR. GIBBS:
I guess I know more about Simon Stimson's affairs than anybody in this town. Some people ain't made for small-town life. I don't know how that'll end; but there's nothing we can do but just leave it alone. Come, get in.
MRS. GIBBS:
No, not yet . . . Frank, I'm worried about you.
DR. GIBBS:
What are you worried about?
MRS. GIBBS:
I think it's my duty to make plans for you to get a real rest and change. And if I get that legacy, well, I'm going to insist on it.
DR. GIBBS:
Now, Julia, there's no sense in going over that again.
MRS. GIBBS:
Frank, you're just unreasonable!
DR. GIBBS:
Starting into the house.
Come on, Julia, it's getting late. First thing you know you'll catch cold. I gave George a piece of my mind tonight. I reckon you'll have your wood chopped for a while anyway. No, no, start getting upstairs.
MRS. GIBBS:
Oh, dear. There's always so many things to pick up, seems like. You know, Frank, Mrs. Fairchild always locks her front door every night. All those people up that part of town do.
DR. GIBBS:
Blowing out the lamp.
They're all getting citified, that's the trouble with them. They haven't got nothing fit to burgle and everybody knows it.
They disappear.
REBECCA climbs up the ladder beside GEORGE.
GEORGE:
Get out, Rebecca. There's only room for one at this window. You're always spoiling everything.
REBECCA:
Well, let me look just a minute.
GEORGE:
Use your own window.
REBECCA:
I did, but there's no moon there. . . . George, do you know what I think, do you? I think maybe the moon's getting nearer and nearer and there'll be a big 'splosion.
GEORGE:
Rebecca, you don't know anything. If the moon were getting nearer, the guys that sit up all night with telescopes would see it first and they'd tell about it, and it'd be in all the newspapers.
REBECCA:
George, is the moon shining on South America, Canada and half the whole world?
GEORGE:
Well—prob'ly is.
The STAGE MANAGER strolls on.
Pause. The sound of crickets is heard.
STAGE MANAGER:
Nine thirty. Most of the lights are out. No, there's Constable Warren trying a few doors on Main Street. And here comes Editor Webb, after putting his newspaper to bed.
MR. WARREN, an elderly policeman, comes along Main Street from the right, MR. WEBB from the left.
MR. WEBB:
Good evening, Bill.
CONSTABLE WARREN:
Evenin', Mr. Webb.
MR. WEBB:
Quite a moon!
CONSTABLE WARREN:
Yepp.
MR. WEBB:
All quiet tonight?
CONSTABLE WARREN:
Simon Stimson is rollin' around a little. Just saw his wife movin' out to hunt for him so I looked the other way—there he is now.
SIMON STIMSON comes down Main Street from the left, only a trace of unsteadiness in his walk.
MR. WEBB:
Good evening, Simon . . . Town seems to have settled down for the night pretty well. . . .
SIMON STIMSON comes up to him and pauses a moment and stares at him, swaying slightly.
Good evening . . . Yes, most of the town's settled down for the night, Simon. . . . I guess we better do the same. Can I walk along a ways with you?
SIMON STIMSON continues on his way without a word and disappears at the right.
Good night.
CONSTABLE WARREN:
I don't know how that's goin' to end, Mr. Webb.
MR. WEBB:
Well, he's seen a peck of trouble, one thing after another. . . . Oh, Bill . . . if you see my boy smoking cigarettes, just give him a word, will you? He thinks a lot of you, Bill.
CONSTABLE WARREN:
I don't think he smokes no cigarettes, Mr. Webb. Leastways, not more'n two or three a year.
MR. WEBB:
Hm . . . I hope not.—Well, good night, Bill.
CONSTABLE WARREN:
Good night, Mr. Webb.
Exit.
MR. WEBB:
Who's that up there? Is that you, Myrtle?
EMILY:
No, it's me, Papa.
MR. WEBB:
Why aren't you in bed?
EMILY:
I don't know. I just can't sleep yet, Papa. The moonlight's so won-derful. And the smell of Mrs. Gibbs' heliotrope. Can you smell it?
MR. WEBB:
Hm . . . Yes. Haven't any troubles on your mind, have you, Emily?
EMILY:
Troubles, Papa? No.
MR. WEBB:
Well, enjoy yourself, but don't let your mother catch you. Good night, Emily.
EMILY:
Good night, Papa.
MR. WEBB crosses into the house, whistling "Blessed Be the Tie That Binds" and disappears.
REBECCA:
I never told you about that letter Jane Crofut got from her minister when she was sick. He wrote Jane a letter and on the envelope the address was like this: It said: Jane Crofut; The Crofut Farm; Grover's Corners; Sutton County; New Hampshire; United States of America.
GEORGE:
What's funny about that?
REBECCA:
But listen, it's not finished: the United States of America; Continent of North America; Western Hemisphere; the Earth; the Solar System; the Universe; the Mind of God—that's what it said on the envelope.
GEORGE:
What do you know!
REBECCA:
And the postman brought it just the same.
GEORGE:
What do you know!
STAGE MANAGER:
That's the end of the First Act, friends. You can go and smoke now, those that smoke.
Act II
The tables and chairs of the two kitchens are still on the stage.
The ladders and the small bench have been withdrawn.
The STAGE MANAGER has been at his accustomed place watching the audience return to its seats.
STAGE MANAGER:
Three years have gone by.
Yes, the sun's come up over a thousand times.
Summers and winters have cracked the mountains a little bit more and the rains have brought down some of the dirt.
Some babies that weren't even born before have begun talking regular sentences already; and a number of people who thought they were right young and spry have noticed that they can't bound up a flight of stairs like they used to, without their heart fluttering a little.
All that can happen in a thousand days.
Nature's been pushing and contriving in other ways, too: a number of young people fell in love and got married.
Yes, the mountain got bit away a few fractions of an inch; millions of gallons of water went by the mill; and here and there a new home was set up under a roof.
Almost everybody in the world gets married,—you know what I mean? In our town there aren't hardly any exceptions. Most everybody in the world climbs into their graves married.
The First Act was called the Daily Life. This act is called Love and Marriage. There's another act coming after this: I reckon you can guess what that's about.
So:
It's three years later. It's 1904.
It's July 7th, just after High School Commencement.
That's the time most of our young people jump up and get married.
Soon as they've passed their last examinations in solid geometry and Cicero's Orations, looks like they suddenly feel themselves fit to be married.
It's early morning. Only this time it's been raining. It's been pouring and thundering.
Mrs. Gibbs' garden, and Mrs. Webb's here: drenched.
All those bean poles and pea vines: drenched.
All yesterday over there on Main Street, the rain looked like curtains being blown along.
Hm . . . it may begin again any minute.
There! You can hear the 5:45 for Boston.
MRS. GIBBS and MRS. WEBB enter their kitchens and start the day as in the First Act.
And there's Mrs. Gibbs and Mrs. Webb come down to make breakfast, just as though it were an ordinary day. I don't have to point out to the women in my audience that those ladies they see before them, both of those ladies cooked three meals a day—one of 'em for twenty years, the other for forty—and no summer vacation. They brought up two children apiece, washed, cleaned the house,—and never a nervous breakdown.
It's like what one of those Middle West poets said: You've got to love life to have life, and you've got to have life to love life. . . . It's what they call a vicious circle.
HOWIE NEWSOME:
Off stage left.
Giddap, Bessie!
STAGE MANAGER:
Here comes Howie Newsome delivering the milk. And there's Si Crowell delivering the papers like his brother before him.
SI CROWELL has entered hurling imaginary newspapers into doorways; HOWIE NEWSOME has come along Main Street with Bessie.
SI CROWELL:
Morning, Howie.
HOWIE NEWSOME:
Morning, Si.—Anything in the papers I ought to know?
SI CROWELL:
Nothing much, except we're losing about the best baseball pitcher Grover's Corners ever had—George Gibbs.
HOWIE NEWSOME:
Reckon he is.
SI CROWELL:
He could hit and run bases, too.
HOWIE NEWSOME:
Yep. Mighty fine ball player.—Whoa! Bessie! I guess I can stop and talk if I've a mind to!
SI CROWELL:
I don't see how he could give up a thing like that just to get married. Would you, Howie?
HOWIE NEWSOME:
Can't tell, Si. Never had no talent that way.
CONSTABLE WARREN enters. They exchange good mornings.
You're up early, Bill.
CONSTABLE WARREN:
Seein' if there's anything I can do to prevent a flood. River's been risin' all night.
HOWIE NEWSOME:
Si Crowell's all worked up here about George Gibbs' retiring from baseball.
CONSTABLE WARREN:
Yes, sir; that's the way it goes. Back in '84 we had a player, Si—even George Gibbs couldn't touch him. Name of Hank Todd. Went down to Maine and become a parson. Wonderful ball player.—Howie, how does the weather look to you?
HOWIE NEWSOME:
Oh, 'tain't bad. Think maybe it'll clear up for good.
CONSTABLE WARREN and SI CROWELL continue on their way. HOWIE NEWSOME brings the milk first to Mrs. Gibbs' house. She meets him by the trellis.
MRS. GIBBS:
Good morning, Howie. Do you think it's going to rain again?
HOWIE NEWSOME:
Morning, Mrs. Gibbs. It rained so heavy, I think maybe it'll clear up.
MRS. GIBBS:
Certainly hope it will.
HOWIE NEWSOME:
How much did you want today?
MRS. GIBBS:
I'm going to have a houseful of relations, Howie. Looks to me like I'll need three-a-milk and two-a-cream.
HOWIE NEWSOME:
My wife says to tell you we both hope they'll be very happy, Mrs. Gibbs. Know they will.
MRS. GIBBS:
Thanks a lot, Howie. Tell your wife I hope she gits there to the wedding.
HOWIE NEWSOME:
Yes, she'll be there; she'll be there if she kin.
HOWIE NEWSOME crosses to Mrs. Webb's house.
Morning, Mrs. Webb.
MRS. WEBB:
Oh, good morning, Mr. Newsome. I told you four quarts of milk, but I hope you can spare me another.
HOWIE NEWSOME:
Yes'm . . . and the two of cream.
MRS. WEBB:
Will it start raining again, Mr. Newsome?
HOWIE NEWSOME:
Well. Just sayin' to Mrs. Gibbs as how it may lighten up. Mrs. Newsome told me to tell you as how we hope they'll both be very happy, Mrs. Webb. Know they will.
MRS. WEBB:
Thank you, and thank Mrs. Newsome and we're counting on seeing you at the wedding.
HOWIE NEWSOME:
Yes, Mrs. Webb. We hope to git there. Couldn't miss that. Come on, Bessie.
Exit HOWIE NEWSOME.
DR. GIBBS descends in shirt sleeves, and sits down at his breakfast table.
DR. GIBBS:
Well, Ma, the day has come. You're losin' one of your chicks.
MRS. GIBBS:
Frank Gibbs, don't you say another word. I feel like crying every minute. Sit down and drink your coffee.
DR. GIBBS:
The groom's up shaving himself—only there ain't an awful lot to shave. Whistling and singing, like he's glad to leave us.—Every now and then he says "I do" to the mirror, but it don't sound convincing to me.
MRS. GIBBS:
I declare, Frank, I don't know how he'll get along. I've arranged his clothes and seen to it he's put warm things on,—Frank! they're too young. Emily won't think of such things. He'll catch his death of cold within a week.
DR. GIBBS:
I was remembering my wedding morning, Julia.
MRS. GIBBS:
Now don't start that, Frank Gibbs.
DR. GIBBS:
I was the scaredest young fella in the State of New Hampshire. I thought I'd make a mistake for sure. And when I saw you comin' down that aisle I thought you were the prettiest girl I'd ever seen, but the only trouble was that I'd never seen you before. There I was in the Congregational Church marryin' a total stranger.
MRS. GIBBS:
And how do you think I felt!—Frank, weddings are perfectly awful things. Farces,—that's what they are!
She puts a plate before him.
Here, I've made something for you.
DR. GIBBS:
Why, Julia Hersey—French toast!
MRS. GIBBS:
'Tain't hard to make and I had to do something.
Pause. DR. GIBBS pours on the syrup.
DR. GIBBS:
How'd you sleep last night, Julia?
MRS. GIBBS:
Well, I heard a lot of the hours struck off.
DR. GIBBS:
Ye-e-s! I get a shock every time I think of George setting out to be a family man—that great gangling thing!—I tell you Julia, there's nothing so terrifying in the world as a son. The relation of father and son is the darndest, awkwardest—
MRS. GIBBS:
Well, mother and daughter's no picnic, let me tell you.
DR. GIBBS:
They'll have a lot of troubles, I suppose, but that's none of our business. Everybody has a right to their own troubles.
MRS. GIBBS:
At the table, drinking her coffee, meditatively.
Yes . . . people are meant to go through life two by two. 'Tain't natural to be lonesome.
Pause. DR. GIBBS starts laughing.
DR. GIBBS:
Julia, do you know one of the things I was scared of when I married you?
MRS. GIBBS:
Oh, go along with you!
DR. GIBBS:
I was afraid we wouldn't have material for conversation more'n'd last us a few weeks.
Both laugh.
I was afraid we'd run out and eat our meals in silence, that's a fact.—Well, you and I been conversing for twenty years now without any noticeable barren spells.
MRS. GIBBS:
Well,—good weather, bad weather—'tain't very choice, but I always find something to say.
She goes to the foot of the stairs.
Did you hear Rebecca stirring around upstairs?
DR. GIBBS:
No. Only day of the year Rebecca hasn't been managing everybody's business up there. She's hiding in her room.—I got the impression she's crying.
MRS. GIBBS:
Lord's sakes!—This has got to stop.—Rebecca! Rebecca! Come and get your breakfast.
GEORGE comes rattling down the stairs, very brisk.
GEORGE:
Good morning, everybody. Only five more hours to live.
Makes the gesture of cutting his throat, and a loud "k-k-k," and starts through the trellis.
MRS. GIBBS:
George Gibbs, where are you going?
GEORGE:
Just stepping across the grass to see my girl.
MRS. GIBBS:
Now, George! You put on your overshoes. It's raining torrents. You don't go out of this house without you're prepared for it.
GEORGE:
Aw, Ma. It's just a step!
MRS. GIBBS:
George! You'll catch your death of cold and cough all through the service.
DR. GIBBS:
George, do as your mother tells you!
DR. GIBBS goes upstairs.
GEORGE returns reluctantly to the kitchen and pantomimes putting on overshoes.
MRS. GIBBS:
From tomorrow on you can kill yourself in all weathers, but while you're in my house you'll live wisely, thank you.—Maybe Mrs. Webb isn't used to callers at seven in the morning.—Here, take a cup of coffee first.
GEORGE:
Be back in a minute.
He crosses the stage, leaping over the puddles.
Good morning, Mother Webb.
MRS. WEBB:
Goodness! You frightened me!—Now, George, you can come in a minute out of the wet, but you know I can't ask you in.
GEORGE:
Why not—?
MRS. WEBB:
George, you know 's well as I do: the groom can't see his bride on his wedding day, not until he sees her in church.
GEORGE:
Aw!—that's just a superstition.—Good morning, Mr. Webb.
Enter MR. WEBB.
MR. WEBB:
Good morning, George.
GEORGE:
Mr. Webb, you don't believe in that superstition, do you?
MR. WEBB:
There's a lot of common sense in some superstitions, George.
He sits at the table, facing right.
MRS. WEBB:
Millions have folla'd it, George, and you don't want to be the first to fly in the face of custom.
GEORGE:
How is Emily?
MRS. WEBB:
She hasn't waked up yet. I haven't heard a sound out of her.
GEORGE:
Emily's asleep!!!
MRS. WEBB:
No wonder! We were up 'til all hours, sewing and packing. Now I'll tell you what I'll do; you set down here a minute with Mr. Webb and drink this cup of coffee; and I'll go upstairs and see she doesn't come down and surprise you. There's some bacon, too; but don't be long about it.
Exit MRS. WEBB.
Embarrassed silence.
MR. WEBB dunks doughnuts in his coffee.
More silence.
MR. WEBB:
Suddenly and loudly.
Well, George, how are you?
GEORGE:
Startled, choking over his coffee.
Oh, fine, I'm fine.
Pause.
Mr. Webb, what sense could there be in a superstition like that?
MR. WEBB:
Well, you see,—on her wedding morning a girl's head's apt to be full of . . . clothes and one thing and another. Don't you think that's probably it?
GEORGE:
Ye-e-s. I never thought of that.
MR. WEBB:
A girl's apt to be a mite nervous on her wedding day.
Pause.
GEORGE:
I wish a fellow could get married without all that marching up and down.
MR. WEBB:
Every man that's ever lived has felt that way about it, George; but it hasn't been any use. It's the womenfolk who've built up weddings, my boy. For a while now the women have it all their own. A man looks pretty small at a wedding, George. All those good women standing shoulder to shoulder making sure that the knot's tied in a mighty public way.
GEORGE:
But . . . you believe in it, don't you, Mr. Webb?
MR. WEBB:
With alacrity.
Oh, yes; oh, yes. Don't you misunderstand me, my boy. Marriage is a wonderful thing,—wonderful thing. And don't you forget that, George.
GEORGE:
No, sir.—Mr. Webb, how old were you when you got married?
MR. WEBB:
Well, you see: I'd been to college and I'd taken a little time to get settled. But Mrs. Webb—she wasn't much older than what Emily is. Oh, age hasn't much to do with it, George,—not compared with . . . uh . . . other things.
GEORGE:
What were you going to say, Mr. Webb?
MR. WEBB:
Oh, I don't know.—Was I going to say something?
Pause.
George, I was thinking the other night of some advice my father gave me when I got married. Charles, he said, Charles, start out early showing who's boss, he said. Best thing to do is to give an order, even if it don't make sense; just so she'll learn to obey. And he said: if anything about your wife irritates you—her conversation, or anything—just get up and leave the house. That'll make it clear to her, he said. And, oh, yes! he said never, never let your wife know how much money you have, never.
GEORGE:
Well, Mr. Webb . . . I don't think I could . . .
MR. WEBB:
So I took the opposite of my father's advice and I've been happy ever since. And let that be a lesson to you, George, never to ask advice on personal matters.—George, are you going to raise chickens on your farm?
GEORGE:
What?
MR. WEBB:
Are you going to raise chickens on your farm?
GEORGE:
Uncle Luke's never been much interested, but I thought—
MR. WEBB:
A book came into my office the other day, George, on the Philo System of raising chickens. I want you to read it. I'm thinking of beginning in a small way in the back yard, and I'm going to put an incubator in the cellar—
Enter MRS. WEBB.
MRS. WEBB:
Charles, are you talking about that old incubator again? I thought you two'd be talking about things worth while.
MR. WEBB:
Bitingly.
Well, Myrtle, if you want to give the boy some good advice, I'll go upstairs and leave you alone with him.
MRS. WEBB:
Pulling GEORGE up.
George, Emily's got to come downstairs and eat her breakfast. She sends you her love but she doesn't want to lay eyes on you. Good-by.
GEORGE:
Good-by.
GEORGE crosses the stage to his own home, bewildered and crestfallen. He slowly dodges a puddle and disappears into his house.
MR. WEBB:
Myrtle, I guess you don't know about that older superstition.
MRS. WEBB:
What do you mean, Charles?
MR. WEBB:
Since the cave men: no bridegroom should see his father-in-law on the day of the wedding, or near it. Now remember that.
Both leave the stage.
STAGE MANAGER:
Thank you very much, Mr. and Mrs. Webb.—Now I have to interrupt again here. You see, we want to know how all this began—this wedding, this plan to spend a lifetime together. I'm awfully interested in how big things like that begin.
You know how it is: you're twenty-one or twenty-two and you make some decisions; then whisssh! you're seventy: you've been a lawyer for fifty years, and that white-haired lady at your side has eaten over fifty thousand meals with you.
How do such things begin?
George and Emily are going to show you now the conversation they had when they first knew that . . . that . . . as the saying goes . . . they were meant for one another.
But before they do it I want you to try and remember what it was like to have been very young.
And particularly the days when you were first in love; when you were like a person sleepwalking, and you didn't quite see the street you were in, and didn't quite hear everything that was said to you.
You're just a little bit crazy. Will you remember that, please?
Now they'll be coming out of high school at three o'clock. George has just been elected President of the Junior Class, and as it's June, that means he'll be President of the Senior Class all next year. And Emily's just been elected Secretary and Treasurer.
I don't have to tell you how important that is.
He places a board across the backs of two chairs, which he takes from those at the Gibbs family's table. He brings two high stools from the wings and places them behind the board. Persons sitting on the stools will be facing the audience. This is the counter of Mr. Morgan's drugstore. The sounds of young people's voices are heard off left.
Yepp,—there they are coming down Main Street now.
EMILY, carrying an armful of—imaginary—schoolbooks, comes along Main Street from the left.
EMILY:
I can't, Louise. I've got to go home. Good-by. Oh, Ernestine! Ernestine! Can you come over tonight and do Latin? Isn't that Cicero the worst thing—! Tell your mother you have to. G'by. G'by, Helen. G'by, Fred.
GEORGE, also carrying books, catches up with her.
GEORGE:
Can I carry your books home for you, Emily?
EMILY:
Coolly.
Why . . . uh . . . Thank you. It isn't far.
She gives them to him.
GEORGE:
Excuse me a minute, Emily.—Say, Bob, if I'm a little late, start practice anyway. And give Herb some long high ones.
EMILY:
Good-by, Lizzy.
GEORGE:
Good-by, Lizzy.—I'm awfully glad you were elected, too, Emily.
EMILY:
Thank you.
They have been standing on Main Street, almost against the back wall. They take the first steps toward the audience when GEORGE stops and says:
GEORGE:
Emily, why are you mad at me?
EMILY:
I'm not mad at you.
GEORGE:
You've been treating me so funny lately.
EMILY:
Well, since you ask me, I might as well say it right out, George,—
She catches sight of a teacher passing.
Good-by, Miss Corcoran.
GEORGE:
Good-by, Miss Corcoran.—Wha—what is it?
EMILY:
Not scoldingly; finding it difficult to say.
I don't like the whole change that's come over you in the last year. I'm sorry if that hurts your feelings, but I've got to—tell the truth and shame the devil.
GEORGE:
A change?—Wha—what do you mean?
EMILY:
Well, up to a year ago I used to like you a lot. And I used to watch you as you did everything . . . because we'd been friends so long . . . and then you began spending all your time at baseball . . . and you never stopped to speak to anybody any more. Not even to your own family you didn't . . . and, George, it's a fact, you've got awful conceited and stuck-up, and all the girls say so. They may not say so to your face, but that's what they say about you behind your back, and it hurts me to hear them say it, but I've got to agree with them a little. I'm sorry if it hurts your feelings . . . but I can't be sorry I said it.
GEORGE:
I . . . I'm glad you said it, Emily. I never thought that such a thing was happening to me. I guess it's hard for a fella not to have faults creep into his character.
They take a step or two in silence, then stand still in misery.
EMILY:
I always expect a man to be perfect and I think he should be.
GEORGE:
Oh . . . I don't think it's possible to be perfect, Emily.
EMILY:
Well, my father is, and as far as I can see your father is. There's no reason on earth why you shouldn't be, too.
GEORGE:
Well, I feel it's the other way round. That men aren't naturally good; but girls are.
EMILY:
Well, you might as well know right now that I'm not perfect. It's not as easy for a girl to be perfect as a man, because we girls are more—more—nervous.—Now I'm sorry I said all that about you. I don't know what made me say it.
GEORGE:
Emily,—
EMILY:
Now I can see it's not the truth at all. And I suddenly feel that it isn't important, anyway.
GEORGE:
Emily . . . would you like an ice-cream soda, or something, before you go home?
EMILY:
Well, thank you . . . I would.
They advance toward the audience and make an abrupt right turn, opening the door of Morgan's drugstore. Under strong emotion, EMILY keeps her face down. GEORGE speaks to some passers-by.
GEORGE:
Hello, Stew,—how are you?—Good afternoon, Mrs. Slocum.
The STAGE MANAGER, wearing spectacles and assuming the role of Mr. Morgan, enters abruptly from the right and stands between the audience and the counter of his soda fountain.
STAGE MANAGER:
Hello, George. Hello, Emily.—What'll you have?—Why, Emily Webb,—what you been crying about?
GEORGE:
He gropes for an explanation.
She . . . she just got an awful scare, Mr. Morgan. She almost got run over by that hardware-store wagon. Everybody says that Tom Huckins drives like a crazy man.
STAGE MANAGER:
Drawing a drink of water.
Well, now! You take a drink of water, Emily. You look all shook up. I tell you, you've got to look both ways before you cross Main Street these days. Gets worse every year.—What'll you have?
EMILY:
I'll have a strawberry phosphate, thank you, Mr. Morgan.
GEORGE:
No, no, Emily. Have an ice-cream soda with me. Two strawberry ice-cream sodas, Mr. Morgan.
STAGE MANAGER:
Working the faucets.
Two strawberry ice-cream sodas, yes sir. Yes, sir. There are a hundred and twenty-five horses in Grover's Corners this minute I'm talking to you. State Inspector was in here yesterday. And now they're bringing in these auto-mo-biles, the best thing to do is to just stay home. Why, I can remember when a dog could go to sleep all day in the middle of Main Street and nothing come along to disturb him.
He sets the imaginary glasses before them.
There they are. Enjoy 'em.
He sees a customer, right.
Yes, Mrs. Ellis. What can I do for you?
He goes out right.
EMILY:
They're so expensive.
GEORGE:
No, no,—don't you think of that. We're celebrating our election. And then do you know what else I'm celebrating?
EMILY:
N-no.
GEORGE:
I'm celebrating because I've got a friend who tells me all the things that ought to be told me.
EMILY:
George, please don't think of that. I don't know why I said it. It's not true. You're—
GEORGE:
No, Emily, you stick to it. I'm glad you spoke to me like you did. But you'll see: I'm going to change so quick—you bet I'm going to change. And, Emily, I want to ask you a favor.
EMILY:
What?
GEORGE:
Emily, if I go away to State Agriculture College next year, will you write me a letter once in a while?
EMILY:
I certainly will. I certainly will, George . . .
Pause. They start sipping the sodas through the straws.
It certainly seems like being away three years you'd get out of touch with things. Maybe letters from Grover's Corners wouldn't be so interesting after a while. Grover's Corners isn't a very important place when you think of all—New Hampshire; but I think it's a very nice town.
GEORGE:
The day wouldn't come when I wouldn't want to know everything that's happening here. I know that's true, Emily.
EMILY:
Well, I'll try to make my letters interesting.
Pause.
GEORGE:
Y'know. Emily, whenever I meet a farmer I ask him if he thinks it's important to go to Agriculture School to be a good farmer.
EMILY:
Why, George—
GEORGE:
Yeah, and some of them say that it's even a waste of time. You can get all those things, anyway, out of the pamphlets the government sends out. And Uncle Luke's getting old,—he's about ready for me to start in taking over his farm tomorrow, if I could.
EMILY:
My!
GEORGE:
And, like you say, being gone all that time . . . in other places and meeting other people . . . Gosh, if anything like that can happen I don't want to go away. I guess new people aren't any better than old ones. I'll bet they almost never are. Emily . . . I feel that you're as good a friend as I've got. I don't need to go and meet the people in other towns.
EMILY:
But, George, maybe it's very important for you to go and learn all that about—cattle judging and soils and those things. . . . Of course, I don't know.
GEORGE:
After a pause, very seriously.
Emily, I'm going to make up my mind right now. I won't go. I'll tell Pa about it tonight.
EMILY:
Why, George, I don't see why you have to decide right now. It's a whole year away.
GEORGE:
Emily, I'm glad you spoke to me about that . . . that fault in my character. What you said was right; but there was one thing wrong in it, and that was when you said that for a year I wasn't noticing people, and . . . you, for instance. Why, you say you were watching me when I did everything . . . I was doing the same about you all the time. Why, sure,—I always thought about you as one of the chief people I thought about. I always made sure where you were sitting on the bleachers, and who you were with, and for three days now I've been trying to walk home with you; but something's always got in the way. Yesterday I was standing over against the wall waiting for you, and you walked home with Miss Corcoran.
EMILY:
George! . . . Life's awful funny! How could I have known that? Why, I thought—
GEORGE:
Listen, Emily, I'm going to tell you why I'm not going to Agriculture School. I think that once you've found a person that you're very fond of . . . I mean a person who's fond of you, too, and likes you enough to be interested in your character . . . Well, I think that's just as important as college is, and even more so. That's what I think.
EMILY:
I think it's awfully important, too.
GEORGE:
Emily.
EMILY:
Y-yes, George.
GEORGE:
Emily, if I do improve and make a big change . . . would you be . . . I mean: could you be . . .
EMILY:
I . . . I am now; I always have been.
GEORGE:
Pause.
So I guess this is an important talk we've been having.
EMILY:
Yes . . . yes.
GEORGE:
Takes a deep breath and straightens his back.
Wait just a minute and I'll walk you home.
With mounting alarm he digs into his pockets for the money.
The STAGE MANAGER enters, right.
GEORGE, deeply embarrassed, but direct, says to him:
Mr. Morgan, I'll have to go home and get the money to pay you for this. It'll only take me a minute.
STAGE MANAGER:
Pretending to be affronted.
What's that? George Gibbs, do you mean to tell me—!
GEORGE:
Yes, but I had reasons, Mr. Morgan.—Look, here's my gold watch to keep until I come back with the money.
STAGE MANAGER:
That's all right. Keep your watch. I'll trust you.
GEORGE:
I'll be back in five minutes.
STAGE MANAGER:
I'll trust you ten years, George,—not a day over.—Got all over your shock, Emily?
EMILY:
Yes, thank you, Mr. Morgan. It was nothing.
GEORGE:
Taking up the books from the counter.
I'm ready.
They walk in grave silence across the stage and pass through the trellis at the Webbs' back door and disappear.
The STAGE MANAGER watches them go out, then turns to the audience, removing his spectacles.
STAGE MANAGER:
Well,—
He claps his hands as a signal.
Now we're ready to get on with the wedding.
He stands waiting while the set is prepared for the next scene.
STAGEHANDS remove the chairs, tables and trellises from the Gibbs and Webb houses.
They arrange the pews for the church in the center of the stage. The congregation will sit facing the back wall. The aisle of the church starts at the center of the back wall and comes toward the audience.
A small platform is placed against the back wall on which the STAGE MANAGER will stand later, playing the minister.
The image of a stained-glass window is cast from a lantern slide upon the back wall.
When all is ready the STAGE MANAGER strolls to the center of the stage, down front, and, musingly, addresses the audience.
There are a lot of things to be said about a wedding; there are a lot of thoughts that go on during a wedding.
We can't get them all into one wedding, naturally, and especially not into a wedding at Grover's Corners, where they're awfully plain and short.
In this wedding I play the minister. That gives me the right to say a few more things about it.
For a while now, the play gets pretty serious.
Y'see, some churches say that marriage is a sacrament. I don't quite know what that means, but I can guess. Like Mrs. Gibbs said a few minutes ago: People were made to live two-by-two.
This is a good wedding, but people are so put together that even at a good wedding there's a lot of confusion way down deep in people's minds and we thought that that ought to be in our play, too.
The real hero of this scene isn't on the stage at all, and you know who that is. It's like what one of those European fellas said: Every child born into the world is nature's attempt to make a perfect human being. Well, we've seen nature pushing and contriving for some time now. We all know that nature's interested in quantity; but I think she's interested in quality, too,—that's why I'm in the ministry.
And don't forget all the other witnesses at this wedding,—the ancestors. Millions of them. Most of them set out to live two-by-two, also. Millions of them.
Well, that's all my sermon. 'Twan't very long, anyway.
The organ starts playing Handel's "Largo."
The congregation streams into the church and sits in silence.
Church bells are heard.
MRS. GIBBS sits in the front row, the first seat on the aisle, the right section; next to her are REBECCA and DR. GIBBS.
Across the aisle MRS. WEBB, WALLY and MR. WEBB. A small choir takes its place, facing the audience under the stained-glass window.
MRS. WEBB, on the way to her place, turns back and speaks to the audience.
MRS. WEBB:
I don't know why on earth I should be crying. I suppose there's nothing to cry about. It came over me at breakfast this morning; there was Emily eating her breakfast as she's done for seventeen years and now she's going off to eat it in someone else's house. I suppose that's it.
And Emily! She suddenly said: I can't eat another mouthful, and she put her head down on the table and she cried.
She starts toward her seat in the church, but turns back and adds:
Oh, I've got to say it: you know, there's something downright cruel about sending our girls out into marriage this way. I hope some of her girl friends have told her a thing or two. It's cruel, I know, but I couldn't bring myself to say anything. I went into it blind as a bat myself.
In half-amused exasperation.
The whole world's wrong, that's what's the matter.
There they come.
She hurries to her place in the pew.
GEORGE starts to come down the right aisle of the theatre, through the audience.
Suddenly THREE MEMBERS of his baseball team appear by the right proscenium pillar and start whistling and catcalling to him. They are dressed for the ball field.
THE BASEBALL PLAYERS:
Eh, George, George! Hast—yaow! Look at him, fellas—he looks scared to death. Yaow! George, don't look so innocent, you old geezer. We know what you're thinking. Don't disgrace the team, big boy. Whoo-oo-oo.
STAGE MANAGER:
All right! All right! That'll do. That's enough of that.
Smiling, he pushes them off the stage. They lean back to shout a few more catcalls.
There used to be an awful lot of that kind of thing at weddings in the old days,—Rome, and later. We're more civilized now,—so they say.
The choir starts singing "Love Divine, All Love Excelling—." GEORGE has reached the stage. He stares at the congregation a moment, then takes a few steps of withdrawal, toward the right proscenium pillar. His mother, from the front row, seems to have felt his confusion. She leaves her seat and comes down the aisle quickly to him.
MRS. GIBBS:
George! George! What's the matter?
GEORGE:
Ma, I don't want to grow old. Why's everybody pushing me so?
MRS. GIBBS:
Why, George . . . you wanted it.
GEORGE:
No, Ma, listen to me—
MRS. GIBBS:
No, no, George,—you're a man now.
GEORGE:
Listen, Ma,—for the last time I ask you . . . All I want to do is to be a fella—
MRS. GIBBS:
George! If anyone should hear you! Now stop. Why, I'm ashamed of you!
GEORGE:
He comes to himself and looks over the scene.
What? Where's Emily?
MRS. GIBBS:
Relieved.
George! You gave me such a turn.
GEORGE:
Cheer up, Ma. I'm getting married.
MRS. GIBBS:
Let me catch my breath a minute.
GEORGE:
Comforting her.
Now, Ma, you save Thursday nights. Emily and I are coming over to dinner every Thursday night . . . you'll see. Ma, what are you crying for? Come on; we've got to get ready for this.
MRS. GIBBS, mastering her emotion, fixes his tie and whispers to him.
In the meantime, EMILY, in white and wearing her wedding veil, has come through the audience and mounted onto the stage. She too draws back, frightened, when she sees the congregation in the church. The choir begins: "Blessed Be the Tie That Binds."
EMILY:
I never felt so alone in my whole life. And George over there, looking so . . . ! I hate him. I wish I were dead. Papa! Papa!
MR. WEBB:
Leaves his seat in the pews and comes toward her anxiously.
Emily! Emily! Now don't get upset. . . .
EMILY:
But, Papa,—I don't want to get married. . . .
MR. WEBB:
Sh—sh—Emily. Everything's all right.
EMILY:
Why can't I stay for a while just as I am? Let's go away,—
MR. WEBB:
No, no, Emily. Now stop and think a minute.
EMILY:
Don't you remember that you used to say,—all the time you used to say—all the time: that I was your girl! There must be lots of places we can go to. I'll work for you. I could keep house.
MR. WEBB:
Sh . . . You mustn't think of such things. You're just nervous, Emily.
He turns and calls:
George! George! Will you come here a minute?
He leads her toward George.
Why you're marrying the best young fellow in the world. George is a fine fellow.
EMILY:
But Papa,—
MRS. GIBBS returns unobtrusively to her seat.
MR. WEBB has one arm around his daughter. He places his hand on GEORGE'S shoulder.
MR. WEBB:
I'm giving away my daughter, George. Do you think you can take care of her?
GEORGE:
Mr. Webb, I want to . . . I want to try. Emily, I'm going to do my best. I love you, Emily. I need you.
EMILY:
Well, if you love me, help me. All I want is someone to love me.
GEORGE:
I will, Emily. Emily, I'll try.
EMILY:
And I mean for ever. Do you hear? For ever and ever.
They fall into each other's arms.
The March from Lohengrin is heard.
The STAGE MANAGER, as CLERGYMAN, stands on the box, up center.
MR. WEBB:
Come, they're waiting for us. Now you know it'll be all right. Come, quick.
GEORGE slips away and takes his place beside the STAGE MANAGER-CLERGYMAN.
EMILY proceeds up the aisle on her father's arm.
STAGE MANAGER:
Do you, George, take this woman, Emily, to be your wedded wife, to have . . .
MRS. SOAMES has been sitting in the last row of the congregation.
She now turns to her neighbors and speaks in a shrill voice. Her chatter drowns out the rest of the clergyman's words.
MRS. SOAMES:
Perfectly lovely wedding! Loveliest wedding I ever saw. Oh, I do love a good wedding, don't you? Doesn't she make a lovely bride?
GEORGE:
I do.
STAGE MANAGER:
Do you, Emily, take this man, George, to be your wedded husband,—
Again his further words are covered by those of MRS. SOAMES.
MRS. SOAMES:
Don't know when I've seen such a lovely wedding. But I always cry. Don't know why it is, but I always cry. I just like to see young people happy, don't you? Oh, I think it's lovely.
The ring.
The kiss.
The stage is suddenly arrested into silent tableau.
The STAGE MANAGER, his eyes on the distance, as though to himself:
STAGE MANAGER:
I've married over two hundred couples in my day.
Do I believe in it?
I don't know.
M. . . . marries N. . . . millions of them.
The cottage, the go-cart, the Sunday-afternoon drives in the Ford, the first rheumatism, the grandchildren, the second rheumatism, the deathbed, the reading of the will,—
He now looks at the audience for the first time, with a warm smile that removes any sense of cynicism from the next line.
Once in a thousand times it's interesting.
—Well, let's have Mendelssohn's "Wedding March"!
The organ picks up the March.
The BRIDE and GROOM come down the aisle, radiant, but trying to be very dignified.
MRS. SOAMES:
Aren't they a lovely couple? Oh, I've never been to such a nice wedding. I'm sure they'll be happy. I always say: happiness, that's the great thing! The important thing is to be happy.
The BRIDE and GROOM reach the steps leading into the audience. A bright light is thrown upon them. They descend into the auditorium and run up the aisle joyously.
STAGE MANAGER:
That's all the Second Act, folks. Ten minutes' intermission.
CURTAIN
Act III
During the intermission the audience has seen the stagehands arranging the stage. On the right-hand side, a little right of the center, ten or twelve ordinary chairs have been placed in three openly spaced rows facing the audience.
These are graves in the cemetery.
Toward the end of the intermission the ACTORS enter and
take their places. The front row contains: toward the center of the stage, an empty chair; then MRS. GIBBS; SIMON STIMSON.
The second row contains, among others, MRS. SOAMES.
The third row has WALLY WEBB.
The dead do not turn their heads or their eyes to right or left, but they sit in a quiet without stiffness. When they speak their tone is matter-of-fact, without sentimentality and, above all, without lugubriousness.
The STAGE MANAGER takes his accustomed place and waits for the house lights to go down.
STAGE MANAGER:
This time nine years have gone by, friends—summer, 1913.
Gradual changes in Grover's Corners. Horses are getting rarer.
Farmers coming into town in Fords.
Everybody locks their house doors now at night. Ain't been any burglars in town yet, but everybody's heard about 'em.
You'd be surprised, though—on the whole, things don't change much around here.
This is certainly an important part of Grover's Corners. It's on a hilltop—a windy hilltop—lots of sky, lots of clouds,—often lots of sun and moon and stars.
You come up here, on a fine afternoon and you can see range on range of hills—awful blue they are—up there by Lake Sunapee and Lake Winnipesaukee . . . and way up, if you've got a glass, you can see the White Mountains and Mt. Washington—where North Conway and Conway is. And, of course, our favorite mountain, Mt. Monadnock, 's right here—and all these towns that lie around it: Jaffrey, 'n East Jaffrey, 'n Peterborough, 'n Dublin; and
Then pointing down in the audience.
there, quite a ways down, is Grover's Corners.
Yes, beautiful spot up here. Mountain laurel and li-lacks. I often wonder why people like to be buried in Woodlawn and Brooklyn when they might pass the same time up here in New Hampshire.
Over there—
Pointing to stage left.
are the old stones,—1670, 1680. Strong-minded people that come a long way to be independent. Summer people walk around there laughing at the funny words on the tombstones . . . it don't do any harm. And genealogists come up from Boston—get paid by city people for looking up their ancestors. They want to make sure they're Daughters of the American Revolution and of the Mayflower. . . . Well, I guess that don't do any harm, either. Wherever you come near the human race, there's layers and layers of nonsense. . . .
Over there are some Civil War veterans. Iron flags on their graves . . . New Hampshire boys . . . had a notion that the Union ought to be kept together, though they'd never seen more than fifty miles of it themselves. All they knew was the name, friends—the United States of America. The United States of America. And they went and died about it.
This here is the new part of the cemetery. Here's your friend Mrs. Gibbs. 'N let me see—Here's Mr. Stimson, organist at the Congregational Church. And Mrs. Soames who enjoyed the wedding so—you remember? Oh, and a lot of others. And Editor Webb's boy, Wallace, whose appendix burst while he was on a Boy Scout trip to Crawford Notch.
Yes, an awful lot of sorrow has sort of quieted down up here.
People just wild with grief have brought their relatives up to this hill. We all know how it is . . . and then time . . . and sunny days . . . and rainy days . . . 'n snow . . . We're all glad they're in a beautiful place and we're coming up here ourselves when our fit's over.
Now there are some things we all know, but we don't take'm out and look at'm very often. We all know that something is eternal. And it ain't houses and it ain't names, and it ain't earth, and it ain't even the stars . . . everybody knows in their bones that something is eternal, and that something has to do with human beings. All the greatest people ever lived have been telling us that for five thousand years and yet you'd be surprised how people are always losing hold of it. There's something way down deep that's eternal about every human being.
Pause.
You know as well as I do that the dead don't stay interested in us living people for very long. Gradually, gradually, they lose hold of the earth . . . and the ambitions they had . . . and the pleasures they had . . . and the things they suffered . . . and the people they loved.
They get weaned away from earth—that's the way I put it,—weaned away.
And they stay here while the earth part of 'em burns away, burns out; and all that time they slowly get indifferent to what's goin' on in Grover's Corners.
They're waitin'. They're waitin' for something that they feel is comin'. Something important, and great. Aren't they waitin' for the eternal part in them to come out clear?
Some of the things they're going to say maybe'll hurt your feelings—but that's the way it is: mother 'n daughter . . . husband 'n wife . . . enemy 'n enemy . . . money 'n miser . . . all those terribly important things kind of grow pale around here. And what's left when memory's gone, and your identity, Mrs. Smith?
He looks at the audience a minute, then turns to the stage.
Well! There are some living people. There's Joe Stoddard, our undertaker, supervising a new-made grave. And here comes a Grover's Corners boy, that left town to go out West.
JOE STODDARD has hovered about in the background. SAM CRAIG enters left, wiping his forehead from the exertion. He carries an umbrella and strolls front.
SAM CRAIG:
Good afternoon, Joe Stoddard.
JOE STODDARD:
Good afternoon, good afternoon. Let me see now: do I know you?
SAM CRAIG:
I'm Sam Craig.
JOE STODDARD:
Gracious sakes' alive! Of all people! I should'a knowed you'd be back for the funeral. You've been away a long time, Sam.
SAM CRAIG:
Yes, I've been away over twelve years. I'm in business out in Buffalo now, Joe. But I was in the East when I got news of my cousin's death, so I thought I'd combine things a little and come and see the old home. You look well.
JOE STODDARD:
Yes, yes, can't complain. Very sad, our journey today, Samuel.
SAM CRAIG:
Yes.
JOE STODDARD:
Yes, yes. I always say I hate to supervise when a young person is taken. They'll be here in a few minutes now. I had to come here early today—my son's supervisin' at the home.
SAM CRAIG:
Reading stones.
Old Farmer McCarty, I used to do chores for him—after school. He had the lumbago.
JOE STODDARD:
Yes, we brought Farmer McCarty here a number of years ago now.
SAM CRAIG:
Staring at Mrs. Gibbs' knees.
Why, this is my Aunt Julia . . . I'd forgotten that she'd . . . of course, of course.
JOE STODDARD:
Yes, Doc Gibbs lost his wife two-three years ago . . . about this time. And today's another pretty bad blow for him, too.
MRS. GIBBS:
To Simon Stimson: in an even voice.
That's my sister Carey's boy, Sam . . . Sam Craig.
SIMON STIMSON:
I'm always uncomfortable when they're around.
MRS. GIBBS:
Simon.
SAM CRAIG:
Do they choose their own verses much, Joe?
JOE STODDARD:
No . . . not usual. Mostly the bereaved pick a verse.
SAM CRAIG:
Doesn't sound like Aunt Julia. There aren't many of those Hersey sisters left now. Let me see: where are . . . I wanted to look at my father's and mother's . . .
JOE STODDARD:
Over there with the Craigs . . . Avenue F.
SAM CRAIG:
Reading Simon Stimson's epitaph.
He was organist at church, wasn't he?—Hm, drank a lot, we used to say.
JOE STODDARD:
Nobody was supposed to know about it. He'd seen a peck of trouble.
Behind his hand.
Took his own life, y' know?
SAM CRAIG:
Oh, did he?
JOE STODDARD:
Hung himself in the attic. They tried to hush it up, but of course it got around. He chose his own epy-taph. You can see it there. It ain't a verse exactly.
SAM CRAIG:
Why, it's just some notes of music—what is it?
JOE STODDARD:
Oh, I wouldn't know. It was wrote up in the Boston papers at the time.
SAM CRAIG:
Joe, what did she die of?
JOE STODDARD:
Who?
SAM CRAIG:
My cousin.
JOE STODDARD:
Oh, didn't you know? Had some trouble bringing a baby into the world. 'Twas her second, though. There's a little boy 'bout four years old.
SAM CRAIG:
Opening his umbrella.
The grave's going to be over there?
JOE STODDARD:
Yes, there ain't much more room over here among the Gibbses, so they're opening up a whole new Gibbs section over by Avenue B. You'll excuse me now. I see they're comin'.
From left to center, at the back of the stage, comes a procession. FOUR MEN carry a casket, invisible to us. All the rest are under umbrellas. One can vaguely see: DR. GIBBS, GEORGE, the WEBBS, etc. They gather about a grave in the back center of the stage, a little to the left of center.
MRS. SOAMES:
Who is it, Julia?
MRS. GIBBS:
Without raising her eyes.
My daughter-in-law, Emily Webb.
MRS. SOAMES:
A little surprised, but no emotion.
Well, I declare! The road up here must have been awful muddy. What did she die of, Julia?
MRS. GIBBS:
In childbirth.
MRS. SOAMES:
Childbirth.
Almost with a laugh.
I'd forgotten all about that. My, wasn't life awful—
With a sigh.
and wonderful.
SIMON STIMSON:
With a sideways glance.
Wonderful, was it?
MRS. GIBBS:
Simon! Now, remember!
MRS. SOAMES:
I remember Emily's wedding. Wasn't it a lovely wedding! And I remember her reading the class poem at Graduation Exercises. Emily was one of the brightest girls ever graduated from High School. I've heard Principal Wilkins say so time after time. I called on them at their new farm, just before I died. Perfectly beautiful farm.
A WOMAN FROM AMONG THE DEAD:
It's on the same road we lived on.
A MAN AMONG THE DEAD:
Yepp, right smart farm.
They subside. The group by the grave starts singing "Blessed Be the Tie That Binds."
A WOMAN AMONG THE DEAD:
I always liked that hymn. I was hopin' they'd sing a hymn.
Pause. Suddenly EMILY appears from among the umbrellas. She is wearing a white dress. Her hair is down her back and tied by a white ribbon like a little girl. She comes slowly, gazing wonderingly at the dead, a little dazed.
She stops halfway and smiles faintly. After looking at the mourners for a moment, she walks slowly to the vacant chair beside Mrs. Gibbs and sits down.
EMILY:
To them all, quietly, smiling.
Hello.
MRS. SOAMES:
Hello, Emily.
A MAN AMONG THE DEAD:
Hello, M's Gibbs.
EMILY:
Warmly.
Hello, Mother Gibbs.
MRS. GIBBS:
Emily.
EMILY:
Hello.
With surprise.
It's raining.
Her eyes drift back to the funeral company.
MRS. GIBBS:
Yes . . . They'll be gone soon, dear. Just rest yourself.
EMILY:
It seems thousands and thousands of years since I . . . Papa remembered that that was my favorite hymn.
Oh, I wish I'd been here a long time. I don't like being new here.—How do you do, Mr. Stimson?
SIMON STIMSON:
How do you do, Emily.
EMILY continues to look about her with a wondering smile; as though to shut out from her mind the thought of the funeral company she starts speaking to Mrs. Gibbs with a touch of nervousness.
EMILY:
Mother Gibbs, George and I have made that farm into just the best place you ever saw. We thought of you all the time. We wanted to show you the new barn and a great long ce-ment drinking fountain for the stock. We bought that out of the money you left us.
MRS. GIBBS:
I did?
EMILY:
Don't you remember, Mother Gibbs—the legacy you left us? Why, it was over three hundred and fifty dollars.
MRS. GIBBS:
Yes, yes, Emily.
EMILY:
Well, there's a patent device on the drinking fountain so that it never overflows, Mother Gibbs, and it never sinks below a certain mark they have there. It's fine.
Her voice trails off and her eyes return to the funeral group.
It won't be the same to George without me, but it's a lovely farm.
Suddenly she looks directly at Mrs. Gibbs.
Live people don't understand, do they?
MRS. GIBBS:
No, dear—not very much.
EMILY:
They're sort of shut up in little boxes, aren't they? I feel as though I knew them last a thousand years ago . . . My boy is spending the day at Mrs. Carter's.
She sees MR. CARTER among the dead.
Oh, Mr. Carter, my little boy is spending the day at your house.
MR. CARTER:
Is he?
EMILY:
Yes, he loves it there.—Mother Gibbs, we have a Ford, too. Never gives any trouble. I don't drive, though. Mother Gibbs, when does this feeling go away?—Of being . . . one of them? How long does it . . . ?
MRS. GIBBS:
Sh! dear. Just wait and be patient.
EMILY:
With a sigh.
I know.—Look, they're finished. They're going.
MRS. GIBBS:
Sh—.
The umbrellas leave the stage. DR. GIBBS has come over to his wife's grave and stands before it a moment. EMILY looks up at his face. MRS. GIBBS does not raise her eyes.
EMILY:
Look! Father Gibbs is bringing some of my flowers to you. He looks just like George, doesn't he? Oh, Mother Gibbs, I never realized before how troubled and how . . . how in the dark live persons are. Look at him. I loved him so. From morning till night, that's all they are—troubled.
DR. GIBBS goes off.
THE DEAD:
Little cooler than it was.—Yes, that rain's cooled it off a little. Those northeast winds always do the same thing, don't they? If it isn't a rain, it's a three-day blow.—
A patient calm falls on the stage. The STAGE MANAGER appears at his proscenium pillar, smoking. EMILY sits up abruptly with an idea.
EMILY:
But, Mother Gibbs, one can go back; one can go back there again . . . into living. I feel it. I know it. Why just then for a moment I was thinking about . . . about the farm . . . and for a minute I was there, and my baby was on my lap as plain as day.
MRS. GIBBS:
Yes, of course you can.
EMILY:
I can go back there and live all those days over again . . . why not?
MRS. GIBBS:
All I can say is, Emily, don't.
EMILY:
She appeals urgently to the stage manager.
But it's true, isn't it? I can go and live . . . back there . . . again.
STAGE MANAGER:
Yes, some have tried—but they soon come back here.
MRS. GIBBS:
Don't do it, Emily.
MRS. SOAMES:
Emily, don't. It's not what you think it'd be.
EMILY:
But I won't live over a sad day. I'll choose a happy one—I'll choose the day I first knew that I loved George. Why should that be painful?
THEY are silent. Her question turns to the stage manager.
STAGE MANAGER:
You not only live it; but you watch yourself living it.
EMILY:
Yes?
STAGE MANAGER:
And as you watch it, you see the thing that they—down there—never know. You see the future. You know what's going to happen afterwards.
EMILY:
But is that—painful? Why?
MRS. GIBBS:
That's not the only reason why you shouldn't do it, Emily. When you've been here longer you'll see that our life here is to forget all that, and think only of what's ahead, and be ready for what's ahead. When you've been here longer you'll understand.
EMILY:
Softly.
But, Mother Gibbs, how can I ever forget that life? It's all I know. It's all I had.
MRS. SOAMES:
Oh, Emily. It isn't wise. Really, it isn't.
EMILY:
But it's a thing I must know for myself. I'll choose a happy day, anyway.
MRS. GIBBS:
No!—At least, choose an unimportant day. Choose the least important day in your life. It will be important enough.
EMILY:
To herself.
Then it can't be since I was married; or since the baby was born.
To the stage manager, eagerly.
I can choose a birthday at least, can't I?—I choose my twelfth birthday.
STAGE MANAGER:
All right. February 11th, 1899. A Tuesday.—Do you want any special time of day?
EMILY:
Oh, I want the whole day.
STAGE MANAGER:
We'll begin at dawn. You remember it had been snowing for several days; but it had stopped the night before, and they had begun clearing the roads. The sun's coming up.
EMILY:
With a cry; rising.
There's Main Street . . . why, that's Mr. Morgan's drugstore before he changed it! . . . And there's the livery stable.
The stage at no time in this act has been very dark; but now the left half of the stage gradually becomes very bright—the brightness of a crisp winter morning. EMILY walks toward Main Street.
STAGE MANAGER:
Yes, it's 1899. This is fourteen years ago.
EMILY:
Oh, that's the town I knew as a little girl. And, look, there's the old white fence that used to be around our house. Oh, I'd forgotten that! Oh, I love it so! Are they inside?
STAGE MANAGER:
Yes, your mother'll be coming downstairs in a minute to make breakfast.
EMILY:
Softly.
Will she?
STAGE MANAGER:
And you remember: your father had been away for several days; he came back on the early-morning train.
EMILY:
No . . . ?
STAGE MANAGER:
He'd been back to his college to make a speech—in western New York, at Clinton.
EMILY:
Look! There's Howie Newsome. There's our policeman. But he's dead; he died.
The voices of HOWIE NEWSOME, CONSTABLE WARREN and JOE CROWELL, JR., are heard at the left of the stage. EMILY listens in delight.
HOWIE NEWSOME:
Whoa, Bessie!—Bessie! 'Morning, Bill.
CONSTABLE WARREN:
Morning, Howie.
HOWIE NEWSOME:
You're up early.
CONSTABLE WARREN:
Been rescuin' a party; darn near froze to death, down by Polish Town thar. Got drunk and lay out in the snowdrifts. Thought he was in bed when I shook'm.
EMILY:
Why, there's Joe Crowell. . . .
JOE CROWELL:
Good morning, Mr. Warren. 'Morning, Howie.
MRS. WEBB has appeared in her kitchen, but EMILY does not see her until she calls.
MRS. WEBB:
Chil-dren! Wally! Emily! . . . Time to get up.
EMILY:
Mama, I'm here! Oh! how young Mama looks! I didn't know Mama was ever that young.
MRS. WEBB:
You can come and dress by the kitchen fire, if you like; but hurry.
HOWIE NEWSOME has entered along Main Street and brings the milk to Mrs. Webb's door.
Good morning, Mr. Newsome. Whhhh—it's cold.
HOWIE NEWSOME:
Ten below by my barn, Mrs. Webb.
MRS. WEBB:
Think of it! Keep yourself wrapped up.
She takes her bottles in, shuddering.
EMILY:
With an effort.
Mama, I can't find my blue hair ribbon anywhere.
MRS. WEBB:
Just open your eyes, dear, that's all. I laid it out for you special—on the dresser, there. If it were a snake it would bite you.
EMILY:
Yes, yes . . .
She puts her hand on her heart. MR. WEBB comes along Main Street, where he meets CONSTABLE WARREN. Their movements and voices are increasingly lively in the sharp air.
MR. WEBB:
Good morning, Bill.
CONSTABLE WARREN:
Good morning, Mr. Webb. You're up early.
MR. WEBB:
Yes, just been back to my old college in New York State. Been any trouble here?
CONSTABLE WARREN:
Well, I was called up this mornin' to rescue a Polish fella—darn near froze to death he was.
MR. WEBB:
We must get it in the paper.
CONSTABLE WARREN:
'Twan't much.
EMILY:
Whispers.
Papa.
MR. WEBB shakes the snow off his feet and enters his house. CONSTABLE WARREN goes off, right.
MR. WEBB:
Good morning, Mother.
MRS. WEBB:
How did it go, Charles?
MR. WEBB:
Oh, fine, I guess. I told'm a few things.—Everything all right here?
MRS. WEBB:
Yes—can't think of anything that's happened, special. Been right cold. Howie Newsome says it's ten below over to his barn.
MR. WEBB:
Yes, well, it's colder than that at Hamilton College. Students' ears are falling off. It ain't Christian.—Paper have any mistakes in it?
MRS. WEBB:
None that I noticed. Coffee's ready when you want it.
He starts upstairs.
Charles! Don't forget, it's Emily's birthday. Did you remember to get her something?
MR. WEBB:
Patting his pocket.
Yes, I've got something here.
Calling up the stairs.
Where's my girl? Where's my birthday girl?
He goes off left.
MRS. WEBB:
Don't interrupt her now, Charles. You can see her at breakfast. She's slow enough as it is. Hurry up, children! It's seven o'clock. Now, I don't want to call you again.
EMILY:
Softly, more in wonder than in grief.
I can't bear it. They're so young and beautiful. Why did they ever have to get old? Mama, I'm here. I'm grown up. I love you all, everything.—I can't look at everything hard enough.
She looks questioningly at the STAGE MANAGER, saying or suggesting: "Can I go in?" He nods briefly. She crosses to the inner door to the kitchen, left of her mother, and as though entering the room, says, suggesting the voice of a girl of twelve:
Good morning, Mama.
MRS. WEBB:
Crossing to embrace and kiss her; in her characteristic matter-of-fact manner.
Well, now, dear, a very happy birthday to my girl and many happy returns. There are some surprises waiting for you on the kitchen table.
EMILY:
Oh, Mama, you shouldn't have.
She throws an anguished glance at the stage manager.
I can't—I can't.
MRS. WEBB:
Facing the audience, over her stove.
But birthday or no birthday, I want you to eat your breakfast good and slow. I want you to grow up and be a good strong girl.
That in the blue paper is from your Aunt Carrie; and I reckon you can guess who brought the post-card album. I found it on the doorstep when I brought in the milk—George Gibbs . . . must have come over in the cold pretty early . . . right nice of him.
EMILY:
To herself.
Oh, George! I'd forgotten that. . . .
MRS. WEBB:
Chew that bacon good and slow. It'll help keep you warm on a cold day.
EMILY:
With mounting urgency.
Oh, Mama, just look at me one minute as though you really saw me. Mama, fourteen years have gone by. I'm dead. You're a grandmother, Mama. I married George Gibbs, Mama. Wally's dead, too. Mama, his appendix burst on a camping trip to North Conway. We felt just terrible about it—don't you remember? But, just for a moment now we're all together. Mama, just for a moment we're happy. Let's look at one another.
MRS. WEBB:
That in the yellow paper is something I found in the attic among your grandmother's things. You're old enough to wear it now, and I thought you'd like it.
EMILY:
And this is from you. Why, Mama, it's just lovely and it's just what I wanted. It's beautiful!
She flings her arms around her mother's neck. Her MOTHER goes on with her cooking, but is pleased.
MRS. WEBB:
Well, I hoped you'd like it. Hunted all over. Your Aunt Norah couldn't find one in Concord, so I had to send all the way to Boston.
Laughing.
Wally has something for you, too. He made it at manual-training class and he's very proud of it. Be sure you make a big fuss about it.—Your father has a surprise for you, too; don't know what it is myself. Sh—here he comes.
MR. WEBB:
Off stage.
Where's my girl? Where's my birthday girl?
EMILY:
In a loud voice to the stage manager.
I can't. I can't go on. It goes so fast. We don't have time to look at one another.
She breaks down sobbing.
The lights dim on the left half of the stage. MRS. WEBB disappears.
I didn't realize. So all that was going on and we never noticed. Take me back—up the hill—to my grave. But first: Wait! One more look.
Good-by, Good-by, world. Good-by, Grover's Corners . . . Mama and Papa. Good-by to clocks ticking . . . and Mama's sunflowers. And food and coffee. And new-ironed dresses and hot baths . . . and sleeping and waking up. Oh, earth, you're too wonderful for anybody to realize you.
She looks toward the stage manager and asks abruptly, through her tears:
Do any human beings ever realize life while they live it?—every, every minute?
STAGE MANAGER:
No.
Pause.
The saints and poets, maybe—they do some.
EMILY:
I'm ready to go back.
She returns to her chair beside Mrs. Gibbs.
Pause.
MRS. GIBBS:
Were you happy?
EMILY:
No . . . I should have listened to you. That's all human beings are! Just blind people.
MRS. GIBBS:
Look, it's clearing up. The stars are coming out.
EMILY:
Oh, Mr. Stimson, I should have listened to them.
SIMON STIMSON:
With mounting violence; bitingly.
Yes, now you know. Now you know! That's what it was to be alive. To move about in a cloud of ignorance; to go up and down trampling on the feelings of those . . . of those about you. To spend and waste time as though you had a million years. To be always at the mercy of one self-centered passion, or another. Now you know—that's the happy existence you wanted to go back to. Ignorance and blindness.
MRS. GIBBS:
Spiritedly.
Simon Stimson, that ain't the whole truth and you know it. Emily, look at that star. I forget its name.
A MAN AMONG THE DEAD:
My boy Joel was a sailor,—knew 'em all. He'd set on the porch evenings and tell 'em all by name. Yes, sir, wonderful!
ANOTHER MAN AMONG THE DEAD:
A star's mighty good company.
A WOMAN AMONG THE DEAD:
Yes. Yes, 'tis.
SIMON STIMSON:
Here's one of them coming.
THE DEAD:
That's funny. 'Tain't no time for one of them to be here.—Goodness sakes.
EMILY:
Mother Gibbs, it's George.
MRS. GIBBS:
Sh, dear. Just rest yourself.
EMILY:
It's George.
GEORGE enters from the left, and slowly comes toward them.
A MAN FROM AMONG THE DEAD:
And my boy, Joel, who knew the stars—he used to say it took millions of years for that speck o' light to git to the earth. Don't seem like a body could believe it, but that's what he used to say—millions of years.
GEORGE sinks to his knees then falls full length at Emily's feet.
A WOMAN AMONG THE DEAD:
Goodness! That ain't no way to behave!
MRS. SOAMES:
He ought to be home.
EMILY:
Mother Gibbs?
MRS. GIBBS:
Yes, Emily?
EMILY:
They don't understand, do they?
MRS. GIBBS:
No, dear. They don't understand.
The STAGE MANAGER appears at the right, one hand on a dark curtain which he slowly draws across the scene.
In the distance a clock is heard striking the hour very faintly.
STAGE MANAGER:
Most everybody's asleep in Grover's Corners. There are a few lights on: Shorty Hawkins, down at the depot, has just watched the Albany train go by. And at the livery stable somebody's setting up late and talking.—Yes, it's clearing up. There are the stars—doing their old, old crisscross journeys in the sky. Scholars haven't settled the matter yet, but they seem to think there are no living beings up there. Just chalk . . . or fire. Only this one is straining away, straining away all the time to make something of itself. The strain's so bad that every sixteen hours everybody lies down and gets a rest.
He winds his watch.
Hm. . . . Eleven o'clock in Grover's Corners.—You get a good rest, too. Good night.
THE END
Afterword
I am grateful that the success of this volume has led Harper-Collins to encourage and endorse a revised edition. This edition appears, most appropriately, during Our Town's seventy-fifth-anniversary year, the logo of which opens this piece.
For more than a decade the original Overview has stood the test of time. I have made only minor changes to the text and none to its accompanying Acknowledgments. In these ten years I learned that it was in the Readings section that I needed to make changes, revising and extending the text of many of the original Readings, and adding several new items. To take account of the renewed interest in Thornton Wilder's life and works since 2001, I have added a section on subsidiary works based on Our Town born since 2002. The new century has been good to, and for, Our Town, as I attempt to point out here.
All of the Readings found in the first edition have been retained here, although the texts of many have been re-titled or revised, and we have added three new Readings altogether (numbers 2, 3, and 6). All changes made in this edition are intended to enrich the story of how Our Town came to be and to update the highlights of its history to the present. Readers seeking additional information are encouraged to consult the sources described on pages 195–96.
My family and I are especially indebted to Barbara Hogenson, Rosey Strub, Penelope Niven, and Lori Styler on the Wilder side, and editors Hugh Van Dusen and Barry Harbaugh at HarperCollins for their support of this "revised" venture. We also offer special thanks to Donald Margulies for his thoughtful Addendum to his earlier Foreword.
In my capacity of literary executor for the last eighteen years, I have represented Thornton Wilder's works—the work of a man whom I knew as Uncle Thorny. It is a rare day that does not involve dealing with some aspect of Our Town—production questions, permissions requests, translations matters, talk-backs at theaters, etc. When Thornton Wilder's name is mentioned, the fable of growing up, falling in love, marrying, and dying in Grover's Corners, New Hampshire, is always the first thought that comes to mind. That's the way it is with this playwright's most famous work, and it has pretty much been that way since Our Town opened in New York at Henry Mill-er's Theatre on West Forty-Third Street seventy-five years ago.
I knew the play first on an intimate level in 1955, when as a high school freshman, I played the part of Professor Willard on a temporary stage set up in a postage-sized school gymnasium. I was a frightened puppy in 1955—at playing the role and at playing myself in life. I am confident that hundreds of other students who played the same part that year across the country felt the same way—and so have others who have played it as recently as last year or last week. It's been that way pretty much from the beginning. There are, on average, some four hundred productions of Our Town in the United States every year, and at least twenty more throughout the rest of the world. From Japan to Romania and Peru to Saudi Arabia, somewhere at least once a day Our Town means our town, the place where, be it a town, suburb, or a city neighborhood, we all live, love, and die. In the words of contemporary critic Jeremy McCarter, Wilder's mission for actors and audiences is "to make a little better sense of the funny, scary, bewildering business of being alive."
I attended scattered productions of Our Town growing up and into my adult years. It was hard to avoid them, being a member of the Wilder family. Things got serious after 1995. Now wearing an official Wilder hat, I have seen some eighteen major productions of the stage play in twelve states (several productions more than once) and seven productions of the new Our Town opera (2006) in seven states. I have also held in my hand many programs from foreign productions. A few I can translate; some I have had translated; mostly I try to discern messages from their cover designs.
What have I learned since 1995 about the play my uncle described as "the life of a village against the life of the stars"? I have learned that people do indeed cry when they see Our Town. "Take along plenty of handkerchiefs," Thornton Wilder warned a reporter in 1938 during its original Broadway run. "Strong men cry when they see it." He was right. At several productions I have seen many a hankie at work, heard lots of sniffles, and seen real tears on the faces of women—and sometimes even strong-looking men. From reliable reports I also know that tears do not stop at the border.
Through much of the last century, Our Town's reputation, especially among critical circles, was often tarred as a moving, but flimsy, sentimental and patriotic depiction of life in a now lost small-town America—presumably the kind of play you cry at for the wrong reasons. Edward Albee saw the source of emotion another way: "I can't even think about parts of [Our Town] without wanting to cry," he said in an interview in the late nineties. "Not because it is cute and touching and greeting card time, but because it is so tough and so sad. And I don't understand why it's played so cute all the time. I've never seen a more misunderstood play."
I have learned from my travels and encounters with Our Town over the last decade that the play is becoming less and less misunderstood. Indeed, I believe that this iconic work is entering a golden age. In my experience, across the country, this play is increasingly being mounted by a rising generation of directors and actors who know it to be the drama described by A. R. Gurney as "a starkly powerful meditation on death and human existence." And in production after production, theaters are finding highly creative and dramatically "fresh" ways to stage the play. Some are tough and dark; others—including those in a number of theaters who turned to Our Town after 9/11—have combined those hues with a special sensibility for the preciousness of life and community. I've seen the use of a powerfully evocative translucent wall placed between the dead and the living (Dallas Theater Center); a backdrop that evoked no less powerfully the original homely and even ugly rehearsal stage on which the play was originally mounted (Westport Country Playhouse); a second act performed in an historic church next door (Arden Theatre); the purposeful mounting of the show from an old-fashioned box set; all types of staging with seats on two, three, or four sides, even on a huge stage open to the stars (Oregon Shakespeare Festival); and countless imaginative ways of handling multi-cultural casting, pantomime, sound effects, music, costumes, and the asking of the questions in Act I (including even a literary executor tasked with asking about "social injustice and industrial inequality").
In the Addendum to his Foreword, Donald Margulies mentions Our Town's recent off-Broadway Barrow Street Theatre production, directed by David Cromer. This theater held 151 seats arranged around a floor-level, three-sided thrust stage containing only two tables and several chairs as props, with the choir in a small balcony area. The arrangement made for an extraordinarily intimate relationship between play and audience, heightened by the actors—in nondescript casual modern dress—often performing among the audience. Emily's return from the dead was staged as an animated tableau-like scene that played off memory, imagination, and the use of sensory stimulation.
A typical evening at Barrow Street left stunned audiences stumbling into the night asking themselves if this could possibly be the same Our Town they remembered seeing—or performing in or hearing about—once upon a time.*
Yes, it is the same play and, for nearly two decades now in theaters everywhere, I have watched audiences asking the same question. Many asking this question are my fellow Our Town alumni and the thousands and thousands of individuals who brushed up against the play in some way in their growing up. It is not only the often novel ways in which Our Town is being performed that moves them so deeply today; my generation has grown up and added what Thornton Wilder's great friend in this century, the poet and librettist J. D. McClatchy, calls "scars on our hearts." For many of us, seeing this play on stages across the country is like seeing a "dramatically" new work. It's the kind of achievement that makes me feel so proud of the man I represent and the reason why I clap loudly when the non-curtain falls at the end of the show. I appear to have lots of company.
So end my observations about what I have learned about Our Town in recent years. Now on with the book!
—Tappan Wilder
February 2013
Overview
Thornton Wilder, Pulitzer Prize–winning, internationally acclaimed novelist, entered the decade of the 1930s determined to achieve still another great distinction: playwright in full Broadway standing. He appeared to have achieved this dream on Friday evening, February 4, 1938, at Henry Mill-er's Theatre on Forty-Third Street, when Frank Craven, the admired character actor, played the part of the Stage Manager in the premiere of Our Town, directed and produced by the legendary Jed Harris. The play concluded with the language used in this production: "They're resting in Grover's Corners. Tomorrow's going to be another day. Good night to you, too. Good night. Get a good rest." After a short, stunned silence, broken by audible sniffles in the house, the audience offered an ovation.
The next day, the phone rang off the hook with good news at the author's home ninety miles away in Hamden, Connecticut. A particularly informative call came from Wilder's greatest actor friend, Ruth Gordon, then starring as Nora in Wilder's adaption/translation of Ibsen's A Doll's House, also playing on Broadway and also directed by Harris. (It is forgotten that Wilder had two shows running in New York City at the same time in 1938.) Wilder reported the highlights of Gordon's call (including tears in the eyes of a Hollywood mogul) to Dwight Dana, his attorney, confidant, and keeper of Wilder's exchequer during the Great Depression. This letter is the earliest written record of the playwright's reaction to a theatrical opening that would have a defining influence on his reputation and bank account ever after. "Dear Dwight," he began:
Funny thing's happened.
Ruth phoned down. It's already broken a house record.
In spite of the mixed reviews when the box-office opened Saturday morning there were 26 people in line; the line continued all day, and the police had to close it for ten minutes so that the audience could get into the matinee; and that $6,500 was taken in on that day—the two performances and the advanced sale.
Imagine that!
Friday night both Sam Goldwyn and Bea Lillie were seen to be weeping. Honest! . . .
Isn't it astonishing, and fun and exhausting?
Our Town did indeed receive mixed reviews. Negative comments focused on whether it was "dramatic" enough to be called a play or merely what Robert Benchley in The New Yorker saw as "so much ersatz." John Gassner in One Act Play Magazine dismissed the play as "devoid of developed situations" and thus much less than "a major dramatic experience," and George Jean Nathan later called it "a stunt." Time thought that Wilder's effective use of "Chinese methods gives ten times as much 'theatre' as conventional scenery could give," but nevertheless found the third act full of disappointing "mysticism and high-flown speculation." The New Masses, the left-wing journal, whose editor, Michael Gold, had famously trashed Wilder's fiction earlier in the decade, tipped its hat slightly to the work while delivering a salvo: "It is an exasperating play, hideous in its basic idea and beautiful in its writing, acting and staging." ("Hideous" was the play-wright's favorable treatment of middle-class, bourgeois values and lives.)
But where it mattered, in such papers as the Herald- Tribune, the World-Telegram, the Brooklyn Daily Eagle, and even in the tabloid Sunday Mirror, the play's staging, acting, directing, and themes evoked powerful adjectives and praise. It was "beautiful," "touching," "one of the great plays of our day," "magnificent." Robert Colman in the Mirror pulled out all stops, proclaiming it "worthy of an honored place in any anthology of the American drama," as soon it would be, starting in 1940. Brooks Atkinson in the New York Times, the first among equals in influence, wrote a review of poetic intensity, hailing Wilder and Harris for a play that "trans-muted the simple events of human life into universal reverie," and that contained nothing less than "a fragment of the immortal truth."
By February 14, box-office sales having held up well enough to justify moving the play to its permanent home, the Morosco Theatre, Wilder felt comfortable enough to write to his friend Lady Sibyl Colefax in London: "Lord! I can't believe it myself. It's the hit of the town. Almost everybody's got some reservations against it (including myself) but every-body's discussing it and going to see it."
The drama that made even Sam Goldwyn cry appears as "M Marries N" in a list of ideas for plays penned July 2, 1935. This precise language—is it possibly the oldest in the play?—survives in the final version, at the end of Act II, when the Stage Manager, as minister, says: "M. . . . marries N. . . . millions of them." This "alphabet" marriage appears less than two weeks after Wilder encountered, at his brother's wedding in New Jersey, the custom of the groom not seeing his bride on the wedding day until they meet at the church. This fact, as well as other references in the play to Wilder family events, has always made Our Town an unusually personal (and tearful) experience for his family.
Thanks to records, we know that "M Marries N" evolved into "Our Village" in 1936, and into "Our Town" by 1937. Wilder was a writer who could not do serious work at his home in Connecticut. It is no surprise, therefore, that Our Town's creative journey encompassed transatlantic streamers; writing tables in hotels and hideaways in such varied places as the Caribbean island of St. Lucia (October 1936) and the MacDowell Colony in Peterborough, New Hampshire (June 1937); and such addresses in Switzerland in the fall of 1937 as Zurich, St. Moritz, Sils-Maria, Sils-Baselgia, Ascona, and Rüschlikon. Of these, the Veltin Studio at the MacDowell Colony and especially a room in the Hotel Belvoir in lake-side Rüschlikon (a small village outside Zurich—eight francs a day, including breakfast and lunch) were key locations where scenes and acts were written, discarded, and revised. And rain or shine, there was one other central ingredient in a Wilder writing day—a long walk. Those taken in the Peter-borough and Lake Sunapee areas of New Hampshire, starting in 1923, set the stage in his mind for Our Town. Shortly after the play opened, Wilder quantified his walks in an interview: "At a rough guess, one day's walk is productive of one fifteen- minute scene. Everything I've ever done has come into being that way and I don't think I could work out an entire play or novel at a desk now if I tried."
The following excerpts from Wilder's letters open helpful windows on the author's progress during the key summer months of 1937. As they indicate, he was, in this period, working on several plays at once. (A reading below touches on the importance of Wilder's one-act plays of 1931 as the tool chest he used to construct Our Town, among them The Happy Journey to Trenton and Camden and Pullman Car Hiawatha.)
June 24 from the MacDowell Colony to Alexander Woollcott. My darts thrown at perfection are being feathered and pointed in many tranquil hours in these woods. Three of them are being assembled at once. None are ready to leave behind me when I sail. I always think of Our Village as yours. It is intended to give you pleasure. The Happy Journey [to Trenton and Camden] is no longer part of it. The last act in the cemetery will be prodigious. [Our Town is dedicated to Woollcott, the critic and broadcaster. He included The Happy Journey in the 1935 edition of his influential Woollcott Reader.]
September 4 from Zurich to his family. I've begun the Second Act of "Our Town." It'll be awful hard to combine all the things, general and particular, that one would wish to say about love and marriage,—combine them in one long flowing musical curve. . . . And back into the First Act go some preparatory speeches: Amy "Mama, am I . . . am I nice lookin'?" Mother "Oh, go-on-with-you. All my children got good features. I'd be ashamed if they hadn't." [Amy was an earlier name for Emily.]
September 6 to Sibyl Colefax from Zurich. A scene that must not be morbid though it plunges deep in the unconfessed structure of the mind. The bride seems never to have seen the groom before, is terrified, fears him, appeals to the audience for help, draws her father over to the proscenium pillar, and asks him to run away with her to the South Sea, to anywhere. He too is haunted; over her head tells the audience that no girl should be married, that there is no anxious state in the world crueler than that of a young wife . . . then passes his hand over his forehead and trembling, reassures his daughter and leads her back to the clergyman.
September 22 to family from Sils-Baselgia. Wonderful place.
The great ghost of Nietzsche. . . . Last night my play got such an influx of new ideas that now it's the most beautiful play you can imagine.
September 25 to Sibyl Colefax from Zurich. It's raining and the pantomime of the funeral goes on over in a far corner of the stage and there are ten umbrellas up.
Every act has hymn-singing in it—the choir practice, the wedding, the funeral. And when the city-dwelling Americans get those homely ur-American hymns going through them,—Just as the negro spirituals bathed and supported "Green pastures."
Yes, the last act has lots of cold iron and grasping-the-nettle in it, but Sils-Maria gave it an ultimate Affirming Ring.
October 1 to Sibyl Colefax from Rüschlikon. I'm behind schedule. I had hoped on October first to be able to jump to Play No #2.
But it doesn't matter: "Our Town's" First and Second Acts are all fair-copied and I think "set." And that difficult cactus-spined third is moving into place every day.
Lord! What I got myself in for. A theologicometaphysico-transcription from the Purgatorio with panels of American rural genre-stuff.
Isn't it awful?
While they are waiting there to have the Earth slip from them, does Dante's vesperal angel make its appearance?
Can we see by the turning of their heads, by a recuillement that Something has come?
First of all: do I believe it?
October 28 to family from Rüschlikon. Jed [Harris] telephoned from London for 20 minutes the other night. He wants to know if "Our Town" would be a good play for the Xmas season in New York. Would it?!! And guess who might act the lanky tooth picking stage-manager? Sinclair Lewis! He's been plaguing Jed to let him act for a long time; and there's a part for his famous New England parlor-trick monologues. Don't tell anybody anything about it . . . [Lewis played the Stage Manager later in summer stock.]
November 24 to Amy Wertheimer from Paris. I was summoned by Jed Harris to Paris and read him "Our Town"—a New Hampshire village explored by the techniques of Chinese Drama and of Pullman Car Hiawatha. He was very enthusiastic and hurried home to America to put it on for the Xmas season. . . . I follow soon for rehearsals.
Wilder did not, in fact, finish Our Town in Europe, and no walks are recorded in the last two places associated with the completion of the acting script. To assure that end and get publicity for it, Harris snatched Wilder off the dock when he arrived home on the Queen Mary and imprisoned him on Long Island. (To quote one headline: WILDER LOCKED UP TILL HE FINISHES THAT PLAY OF HIS.) The prison, a cottage on Long Island in the swanky Cold Spring Harbor area, came with amenities, including cook and butler and much chintz.
More Spartan was the spot where Wilder finally completed the acting script on December 19, only a few days before rehearsals began: the Columbia University Club on Forty-Third Street, three blocks from Broadway. Writing to Dwight Dana, he coupled this good news with a distressing report that he had not yet signed a play contract with Jed Harris, with whom he was "in such a mess of friendship- collaboration sentiment . . . and with a sense of sense of guilt about the unfinished condition of the play that I can't pull myself together to insist." But what of Our Town's prospects? Wilder reported that Frank Craven (who had a contract) thought it "a possibility that the play will be a smashing success." This feeling built among the cast and the few people admitted to observe rehearsals (they predicted "big things"), although Wilder was almost immediately discouraged by some of Harris's stage directions, and worst of all, his "tasteless additions" to Wilder's script. These irritations soon grew into a violent quarrel that poisoned their relationship.
Our Town's route to Broadway wound through Princeton and Boston. The premiere was a single performance at the McCarter Theatre in Princeton, New Jersey, on January 22, 1938. The play drew a ferociously negative review in Variety ("it will probably go down as the season's most extravagant waste of fine talent"), but the audience and Wilder saw it differently. Wilder wrote to Dana:
The performance at Princeton was an undoubted success. The large theatre was sold out with standees. Take was 1900 dollars; Audience swept by laughter often; astonishment; and lots of tears; long applause at the end by an audience that did not move from its seats.
Boston was in some ways a very different story. Our Town arrived there for a scheduled two-week run at the Wilbur Theater starting Tuesday, January 25. It is popularly believed that the Boston critics panned the play. In Fanfare (1957), the legendary stage publicist Richard Maney paints this standard story as only a New Yorker can: "[The play's] reception was so chilly and attendance so wretched that the two-week engagement was pared to one. The American Athens wanted no truck with a play without scenery. To Beacon Hill Brahmins, such an omission was as confusing as tackling a grapefruit without a spoon."
Business was terrible at the Wilbur in Boston in 1938, as it was in other theaters in that especially difficult Great Depression year. But the reviews were not all pans. Wilder described them as "cautious but not unfavorable." Critics saw much to like in the play, but they were perplexed and mystified by its avant-garde features, as this lead from an Associated Press story suggests: SPEECH-MAKING BY "CORPSES" UNUSUAL FEATURE. Mordaunt Hall of the Boston Evening Transcript, a prominent voice, found the play "curious," but noted that it was "roundly applauded by last night's gathering." A New York Times piece painted a similar picture—a "puzzled" audience but one that nevertheless at the end "applauded unashamedly a touching, delicately written, warmly acted play that bears a distant resemblance in its technique to Chinese or Greek methods translated into New England terms."
In Boston, Our Town drew perhaps the most extraordinary headline in its history. In what Wilder described as a "bomb dropped on the cast," the day before the Boston opening Harris's companion, the actress Rosamond Pinchot, committed suicide at her home outside New York. The tragedy was reported on page 1 in the Boston Post January 25:
LINK SUICIDE TO NEW SHOW HERE
Rosamond Pinchot Said to Have Been Brooding
Over Failure to Win Part in "Our Town"
Whatever the differences between the sizes of the houses, the Princeton and Boston productions shared one similarity—tears. Now disturbed about the audience's reaction to the play, Wilder wrote to Sibyl Colefax:
Audiences heavily papered. Laughed and cried. The wife of the Governor of Mass took it on her self to telephone the box-office that the last act was too sad. She was right. Such sobbing and nose- blowing you never heard. Matinee audience, mostly women, emerged red-eyed, swollen faced, and mascara-stained. I never meant that; and direction is responsible for much of it; Jed is now wildly trying to sweeten and water-down the text.
Shaken by Pinchot's death, the poor attendance, and critics who refused to leap with excitement, and losing significant money, Harris faced three options for a drama in which he had great faith: close it (which he prepared to do); withdraw it for further work and try it out in another city (an idea apparently entertained, however briefly, with New Haven in mind); or arrange an earlier-than-planned New York opening. Harris chose the last, threw the cast into four days of rehearsals, and opened the play temporarily at Henry Miller's Theatre on Friday, February 4. Said to have tipped the balance toward that option were the opinions of several influential figures who came from New York to see the play, among them the playwright Marc Connelly. He declared Our Town "magnificent," and ready for Broadway. Wilder, now suffering physical symptoms of distress from the tension of it all, wrote Sibyl Colefax as rehearsals began in New York: "Marc [Connelly] and other have sent the rumors around N.Y. that Friday night will be one exciting occasion. Jed is charging $5.50 top, which is insane."
As noted, the Our Town opening was an exciting occasion. The original Broadway production did not, however, break records. To keep the production going during the difficult hot summer months, Wilder accepted royalty cuts that reached 50 percent. Business improved somewhat when he played the part of the Stage Manager for two weeks in September. The job earned him respectable kudos in the press. He also enjoyed himself, although the experience left him "alternately exhausted and dizzy."
On November 19, slightly more than ten months into the run, Harris closed Our Town in New York after 336 performances and took it out on what was projected to be a lengthy national tour. Three months and twelve cities later, on February 11, 1939, the tour ended abruptly in Chicago. Thomas Coley, an original cast member, recalled the reason in a memoir: "Jed noticed that Frank Craven was earning more each week than he, the producer-director. He came out to persuade Mr. Craven to reduce his percentage of the gross. They argued. Jed lost. In a rage, he closed the play, thus cutting off the nose to spite his face, and, incidentally, the noses of forty-seven actors plus the crew."
Although Our Town had a less than record-breaking launch, its subsequent history, measured in amateur and stock productions, earned it the "smashing success" that Craven had predicted on the eve of rehearsals. And it all happened quite quickly.
The play's amateur and stock rights, for example, became available for the first time on April 19, 1939. By December 31, 1940, the play (handled by Samuel French) had been performed on amateur stages in no fewer than 658 communities. The figure represented every state of the Union save one (Rhode Island), as well as the District of Columbia, Hawaii, and four Canadian provinces. This laid the foundation for the Our Town rule of thumb ever since: It is performed at least once each night somewhere in this country. Behind these figures lies a large cast play that has marvelous parts for young people, is not expensive to mount, is glorious to teach, and treats life, death, and love in such an immediate fashion as to leave indelible and typically nostalgic impressions on generations of students.
Our Town was also a hit from the beginning with stock companies. Through May 1944 it had already been performed forty-three times, principally in the era's summer theaters in New England and the mid-Atlantic states. Five of these productions featured Wilder as the Stage Manager. Since World War II, the pattern has continued, now tied to the growth of American regional theaters in the post-war period. Between 1970 and 1999, for example, the play was performed ninety-one times in professional stock and regional theaters across the country, and it has already been performed another sixteen times so far in the new century. The Long Wharf Theatre in New Haven, Connecticut, Wilder's home city, mounted the play's fiftieth-anniversary production, starring Hal Holbrook. Another landmark production occurred in 1976, at the Williamstown Summer Festival, when Geraldine Fitzgerald bowed as the first woman to play the Stage Manager.
Marc Connelly, one of the saviors of the play when it stumbled in Boston, played the Stage Manager when Our Town had its first major New York revival in 1944, a production Jed Harris directed. There have been four revivals since, the last two being Lincoln Center's Tony Award– winning production starring Spalding Gray in 1988 and the Westport Country Playhouse's successful production starring Paul Newman in 2002. Both productions were subsequently showcased in national public television releases. These first-class and/or stock productions routinely provide the opportunity for audiences, critics, and artists to explore the play and its artistry in a fresh way. The findings can be revelatory—witness playwright Lanford Wilson writing about the fiftieth-anniversary production in 1987 in the New York Times: "And where the hell did [Wilder] get the reputation for being soft? Let's agree never to say that again. Let's not be blinded by the homey cute surface from the fact that 'Our Town' is a deadly cynical and acidly accurate play." After September 11, many theaters also saw in it what Richard Hamburger at the Dallas Theater Center spoke of as a reassuring "sense of continuity and community."
Our Town has also been an international success story, beginning with the first productions in 1938 in the Scandinavian countries. Isabel Wilder's letter to her brother Amos in the Readings that follow opens a small window onto a large story, itself a reminder that the play's themes, so commonly identified as quintessentially American, have universal appeal. For example, since 1960, Unsere kleine stadt has been produced in at least twenty-two languages in twenty-seven countries, outside of Germany, and translated and almost certainly performed in more. (Precise figures can be hard to come by in this chapter of Our Town's history.) Germany has always been a special case for this play as well as Wilder's other works. Between 1950 and 1970, Our Town was produced professionally eighty times in Germany; although it is done less often now, it continues to be performed and read in schools. It says much about the drama's planetary appeal and vision that the cover of the new German paperback edition depicts a major metropolis.
Despite many requests, Wilder did not permit Our Town to be fashioned into a live musical or opera. But he was open to other options. Forgotten is the play's extensive radio history, launched in March 1938 with a segment of The Kate Smith Hour (then the nation's most popular radio show) and including a six-month Camel Caravan series during World War II, and Wilder's own appearance in a Theatre Guild on the Air broadcast in September 1946. With one notable exception the play's early record in television (with Art Carney and Henry Fonda among headliners) is also forgotten. The exception is the ninety-minute musical Producer's Showcase version in 1955 starring Frank Sinatra, Paul Newman, and Eva-Marie Saint, remembered because of the continuing popularity of the award-winning Sammy Cahn–Jimmy Van Heusen song "Love and Marriage." In 1977, Hal Holbrook played the lead role in an admired two-hour NBC broadcast, a tradition of televising the "straight play" that the productions with Spalding Gray and Paul Newman have built upon since.
Thanks to cable television, movie cassettes, and DVD, the Our Town movie released by Sol Lesser at a huge celebration in Boston in May 1940 continues to have a public presence. (This time, Our Town was a success in that city.) Wilder, who had credentials as a screenwriter, was not initially interested in any participation in the script. But to protect his increasingly valuable property, he became deeply involved in it, including the famous decision to let Emily live (she dies only in a dream). He expressed his view on the matter this way in a letter to Lesser (thereby providing countless students with a term-paper subject):
I've always thought [Emily should live]. In a movie you see the people so close to that a different relation is established. In the theatre they are halfway abstractions in an allegory; in the movie they are very concrete. So in so far as the play is a Generalized Allegory she dies—we die—they die; in so far as it's a Concrete Happening it's not important that she die. Let her live—the idea will have been imparted anyway.
As part of the record, it is important to add that it never occurred to Wilder that technology would give the Our Town film such a long afterlife, and that his permission for a onetime-only televised performance of the Cahn–Van Heusen musical would yield the song "Love and Marriage," still sung and hummed—and enjoyed—by millions.
He was glad to have the money that the rights for the two shows yielded, but then he found he had to live with the contribution they made throughout much of the twentieth century to a popular view of Our Town as a sentimental and nostalgic work of art.
A month after the Broadway opening Wilder had fled to Arizona to complete The Merchant of Yonkers, a second play that had made the earlier trip to Switzerland. It is clear from letters that he was thinking hard about what he had learned about playwriting from his Our Town experience. He credited Jed Harris for much of its success, and would approach him two more times to direct new plays. (Harris passed.) But it is also clear that he never believed Harris fully grasped the deeper meaning of his play. In March 1938, from Arizona, he wrote his sister an opinion he appears never to have changed. The immediate context was that Eleanor Roosevelt had written a day earlier in her column "My Day" that the play had "depressed her beyond words."
I've now decided that on one plane Our Town is a very pessimistic piece. But on a higher plane it isn't. That's where Jed fell down. If you hang the planets and the years high up above the play, you can get the Reconciliation but if you don't it's crushing. Jed gypped me on "the cosmic overtones" just where [Max] Reinhardt would be best.
Less than a year later, Reinhardt, the great German director whom Wilder had idealized since boyhood, took Merchant to Broadway—and failed dismally. After the war, the play was reborn as The Matchmaker and set a Wilder Broadway record of 486 performances, 110 more than Our Town. To quote Wilder (and many others): "Theater is a funny business."
In the end, the "funny business" that Wilder sought to conquer after 1930 blessed him with great artistic and monetary success. Where Our Town is concerned, one can go further. Thornton Wilder had two sensational moments in his lifetime—one in fiction, The Bridge of San Luis Rey, and one in drama, Our Town. Had he been a baseball player, they could be compared to hitting grand slams in the bottom of the ninth with his team three runs down.
Sensations cast long shadows. Our Town's shadow is especially long and deep. It is the grand slam at the last out of the last game of the World Series. It says much about the author's drive and his sense of himself that the play's success did not cripple his art; Wilder was incapable of resting on laurels. He went on to write more plays and novels, including another Pulitzer Prize–winning drama and a novel that received the National Book Award, and busied himself to the day of his death with such a host of other literary deeds that he earned among the cognoscenti the reputation as a man of letters rather than only a novelist or a playwright.
But the Our Town shadow was long and deep—and remains so. When Wilder's turn came in 1997 to end up on a stamp, the artist did not hesitate to depict him against the backdrop of a New England landscape. The sun is setting and soon the village will be set against "the life of the stars." That is where Thornton Wilder rests.
—Tappan Wilder 2003
Thornton Wilder stamp issued on April 17, 1997, in the Thornton Wilder Hall at the Miller Memorial Central Library in Hamden, Connecticut.
Pre–Our Town
1. A Wedding: Wilder Encounters a Superstition
Many of the moments of family life in Our Town—the table talk among the children, etc.—are drawn from Thornton Wilder's memories of his own upbringing. The famous line "Pretty enough for all normal purposes" was a family "classic," and the specific mention of North Conway recalls his older brother Amos's years there from 1925 to 1928 as minister of the First Congregational Church. On June 26, 1935, Wilder served as best man in his brother's wedding to Catharine Kerlin in Moorestown, New Jersey. It was here, in the Kerlin family home, that he witnessed the future mother-in-law inform the groom at breakfast on the wedding day that he would not see his bride until the ceremony. The wedding took place in the garden. Honoring the theatrical importance of this wedding, Catharine Kerlin Wilder's bridal dress is now on permanent display at the Historical Society of Moorestown.
Pictured left to right: Amos Niven Wilder, Catharine Kerlin, and Thornton Niven Wilder
2. Life, Death, and Understanding in Wilder's Earlier Fiction and Drama
Fiction: "Once Upon a Time . . ."
Our Town, as the playwright often pointed out, was inspired in part by the story related by Chrysis the hetaira (courtesan) to the young men on the island of Byrnos in Wilder's best-selling novel of 1930, The Woman of Andros. Zeus seeks a favor that the King of the Dead cannot deny, much as he would like to. In the story, set in the pre-Christian era, we find an all but word-by-word foreshadowing of the scene when Emily returns from the dead in a no-less-mythical place on her twelfth birthday—and now understands. Fascinated by the power of memory and imagination in our lives, Wilder in 1930 described one of the themes of the novel in language echoed in Readings 3 and 6: "The difference between the matter-of-factness and almost the triviality of life as we live it and the emotion and beauty of the same life when we remember it, looking backward from years later."
Once upon a time there was a hero who had done a great service to Zeus. When he came to die and was wandering in the gray marshes of hell, he called to Zeus, reminding him of that service and asking a service in return: he asked to return to earth for one day. Zeus was greatly troubled and said that it was not in his power to grant this, since even he could not bring above ground the dead who had descended to his brother's kingdom. But Zeus was so moved by the memory of the past that he went to the palace of his brother and, clasping his knees, asked him to accord him this favor. And the King of the Dead was greatly troubled, saying that even he who was King of the Dead could not grant this thing without involving the return to life in some difficult and painful condition. But the hero gladly accepted whatever difficult or painful condition was involved, and the King of the Dead permitted him to return not only to the earth, but to the past, and to live over again that day in all the twenty-two thousand days of his lifetime that had been least eventful, but it had to be with a mind divided into two persons: the participant who does the deeds and says the words of so many years before, and the onlooker who foresees the end. So the hero returned to the sunlight and to a certain day in his fifteenth year . . .
As he awoke in his boyhood's room, pain filled his heart—not only because it had started beating again, but because he saw the walls of his home and knew that in a moment he would see his parents, who lay long since in the earth of that country. He descended into the courtyard. His mother lifted her eyes from the loom and greeted him and went on with her work. His father passed through the court unseeing, for on that day his mind had been full of care. Suddenly the hero saw that the living too are dead and that we can only be said to be alive in those moments when our hearts are conscious of our treasure; for our hearts are not strong enough to love every moment. And not an hour had gone by before the hero, who was both watching life and living it, called on Zeus to release him from so terrible a dream. The gods heard him, but before he left he fell upon the ground and kissed the soil of the world that is too dear to be realized.
Drama: "Good-By, Emerson Grammar School"
Our Town is also the dramatic child of the three experimental one-act plays that Thornton Wilder published in 1931, The Long Christmas Dinner, The Happy Journey to Trenton and Camden, and Pullman Car Hiawatha. In them, he employed such methods as minimal scenery, time compression, pantomime, and a stage manager as actor in one or in multiple parts, as he would do later in Our Town. The one-acts also explore Wilder themes already well established in his fiction, among them the repetition of family life. Chicago Tribune critic Fanny Butcher in 1931 described Pullman Car Hiawatha as "the chorus of life and death and man's relation to time and space." Managed by Samuel French after 1932, Wilder's one-acts had been produced widely by amateur groups by the time of the Our Town opening, thus helping to seed interest in his first full-length play when it first became available for amateur productions in April 1939.
The following scene is from Pullman Car Hiawatha. Harriet, married to Philip, dies as the train makes its way from New York to Chicago (passing through Grover's Corners, Ohio, along the way). The angel Gabriel and two archangels usher her to her death by climbing steps at the end of a train car, which is staged with chairs. This brief excerpt includes her last words, in form and cadence and actual words not unlike Emily's in Our Town. Wilder attended the Emerson Grammar School in Berkeley, California. He took great pleasure in using his play to thank several of his school-teachers.
HARRIET:
Oh, I'm ashamed! I'm just a stupid and you know it. I'm just another American. But then what wonderful things must be beginning now. You really want me? You really want me?
They [THE ARCHANGELS] start leading her down the aisle of the car.
Let's take the whole train. There are some lovely faces on this train. Can't we all come? You'll never find anyone better than Philip. Please, please, let's all go.
They reach the steps. THE ARCHANGELS interlock their arms as a support for her as she leans heavily on them, taking the steps slowly. Her words are half singing and half babbling.
But look at how tremendously high and far it is. I've a weak heart. I'm not supposed to climb stairs. "I do not ask to see the distant scene: one step enough for me." It's like Switzerland. My tongue keeps saying things. I can't control it. Do let me stop a minute: I want to say good-by.
She turns in their arms.
Just a minute, I want to cry on your shoulder.
She leans her forehead against GABRIEL's shoulder and laughs long and softly.
Good-by, Philip. I begged him not to marry me, but he would. He believed in me just as you do. Good-by 1312 Ridgewood Avenue, Oaksbury, Illinois. I hope I remember all its steps and doors and wallpapers forever. Good-by, Emerson Grammar School on the corner of Forbush Avenue and Wherry Street. Good-by, Miss Walker and Miss Cramer who taught me English and Miss Matthewson who taught me biology. Good-by, First Congregational Church on the corner of Meyerson Avenue and Sixth Street and Dr. McReady and Mrs. McReady and Julia. Good-by, Papa and Mama . . .
She turns.
Now I'm tired of saying good-by. I never used to talk like this. I was so homely I never used to have the courage to talk. Until Philip came. I see now. I see now. I understand everything now.
Pullman Car Hiawatha at Centerstage Theater in Baltimore in 2001 with Angela Reed as Harriet, and Craig Mathers and Willy Conley as archangels
3. Our Town in the Making: Four Drafts
What follows suggests something of the script at various stages of development. The trend is always toward an ever more spare and direct style and focus on Grover's Corners.
"M Marries N": The Birth of the Play (1935)
The stage manager uses chalk to draw the outline of the railroad car in Pullman Car Hiawatha. This technique is also used in this excerpt from Our Town's earliest known progenitor, a twelve-page sketch titled "M Marries N," written soon after Wilder's brother Amos's wedding in June 1935. Its focus is a young couple, George and Anne, discovering they are in love, and concludes with these lines:
GEORGE:
You do like me, too, don't you, Anne?
ANNE:
Y-e-s.
GEORGE:
Anne, I guess I more than like you.
They stand a moment in silence—looking at the ground.
In the scene, set after a school day, he is carrying her books. It includes many features found in Our Town, among them a soda fountain and a trellis. Grover's Corners, New Hampshire, still lies in the future. "M Marries N" is set in "an American village," also identified in the text as "Hamilton in such-and-such a State." In addition to a stage manager, the cast includes a seated fisherman, described later as "Old Philosopher, Old Irony himself, Old gimlet-eye," a figure inspired by Chinese drama.
The first page of "M Marries N," Thornton's earliest known draft of what would become Our Town
Transcription of page from "M Marries N" and subsequent half page:
Blank stage—High up left against the Proscenium column, a man sits smoking and fishing—Stage manager enters from the back of the stage in shirt-sleeves, a piece of chalk in his hand. He announces the name and author of the play. Then:
STAGE MANAGER:
You are to imagine before you an American village.
He draws two parallel lines from the back of the stage towards the prompter's box.
Here is the main street. There are two drug stores, two groceries, and a clothing and notions store. Two churches, a post office and so forth.
He waves his hand.
Trees; you know, in late spring. Thick and green. Shady. You know—twinkle-twinkle. Here at this corner is the home of our heroine's mother—This is the back door—
Two assistants push out a trellis covered with morning glories and a revolving "tree" for drying laundry on—
On this side is the favorite drug store. Here's the counter.
Two assistants go to the left and push out a counter. A rack of onyx-knobbed faucets—strawberry flavoring, chocolate flavoring and so on. They put four high stools before it.
Grover's Corners, New Hampshire, "Latitude 71° 37´, Longitude 42° 40´" (1937)
Reproduction of page 1 of the 1937 draft of Our Town
The image above is exhibited in Wilder's Yale College twentieth-reunion class book (1940). It is captioned, "Reproduction of Page One of the Original Manuscript of Our Town." Notable features include the use still of chalk by the Stage Manager (as in Pullman Car Hiawatha), the playful interaction with the audience from the start, and two brief commedia dell'arte– like entertainments for intermissions. The Long Christmas Dinner traces a family through ninety years, the inspiration for the original scheme for Act II of Our Town, a one-hundred-year history of the Webb family. The latitude and longitude lines are changed in the final version. Neither identifies New Hampshire. (The coordinates shown here mark southern Greenland. Grover's Corners in its final version is located in deep water about a thousand feet off Wharf Road in Rockport, Massachusetts.)
Transcription of page 1 of the 1937 draft of Our Town:
OUR TOWN
(Act II missing) play in Three Acts.
(No curtain.
(No scenery.
When the house-lights go down, the STAGE MANAGER
in overalls, has been leaning up for some time against
the proscenium pillar, smoking a cigarette, and staring
drily at the arrivals in the audience. At last, in a
very Yankee accent, he begins to speak:
STAGE MANAGER:
This play is called "Our Town." It was written by Thornton Wilder. It is produced and directed by Jed Harris, and it is acted by Miss X, Miss Y, Miss Z; Mr. A, Mr. B., Mr. C; and many others.
The First Act shows a day in Our Town; the second act shows a century in our first family's home, and the last act shows—well, you'll see.
Between the First Act and the Second, there will be played an interlude called "The Pleasures and Penalties of Automobiling"; and between the Second and Third Acts, there will be another interlude—a propaganda piece called "Is the Devil Entitled to a Vote?"
Are you ready?
He looks at the lady who arrived late. She shakes her head amused, saying Tz-Tz-Tz, implying What'll they do next!
This is Our Town, Grover's Corners, New Hampshire. It's near the Massachusetts line—Latitude 71° 37´, Longitude, 42° 40´. The date is Friday, May 7, 1907.
He looks hard at the lady again and repeats "1907."
It's dawn.
The sky is beginning to show some streaks of light behind our mountain, over in the East there. The morning star is doing that last excitement it always goes into just before dawn.
I'll draw the plan of the town for you.
Chalk in hand he goes to the back of the stage and draws two parallel lines down the center of the stage toward the footlights.
Way back here is the railroad station and the . . .
"Good Night to You All, and Thank You" (1937)
This version of the play's closing lines, worked on in Switzerland and subsequently revised, includes a ghostlike evening "visit." In final form, Emily inherits Mrs. Gibb's lines about understanding, and George "sinks to his knees then falls full length at Emily's feet" rather than flinging himself down, as he does here. A transcript of this text follows.
Final page of the 1937 draft of Our Town
Transcription:
The chairs are being replaced for the cemetery. The "dead" come on, and gather about her.
EMILY:
I didn't listen to you. Now I just want to be quiet for a while. That's all human beings are—just blind people.
MRS. GIBBS:
Sh! Sh! It's evening now. The Evening Visit.
EMILY:
What visit?
MRS. GIBBS:
Sh.
Apparently something has appeared to them, invisible to us. They all face it, with breathless attention, and follow it as it crosses the stage, like a breeze across a wheatfield, each bows his head slightly in succession. When it has gone EMILY whispers enthralled:
EMILY:
Every evening?
MRS. GIBBS:
And morning?
EMILY:
The weight's gone. . . . Let me sit by you.
She leans her head against MRS. GIBBS [sic] shoulder.
GEORGE enters. He comes and stands a moment before his mother's chair, his lower lip pressed hard against his upper. Then he goes over to the corner where Emily's grave is. He stands a moment; then flings himself full length upon the stage. EMILY raises her head and stares into her mother's face.
MRS. GIBBS (softly):
They don't believe what they're told. They don't listen to what they're [sic] heart tells them, do they?
STAGE MANAGER
(back at his proscenium with a cigarette):
That's all there is of this play. Good night to you all, and thank you.
"I'll run for something . . .": George Gibbs's Political Aspirations (1938)
From the Stage Manager's prompt script, Act II of Our Town
This page is from the soda fountain scene from the Our Town production stage manager's "Prompt Script," the official record of the actual production. Assuming that George may leave Grover's Corners, we learn here that he harbors political ambitions and, in addition to merely corresponding with a good friend, may someday welcome local intelligence from a reliable source.
Are we surprised? There are always high school senior-class presidents who dream of becoming governors or even presidents, and adoring girlfriends who share their dreams. But Wilder's goal was immersion in a New Hampshire village that was "an allegorical representation of all life" (see Reading 6). In rehearsals a change was made—the key lines were deleted, as shown in this reading and as printed below. But a line related to the statewide scenario slipped into the wedding scene in the Our Town Samuel French Acting Edition where the Stage Manager says: "Maybe [Nature's] tryin' to make another good Governor for New Hampshire. That's what Emily hopes . . ." Wilder removed this line when he crafted his definitive version of Our Town in 1957.
Transcription:
EMILY:
It certainly seems like being away three years you'd get out of touch with things.
GEORGE:
No. No. I mustn't do that. You see, I'm not only going to be just a farmer. After a while maybe I'll run for something to get elected. So your letters'll be very important to me—you know, telling me what's going on here and all.
[with a pick up in Emily's speech] ". . . Maybe letters from Grover's Corners . . ." etc.
4. The Writing of Our Town: Here and Abroad
MacDowell colonists—artists, writers, musicians, and architects—work in solitude, each in a separate studio, on a four-hundred-acre farm of woodland and meadow in Peter-borough, New Hampshire. Wilder made nine official visits to MacDowell between 1924 and 1953. During his sixth, in June 1937, he worked almost exclusively on Our Town in Veltin Studio, shown here.
Veltin Studio, the MacDowell Colony in Peterborough, New Hampshire
His walks through the countryside and the town were important influences on the work. Local legend has it that Fletcher Dole and Albert E. Campbell, respectively Peterborough's milkman and druggist in this period, inspired the characters in the play. (Both were members of a delegation, led by the governor, that attended the world premiere of the Our Town film in Boston in May 1940.) When asked if he knew Wilder, Dole is reputed to have replied, "Nope, but he knew me." When asked if Peterborough was Our Town, Wilder always shifted the question to a global perspective, as in this reply to reporter John Stevens, who was in Peter-borough to cover Wilder receiving the first Edward MacDowell Medal in the summer of 1960:
"Young man," he said, "Grover's Corners is your home town in New York and mine in Wisconsin. It's everyone's home town. I have received letters from people in Chile, Iran and Iraq who have read or seen the play. Despite sociological differences, they tell me they have readily identified their everyday experiences with those of Our Town's George Briggs [sic] and Emily Webb, and Howie Newsome and the tormented, dipsomaniacal Beethoven trapped in Grover's Corners . . ." (New York Times, August 21)
The revisions of the first two acts and much work on the final version of Act III of Our Town occurred in Switzerland, where Wilder spent two months in September 1937. He was based at the Hotel Belvoir in Rüschlikon on the edge of Lake Zurich some five miles from the center of Zurich. Here he combined his writing with long walks along the lake and into the city and brief side trips out of town. Because of the importance of Our Town, the Hotel Belvoir can be described as one of the most famous addresses in Wilder's peripatetic life as a creative artist.
He had already published novels set in such exotic places as seventeenth-century Peru and a mythical Greek island about two hundred years before the birth of Christ. He wrote in the late 1920s that his work was "French in form and manners (Saint-Simon and La Bruyère); German in feeling (Bach and Beethoven); and American in eagerness." By the middle and late 1930s the "eagerness" was evident in such short plays as Pullman Car Hiawatha and The Happy Journey to Trenton and Camden (both 1931), and in the novel Heaven's My Destination (1935). Our Town had expanded to evoke his signature, lifelong commitment to celebrating the connection between the commonplace and the cosmic dimensions of the lives of hardworking, humble, middle-class American men and women. (See next Reading.)
The Hotel Belvoir in Rüschlikon as it appeared in the 1930s
The Princeton Flyer—first advertisement for Our Town
Our Town on the Boards
5. In Production: Sample Images
The McCarter Theatre, Princeton, New Jersey (1938)
Our Town's first public performance took place at the the McCarter on January 22, 1938. The fine print of this advertisement reads, "The record of a tiny New Hampshire village as created by the lives of its most humble inhabitants." The premiere performance attracted an appreciative capacity audience. Wilder described it as composed of "fashionable villa colony; academic bourgeoisie; and students."
The Broadway Program (1938–39)
The following image is the cover of the program used during the play's run at the Morosco Theatre on Broadway. The dramatically large plume of smoke is a deadly accurate reminder of a defining feature of New Hampshire mill towns in the nineteenth and early twentieth centuries. Wilder was well aware of this satanic feature of these communities, offering glimpses of it in references to the successful Cartwright interests in manufacturing and banking. He would refer those interested in more details to Herman Melville's brutal short story "The Tartarus of Maids" (1855).
Our Town's first Broadway program
Two Original Cast Photographs
Frank Craven (Stage Manager) and Arthur Allen (Professor Willard) in the original Broadway production of Our Town (1938)
This rarely reproduced Vandamm shot shows the Stage Manager (Frank Craven) instructing Professor Willard (Arthur Allen) in Act I "to sketch in a few details of our past history here." From the Boston preview, Wilder wrote Alexander Woollcott that Craven was "lovable" but had so much Irish blood that he left Wilder longing for "that deep, New England stoic irony that's grasped the iron of life and shares it with the house." He was likewise critical of Allen playing the part for laughs. "The Professor, adored by the audience and always clapped to the echo, is a caricature," Wilder wrote Woollcott. (The problem persists; it is always tempting to play this part for laughs.)
Act III. Emily arrives at her grave for the first time.
Because it gives a full sense of Wilder and Harris's use of the bare stage and depicts Emily's arrival at her grave in Act III, this Vandamm photo is the most widely reproduced shot of the original Broadway production. For many years it was included at the beginning of the acting edition. Martha Scott, who played Emily, was a last-minute addition to the cast. Wilder adored her performance.
The use of the bare stage was novel, but not unique, in 1938. Life magazine's extensive photographic coverage of the play was captioned "Thornton Wilder's 'Our Town' is the latest in the Bare Stage." In addition to discussing other plays, the article included a reproduction of a New Yorker cartoon of the day showing three determined matinee ladies at a ticket booth. The first asks, "Does this play have scenery?"
6. The Playwright Discusses His Play
In company with most writers, Thornton Wilder did not believe it his job to both write and explain his novels and plays. Even so, he was always an enthusiastic champion for his work and put on quite a show when interviewed, as revealed here. The first is an interview given before Our Town had gone into rehearsals; the second is a preface to Our Town, published eight days after the Broadway opening; and last, an interview given four months later.
December 7, 1937—Before Rehearsals
"Sense of the Whole"
Our Town's producer-director Jed Harris let Wilder out of "prison" on Long Island to be interviewed for an article published on December 7, 1937, in the New York World- Telegram, from which this excerpt is taken. Wilder's words characteristically range over his calling, the nature and appeal of drama as an art form for the times, and the nature of his own play. A Doll's House opened in New York on January 27, 1938, and set a Broadway record for the work (144 performances). To write drama full-time, Wilder had given up his teaching post at the University of Chicago in 1936.
Jed Harris (Yale '21) has Thornton Wilder (Yale '20) under lock and key out Port Washington way. This is because Professor Wilder has to finish an original play called Our Town which Mr. Harris is waiting to put into rehearsal.
Every other day or so, however, Mr. Harris lets Mr. Wilder come to town (under surveillance); and in town he was today, pacing about Mr. Harris' office in the Empire Theater Building.
You may know Mr. Wilder as "the professor," or as "the man who wrote The Bridge of San Luis Rey," but Mr. Wilder, from now on, wants to be known as Mr. Wilder, the dramatist. . . .
The author of—in addition to The Bridge—The Woman of Andros and Heaven's My Destination is not exactly making his theatrical debut. Some years ago the town saw his translation of M. André Obey's Le Viol de Lucrèce; he has written a quartet of one-acts and an adaption of Ibsen's A Doll's House, abetted by the incomparable Ruth Gordon as Nora, is even now hovering in Chicago preparatory to a descent upon Manhattan. Nevertheless:
"I feel," says Mr. Wilder, "that my whole life has been an apprenticeship to writing for the theater.
"You see (eagerly) imaginative story telling consists of telling a number of lies in order to convey a truth; it is a rearrangement of falsehoods which, if it is done honestly, results in verity.
"Now, the thing which most appeals to me about the theater is the absence of editorial comment. There is arrangement, of course, but at least you do not have in the theater, as in the novel, a single fallible human being claiming Godlike omniscience.
"To be sure, it is something of an illusion, but I regard it as a great good."
Mr. Wilder leaned back in his chair, lit another cigarette and went on. One felt as though one were in an especially pleasant classroom.
"Another thing. It is always now on the stage. The stage lives in the pure present; it offers always the pure action and not someone's digestion of that action. . . .
"The play—well, you might say that it is kind of an attempt at complete immersion into everything about a New Hampshire village which, I hope, is gradually felt by the audience to be an allegorical representation of all life.
"It is an idea which has teased me for a long while, but you could say that it was really done—most of it—last summer in a little hotel near Zurich.
"You know, I'm a Wisconsin boy from State of Maine stock, but I spent six summers tutoring in a New Hampshire camp and six summers as a guest of the MacDowell Colony at Peterborough and you can't help but be absorbed by the New Hampshire quality.
"How would I define that? Why, it's independence, understatement—a dry, humorous sense, and, within the walls of the home, a wonderful, congenial homeliness. Lacking in warmth? Not if you know the idiom.
"I used to think about them on the evening walks of twelve summers. There are others I know better, but this is basically a generalization, and it is hard to generalize about one's neighbors.
"I wanted to pile up a million details of daily living, with some sense of the whole in living and dying—San Luis Rey, if you please. I think it the business of writing to restore that sense of the whole."
February 13, 1938—Nine Days after Opening
"A Village Against the Life of the Stars": Our Town's First Preface
No doubt at the request of Brooks Atkinson, Wilder published what he boldly titled "A Preface for Our Town" in the New York Times on February 13, 1938. The play was safely lodged in the Morosco Theatre when it appeared on page one of the paper's Sunday Arts section. Throughout his life Wilder referred to his formative experience in Rome (1920–21) while studying archaeology. This influence is more than suggested in the excerpt from a letter Wilder wrote to his family in 1921, which concludes this Reading.
For a while in Rome I lived among archeologists, and ever since I find myself occasionally looking at the things about me as an archeologist will look at them a thousand years hence. Rockefeller Center will be reconstructed in imagination from the ruins of its foundations. How high was it? A thesis will be written on the bronze plates found in New York's detritus heaps—"Tradesmen's Entrance," "Night Bell."
In Rome I was led through a study of the plumbing on the Palatine Hill. A friend of mine could ascribe a date, "within ten years," to every fragment of cement made in the Roman Republic and early Empire.
An archeologist's eyes combine the view of the telescope with the view of the microscope. He reconstructs the very distant with the help of the very small.
It was something of this method that I brought to a New Hampshire village. I spent parts of six summers tutoring at Lake Sunapee and six at the MacDowell Colony at Peterborough. I took long walks through scores of upland villages.
And the archeologist's and the social historian's points of view began to mingle with another unremitting preoccupation which is the central theme of the play: What is the relation between the countless "unimportant" details of our daily life, on the one hand, and the great perspectives of time, social history, and current religious ideas, on the other?
What is trivial and what is significant about any one person's making a breakfast, engaging in a domestic quarrel, in a "love scene," in dying? To record one's feelings about this question is necessarily to exhibit the realistic detail of life, and one is at once up against the problem of realism in literature. . . .
I wished to record a village's life on the stage, with realism and with generality.
The stage has a deceptive advantage over the novel—in that lighted room at the end of the darkened auditorium things seem to be half caught up into generality already. The stage cries aloud its mission to represent the Act in Eternity. So powerful is the focus that it brings to bear on any presented occasion that every lapse of the author from his collaborative intensity is doubly conspicuous: the truth tumbles down into a heap of abject truths and the result is doubly trivial.
So I tried to restore significance to the small details of life by removing scenery. The spectator through lending his imagination to the action restages it inside his own head.
In its healthiest ages the theater has always exhibited the least scenery. Aristophanes' The Clouds—423 B.C. Two houses are represented on the stage; inside of one of them we see two beds. Strepsiades is talking in his sleep about his racehorses. A few minutes later he crosses the stage to Socrates' house, the Idea Factory, the "Thinkery." In the Spanish theater Lope de Vega put a rug in the middle of the scene—it was a raft in mid-ocean bearing a castaway. The Elizabethans, the Chinese used similar devices.
The theater longs to represent the symbols of things, not the things themselves. All the lies it tells—the lie that that young lady is Caesar's wife; the lie that people can go through life talking in blank verse; the lie that that man just killed that man—all those lies enhance the one truth that is there—the truth that dictated the story, the myth. The theater asks for as many conventions as possible. A convention is an agreed-upon falsehood, an accepted untruth. When the theater pretends to give the real thing in canvas and wood and metal it loses something of the realer thing which is its true business. Ibsen and Chekhov carried realism as far as it could go, and it took all their genius to do it. Now the camera is carrying it on and is in great "theoretical peril" of falling short of literature. (In a world of actual peril that "theoretical peril" looks very farfetched, but ex–college professors must be indulged.)
But the writing of the play was not accompanied by any such conscious argumentation as this. It sprang from a deep admiration for those little white towns in the hills and from a deep devotion to the theater. These are but the belated gropings to reconstruct what may have taken place when the play first presented itself—the life of a village against the life of the stars.
In an earlier draft of the play there were some other lines that led up to those which now serve as its motto. The Stage Manager has been talking about the material that is being placed in the cornerstone of the new bank at Grover's Corners, material that has been chemically treated so that it will last a thousand or two thousand years. He suggests that this play has been placed there so that future ages will know more about the life of the average person; more than just the Treaty of Versailles and the Lindbergh Flight—see what I mean?
Well, people a thousand years from now, in the provinces North of New York at the beginning of the Twentieth Century, people ate three times a day—soon after dawn, at noon, and at sunset.
Every seventh day, by law and by religion, there was a day of rest and all work came to a stop.
The religion at that time was Christianity, but I guess you have other records about Christianity.
The domestic set-up was marriage, a binding relation between a male and one female that lasted for life.
. . . Anything else? Oh, yes, when people died they were buried in the ground just as they were.
Well, people a thousand years from now, this is the way we were—in our growing-up, in our marrying, in our doctoring, in our living, and in our dying.
Now let's get back to our day in Grover's Corners. . . .
Thornton Wilder to his family, from Rome, 1921:
I went with an archeological party the other day to a newly discovered tomb of about the first century; it was under a street near the center of the city, and while by candle-light we peered at faded paintings of a family called Aurelius, symbolic representations of their dear children and parents borne graciously away by winged spirits playing in gardens and adjusting their Roman robes, the street-cars of today rushed over the loves and pieties and habits of the Aurelius family, while the same elements were passing over in Orelio families that will be as great an effort to recover two thousand years from now, as pleasing an effort, and as humanizing.
"Take Your Pencil . . ."
On May 2, 1938, Our Town received the Pulitzer Prize for drama. The press came calling. To the clearly bewitched reporter from The Sun (New York), Henry Strickler, Wilder granted a classic, wide-ranging interview published on May 14. He was particularly interested in talking about the charge that his play was guilty of the crime of sentimentality—and speak he did as we see in this excerpt from Strickler's piece:
Thornton Wilder and the reporter were sitting at a desk in the Jed Harris office, trying to launch an interview. Plainly the situation was out of hand.
Mr. Wilder had answered the preliminary questions as to where he had been, how long he was going to be in New York and how it feels to be the author of a Pulitzer Prize winning novel, The Bridge of San Luis Rey, 1928, and a Pulitzer Prize winning play, Our Town, 1938.
The reporter, searching the folds of his ignorance for an opening, asked Mr. Wilder where he got his story ideas. Mr. Wilder said they came to him on hikes and in the shower and places. The reporter couldn't remember having broken out with anything but a sweat, sunburn and a rash on hikes. Nor could he recall ever having got anything out of a shower but water, a lingering case of athlete's foot and a nasty bruise. So he just stared at Mr. Wilder, who can walk a mile, take a shower and come down with a full-grown second act.
Mr. Wilder broke the uncomfortable silence by guessing correctly that the reporter was from the MidWest, a fact constantly betrayed by a rustic inflection of speech. The interview threatened to fall off into football amid many inane pleasantries, but Mr. Wilder, sensing an impasse, took the bull by the horns.
"Take your pencil," he ordered, getting out of his chair. He flicked the ash from his cigarette, made two complete hikes around the room in meditation and then began dictating in short, easily penciled phrases.
"Many people have charged the play Our Town of being sentimental. The charge seems to be that the home life of the people represented in the play is too uniformly felicitous and the description of the state after death too literal and too idyllic. It is true that village life anywhere presents a proportional element of boredom, small-minded community interference and tragic occasions.
"The literary description of New England has generally occupied itself with similar disproportionate descriptions of avarice and horrifying behavior of the remote farmers whose families' consanguinity, isolation and back-breaking work have developed occasions of violence and crime."
Mr. Wilder was by this time circling the room at the rate of about two revolutions per paragraph.
"The proportion of good and ill in Our Town," he continued, "has been frankly cast on the happier side because it is established as a view of the village of 1901 seen through the eyes of 1938.
"Eight out of ten find that memory has selected from their earlier years the more touching and affectionate aspects of their early life. Death, separation and distance have condoned whatever elements are painful."
"Isn't that true?" Mr. Wilder asked, directly addressing the reporter.
"Absolutely," the reporter replied. "What was that last word?"
"Painful," Mr. Wilder said, and started circling again.
"As to the description of the afterlife," he continued, "nothing is more surprising to me than being told that it is original, for it is a transcript of the tone of the first of ten cantos of Dante's "Purgatory" where the newly dead are shown in patient waiting, being—quote—weaned away—unquote—from the attachments of their earthly life and in expectation of some ultimate purification and translation, a doctrine held as an article of faith for many centuries.
"Sentimentality may be described as the distortion of the objective facts of experience felt by the majority of mature persons, a distortion upon material to satisfy wishful fancies that spring from personal identification with the characters in situations presented."
Mr. Wilder sank into his chair in silence in the nick of time. The reporter was about to suffer a stroke of writer's cramp. Mr. Wilder reached over into a bowl of hitherto unnoticed candy and began popping pieces into his mouth while he meditated.
7. Wilder vs. Harris: Before and After
The inside flap of the dust jacket of the first reading edition of Our Town listed seven gorgeous raves hailing not "Thornton Wilder's new play," but "the Jed Harris production of Our Town." This is understandable. In 1938 Thornton Wilder was a new face on Broadway and Jed Harris was a theatrical legend eager to regain his footing and fame. The next two sections open the door on the subject of their stormy collaboration and how it played out in their differing views about the tone of the play.
"Lean, dark, and hungry looking," "scorched with ambition," marked by "a remarkable set of phobias" and "hatreds"—these are a few of the adjectives Richard Maney employs in his portrait of the producer-director Jed Harris in Fanfare (1957). Maney concludes with these words about the Broadway legend who appeared on the cover of Time on September 3, 1928: "Whatever demons have pursued him, he has a knowledge of the theater and a skill in it unmatched by any of his fellows. There are no peaks he might not have scaled had he cared to muffle his malice. The obstacles which stymied him were his own creations." Martin Gottfried sub titled his 1984 biography of Harris "The Curse of Genius." He concludes his recital of Harris's brilliance and self- destructive behavior: "[Harris] had predicted before it began that he'd burn out young. Instead, arrogance, egotism, cruelty, and Machiavellianism had kept his talent from being spent and that was his greatest tragedy."
Harris was the price Wilder paid for the success of his Our Town. He paid it with gritted teeth, moments of great anger (unusual with Wilder), and admiration. He did so because he also saw what Maney saw in Harris, "a knowledge of the theater and a skill in it unmatched by any of his fellows." This was the Harris that Wilder admired so much when they became close friends in the late twenties; and this was the Harris that his Yale classmates could still recall vividly twenty years later when they wrote of the undergraduate who once "lived in Welch [Hall] and read Ibsen for breakfast." (Wilder may have known Harris during the latter's abbreviated stay as a Yale student.)
Like a moth drawn to a flame, Wilder made the relationship with Harris in 1937–38 needlessly stressful. First, because he knew it would "hurt Jed's feelings," he elected not to mount Our Town through his own highly regarded agent, Harold Freedman. Second, he did not invoke the powers he had under the production contract—signed ten days before the Princeton performance—that forbade changes in the script without his approval. He rectified the first mistake immediately after the play opened, a decision that infuriated Harris. (Freedman's first job was to deal with bounced checks from Harris's office.) The second Wilder fixed over time by virtue of the fact that, at the end of the theatrical day, he controlled the printed page. Where Our Town is concerned, this process partially ended in 1957 when Harper and Row published the playwright's "final" approved version—the one used in this edition—and only completely ended in 2013, with release of the play's corrected acting edition published by Samuel French.
What follows lifts the curtain on Wilder's differences with Harris regarding additions and deletions in his manuscript. All stemmed from one root complaint: Wilder's view that Harris was turning his play into a folksy drama for two acts connected to a harrowing last act that left the audience in too many tears.
Before: Wilder's Critical Response to Harris's Directing Choices
The first page of Wilder's handwritten, sealed note regarding Jed Harris's direction of Our Town
On the afternoon of the Princeton opening, Wilder wrote and sealed this note in which he outlines his grievances regarding Jed Harris's direction of Our Town. Isabel Wilder, his sister, opened it at the time of the play's first New York revival in 1944, and again before the play's 1946 production in London. Both productions were directed by Harris (with Isabel as the playwright's representative), and concluded his contractual rights in the play. There is no evidence that Harris ever read this note—or wanted to. It is printed in its entirety here.
The following Elements in the Production of "Our Town" are likely to harm and perhaps shipwreck its effectiveness:
1. The First Act—and in large measure the play—is in danger of falling into trivial episodes, through failure to build up the two great idea-pillars of the Stage-Manager's interruptions. The Professor's speech has been reduced to pleasant fooling, instead of being made forceful and informative, as I have often requested; the Passage on the future has been watered down, and the actor has not been vigorously directed.
2. The element of the Concrete Localization of the Town has been neglected—in fact, the Director has an astonishingly weak sense of visual reconstruction. Characters talk to one another from Mrs. Webb's back door to Main Street; and from one end of Main Street to another in the same tone of voice they use when they are in the same "room." They stroll practically in and out of Main Street when they are in a house; Emily's grave is one minute here and soon after there.
3. In spite of express promises to remove them a series of interpolations in the First Act remain; each one of these has the character of amiable dribbling, robbing the text of its nervous compression, from which alone can spring the sense of Significance in the Trivial Acts of Life, which is the subject of the play.
4. The recent alterations to the closing words of Mrs. Gibbs and Emily in Act III are soft, and bathetic.
5. There seems every likelihood that a pseudo- artistic inclination to dim lights will further devitalize the Stage-Manager's long speeches; and the last Act. The eternal principle that the ear does not choose to hear, if the eye is not completely satisfied, particularly applies in this play.
After: Wilder's Notes to Harris Regarding Subsequent Productions of Our Town
Despite his efforts during the original production to rid the script of Harris's "tasteless alternations," Wilder discovered that several had crept back into the text as Harris prepared to direct the war-delayed London premiere in 1946. Wilder concluded with an appeal to avoid tears and to keep speeches "un-lugubrious," an adjective he also used in his "Some Suggestions for the Director" in the acting edition. The reading is printed in its entirety. All changes are part of the play today.
April 7, 1946
THE TEXT OF "OUR TOWN" FOR THE LONDON
AND ALL sUBSEQUENT PRODUCTIONS
In spite of the fact that I left in the Jed Harris offices three copies of the specifically marked Definite Copies of the text of the play, I found during the final rehearsals of the play a number of unauthorized readings were still being used. I called Jed Harris's attention to them; he made notations of the readings, and assured me they would be corrected.
I hereby wish to prepare this memorandum for control of the text as presented in England.
Page references are to the Samuel French Acting Edition.
Page 8. Howie Newsome, the milkman, does not say "Twins, eh? That's good news for a man in my business"—but "Twins, eh? I declare, this town's getting bigger every year."
Page 15. Mrs. Webb, after saying ". . . That's how I got to see the Atlantic Ocean, y'know," does not give the speech about "biggest fools coming from Boston." The scene is concluded by Mrs. Gibbs saying: "Oh, I'm sorry I mentioned it. Only it seems to me that once in your life before you die, you ought to see a country where they don't talk in English and don't think in English, and don't even want to."
Page 25. The Stage Manager at the conclusion of the speech is requested to retain both the words and the spirit of the words: "So—people a thousand years from now—this is the way we were, etc."
Page 50. After the words ". . . and particularly the days when you were first in love;" I wish the speech to continue (as in all published texts): "when you were like a person sleeping [sic] walking, and you didn't quite see the street you were walking in, and you didn't quite hear everything that was said to you."
If the actor feels unable to cope with them he may omit the next two sentences in the French Edition.
Page 58. By inadvertence or a typist's error the following phrase was omitted from the "French" edition, though it is in the "library" edition and was used by Frank Craven. After: ". . . interested in quantity; but I think she's interested in quality, too—" comes: "—that's why I'm in the ministry."
The author particularly requests those responsible for maintaining the continued freshness of performances to watch the following passages which experience has shown are likely to become conventional with repetition:
Act III. The speeches of the seated dead must be kept "matter of fact" and un-lugubrious.
Act II. Emily is to refrain from tears and sobbing after she has entered the Drugstore.
Act II. George with his mother and Emily with her father in the scene immediately prior to the wedding are to use moderation in weeping and embracing.
Act II. Mrs. Webb in her address to the audience prior to the wedding is to use restraint in emphasis and not to weep or sob at all.
—Thornton Wilder
Special Features and Legacy
8. Wilder as Actor
During the Broadway run, Wilder filled in for two weeks as the Stage Manager for Frank Craven in September 1938. Taking account of his royalty income, he charged a reduced fee of a hundred dollars a week, which he donated to the Actors Fund. Acting made him a better playwright, he often said. It also allowed him, that September, to delete lines that Harris had inserted into his play.
Wilder appeared in the role of the Stage Manager in five summer stock productions of Our Town in 1939–40. After the war he acted in both Our Town and The Skin of Our Teeth. In total, he performed the role of the Stage Manager some twelve times in summer stock—his last appearance at Williamstown in 1959 when he was sixty-two.
How did he play the role? Avoiding Craven's "soft Irish whimsy," he always "tried to play it straight," as he informed a New York Times reporter covering his final appearance in the role in 1959.
In May 1950, a local reporter saw it this way when Wilder appeared as the Stage Manager at the College of Wooster in Ohio.
Mr. Wilder plays the stage manager with a casual informality that is somewhat deceptive. He is confidential, humorous, intense, philosophical by turns, but always so informal that you do not for some time appreciate the rhythmical control with which he shapes the play. The immense air of reality which infuses the play results from his apparently simple but intense demonstration of its fundamental themes. I forgot at times that he was acting; then I was not sure whether he was practicing the art that conceals art or demonstrates the fundamental truths of the play so impressively and effectively because he so intensely believed them. Whatever the art, I found myself eagerly awaiting his every reappearance because he established for me a more intimate connection with the stage than I have often felt.—F.W.M. (Wooster Daily Record, May 10, 1950)
9. Wilder as Adviser
Wilder advises (left to right) Bertrand Mitchell (director), Jennifer Holt (Emily), and John Stearns (George)
Although playing the role as naturally as possible, Wilder also saw the Stage Manager's character evolve from a friendly to a distant presence as the play progressed. In a letter of May 31, 1975, written seven months before his death, Wilder wrote to Michael Kahn this advice about how to perform the part of the Stage Manager. At the time, Kahn was preparing to direct Our Town at the American Shakespeare Theatre with Fred Gwynne cast in the role:
He now grows from a small-town cracker-barrel, ruminative philosopher—always with a slight smile coming and going—to an almost supernatural spirit presiding over the town affairs. In the last act, he stands gazing over the heads of the audience with a slight smile when Emily asks: "But it's time isn't it?—I can . . . ?" His smile is still relaxed; he nods but he doesn't face her.
Wilder served as an informal adviser when the Peter-borough Players first performed Our Town in 1940. They have since performed it six more times; the last production, in 2008, starred the late James Whitmore.
What did he advise? The Manchester Union-Leader reported him saying that he "never meant that cemetery scene to be so depressing," a view that led the director, who stood firm for a belief in eternal life, to plan to have the dead do "natural things like shelling peas or knitting and smoking." Whether Wilder approved of such an approach is not known. (He almost certainly did not.) What is known is that he advised the cast of Elizabeth Dillon's production at the Trenton Central High School in Trenton, New Jersey, in 1948, to handle act 3 with restraint (no doubt he had Jed Harris's Our Town in mind):
There is one injunction I always like to recommend: The last act is not to be played lugubriously. The seated dead are tranquil and the remarks about the weather are spoken in a perfectly matter-or-fact voice. The Stage Manager's remarks are kept "dry" also,—important things but assured and neither with emotion nor edification,—i.e., statements. Some companies, to my distress have not only staged the last act in darkness but with long doleful pauses,—and have "telegraphed" that gloom throughout the preceding acts! The whole play is set in the daily, daily life that we know and which particularly in New England is understated.
10. Wilder Abroad
Isabel Wilder (1900–95), a novelist and graduate of the Yale School of Drama, served as Thornton's deputy for many years. These excerpts from a letter to their older brother, Amos, written January 24, 1946, paint a lively picture of interest in Our Town and The Skin of Our Teeth in pre- and postwar Europe and Japan, and describe the foundation of Wilder's highly visible role in European, especially German, artistic and academic circles for many years. In 1973, Arena Stage (Washington, DC) took Our Town to the Soviet Union. The production was an enormous success.
Wilder was a great admirer of the fearless Elsa Merlini. "Shades of Dante" refers to the influence of Dante's Purgatorio, which Wilder taught at the University of Chicago, on setting the tone in Act III. Merlini is pictured on the opposite page with two unidentified actors in a production of Piccola Città in Milan in 1946.
Elsa Merlini (Emily) in Piccola Città, Milan, 1946
News from Abroad: Letter to Amos
Dear Amos and Family,
Let's see now, OUR TOWN. War stopped the plans for the English production slated for early 1940. This is interesting,—It was done by Red Cross (U.S.) and U.S.O. with a couple of English actors added in London for Armed Services only. It created such excitement and success that the "great" of the English theatre heard about it sent letters to the London Times (DAME Sybil Thorndike, Charles Cochrane, etc.) asking that in the "interest of Anglo-American" culture and relations and understanding, etc. it be given to the whole English public. Army orders forbade that. But the British government's attention was brought to the matter and in the autumn of 1944 they were to do the extraordinary thing of issuing permits for a company of professionals to go from New York with a production to tour England and settle down in London. (I was going.) The Battle of the Bulge stopped that, now it is to be, main characters American, directed by Jed Harris, original director-producer, produced there by Hugh Beaumont (foremost English firm), minor casts English, by April first.
In 1939 it was done in Rome by Elsa Merlini, leading Italian actress who has her own company. The opening night a leading Fascist politico tried to stop the performance, he and his group in the audience started catcalls and speeches. Merlini came to the front of the stage and above the uproar asked the audience if they wanted her to go on. They cried yes, yes, and the rebels were thrown out. Their complaint had been that it was an anti-Fascist play. Good plays, better plays were written by Italians but weren't produced while undeserving foreign importations were done instead.
Merlini has toured Italy for years; with it in her repertory "Piccola Citta" is a household word. Thornton was told by her, (he met her several times in Rome and Naples last winter) and others (he did not see the production) that many Italians did not completely understand Act I and II but they adored and understood Act III and waited patiently for Act III. Shades of Dante!
It was done long ago in Zurich and was a great success; ditto Skin [The Skin of Our Teeth]. Sweden. Buenos Aires. Pirated and performed in Spain. It was the first foreign play to be done in Berlin shortly after the Occupation. The Russian authorities stopped it in 3 days. Rumors give the reason it was "unsuitable for the Germans so soon,—too democratic." It is now in preparation in the American Section. We have heard direct, aired program and reviews from Munich. Wonderfully played there. A great and moving success. A letter from our Swiss agent who handles the German translation says it is being done everywhere in Germany—they somehow get the script and do it. Yugo-slavia asked T. for it when he was there,—in the interest of cultural relations. Budapest, Czechoslovakia. The requests come in every day. A Rockefeller Doctor travelling in Holland said he'd seen a U.S.O. performance. Our boys adored it. (As everywhere. It was out 8 months for our homesick troops.) Native Hollanders heard about it, asked for it, and have done it themselves. Today I am answering a letter from the University of Delft. The University is having a festival to celebrate Holland's liberation. They want to do SKIN OF OUR TEETH, saying it speaks for them, the whole world at this time rising out of ruins. Our authorities in Japan have written for permission to have Our Town translated and given to the Japanese native theatres for its importance of the American and democratic way of life and the art and literature it represents. Etc. Etc. It was done in prison of war camps. . . . Does this answer your question? You can't say too much!
Love to all, [Isabel]
Act III of Our Town, 2011 production at the New National Theatre, Tokyo, Japan. With Kazuki Kosakai (Stage Manager) and Yuki Saito (Mrs. Gibbs), directed by Hachiya Mizutani.
Our Town continues to be played around the world, with productions in more than thirty countries since 2000.
L'Envoi
11. Final Thoughts: "Value above All Price . . ."
Wilder's gloss in his handwriting on his famous lines.
No line is more quoted in theater programs about Our Town than this sentence from Wilder's 1957 preface to Three Plays. Among his papers is his handwritten editorial note, probably written in the 1960s, in which he calls this line "absurd." The note is quoted in full below. Did he make this annotation for a reason—perhaps simply for the record? We don't know. But it is probably Thornton Wilder's last word on what he felt he had accomplished when he wrote a play called Our Town.
The play is an attempt to find a value above all price for the smallest events in our daily life. But that is absurd. The generations of men follow upon one another in apparently endless repetition. They are born; they grow up; they marry; they have children; they die. Where shall we seek a "value above all price" in these recurrent situations?
The audience in a theatre watches human beings caught up in the happy or unhappy vicissitudes of circumstance. The audience knows more about what most concerns the characters than they can ever know themselves. The audience is given a more than human vision.
In the last act of "Our Town" the author places upon the stage a character who—like the member of the audience—partakes of the "smallest events of our daily life" and is also a spectator of them.
She learns that each life—though it appears to be a repetition among millions—can be felt to be inestimably precious. Though the realization of it is present to us seldom, briefly, and incommunicably. At that moment there are no walls, no chairs, no tables: all is inward. Our true life is in the imagination and in the memory.
Acknowledgments
The Overview of this volume is constructed in large part from Thornton Wilder's words in unpublished letters, journals, business records, and publications not easy to come by.
Many Wilder fans have helped me with this volume. Space permits me to extend thanks to only a few—Barbara Whitepine, Catharine Wilder Guiles, Gilbert Kerlin, Glen Swanson, Camille Dee, David R. Woods, Noa Wheeler; Robert Freedman and Selma Luttinger of the Robert A. Freedman Dramatic Agency; and Barbara Hogenson and Nicole Verity of the Barbara Hogenson Agency. Thomas Clements III kindly provided details about Wilder's stabs at longitude and latitude. Dr. Patricia Willis and the able staff of the Beinecke Library always deserve special applause, as does Penelope Niven, whose assistance has been invaluable. From start to finish, it has been inspiring to work with Donald Margulies.
If there are errors in the Overview, I take responsibility for them and welcome corrections.
Addendum Acknowledgements to the 75th Anniversary Edition
I am grateful to Barbara Hogenson, Rosey Strub, Penelope Niven, and Lori Styler for their help with this new edition. I am glad here to add these additional names: Scott Morfee, J. D. McClatchy, and Thornton Wilder's many able and enthusiastic fans at HarperCollins.
Unpublished Material
Unless otherwise identified in the Overview and Readings, or noted here, all unpublished materials are taken from one of two sources: the holdings in the Thornton Wilder Papers in the Yale Collection of American Literature at the Beinecke Rare Book and Manuscript Library, or the Wilder family's own holdings, including many of Thornton Wilder's legal and agency papers. Silent corrections in spelling and punctuation have been made when deemed appropriate. Wilder's correspondence with Alexander Woollcott is held at Harvard in the Houghton Library's Harvard Theatre Collection, and his letters to Lady Sibyl Colefax are housed in Special Collections, Fales Library, New York University. The original production of Our Town's "prompt script" is held in the Harvard Theatre Collection, Houghton Library, Harvard University (TS 3494.750), and the Collection's assistance in supplying a reproducible page from it (Reading 3) is acknowledged. Wilder's letter to Sol Lesser (Overview), producer of the Our Town film, dated "Easter night [1940]" is held in the Department of Special Collections, University Research Library, University of California, Los Angeles. Fred E. Walker played the part of Dr. Gibbs in Trenton Central High School's 1948 production of Our Town. The letter, held by him and quoted from in Reading 9, was sent to the cast through Dean Frederic Adams of Trinity Cathedral, Trenton. The courtesies extended by these institutions and by Mr. Walker are gratefully acknowledged.
Quotations and Publications
Unless credited in the text, in the Afterword, Jeremy McCarter's words are taken from "The Genius of Grover's Corners," his review of Thornton Wilder: Collected Plays & Writings on Theater, published in the New York Times Book Review, April 1, 2007, p. 27. A. R. Gurney's words are found in his Introduction to The Collected Short Plays of Thornton Wilder, Volume II (New York: Theatre Communication Group Press, 1999, p. xvi); Edward Albee's remarks are from an interview given in April 1999 for a projected Thornton Wilder documentary. J. D. McClatchy uses the quoted phrase in talks about editing Wilder's works and serving as librettist for the Our Town opera.
Reading 2, from The Woman of Andros, is taken from the HarperCollins Perennial edition (New York, 2006), pp. 148–49. Wilder's discussion on the themes in the novel is found on p. 24 of the spring issue of Marshall Field & Company's Fashions of the Hour, an influential publication in the period. Pullman Car Hiawatha, and the other one-act plays mentioned, are available to general readers in The Collected Short Plays of Thornton Wilder, Volume I (New York: Theatre Communications Group Press, 1997) and in individual and collected acting additions (New York: Samuel French, Inc., 2013). Sutherland Denlinger conducted the New York World-Telegram interview of December 7, 1937 (Reading 6). It was reprinted by Jackson R. Bryer, Ed., in Conversations with Thornton Wilder (Jackson: University Press of Mississippi, 1992), pp. 15–17. Wilder's "A Preface for Our Town," (Reading 6) is reprinted in American Characteristics and Other Essays (New York: Harper & Row, 1979; Authors Guild Backprint edition, 2000), pp. 100–3. Thomas Coley's "Our Town" Remembered, a pamphlet dedicated to Isabel Wilder (Overview), was published privately in 1982.
All rights for all published and unpublished work by Thornton Wilder are reserved by the Wilder Family LLC.
Photographs
Unless otherwise credited herein, the photographs in this edition are held in the Thornton Wilder Papers in the Yale Collection of American Literature at the Beinecke Rare Book and Manuscript Library, or by the Wilder family, and are used with permission of the Wilder Family LLC.
I am grateful to Sally Higginson Begley for providing the 1939 Berkshire Theatre Festival production photograph shown in Reading 8 (STF Archive), to the staff of the Peter-borough Players for the 1940 photograph (Reading 9), and to the MacDowell Colony for the picture of Veltin Studio (Reading 4). Catharine Kerlin Wilder (1906–2005), the bride shown in the first photograph (Reading 1), graciously consented to its use. The two Vandamm photographs of the original Broadway production are reproduced with the permission of the Billy Rose Theatre Collection, New York Public Library for the Performing Arts, Astor, Lenox, and Tilden Foundations.
We thank the management of the Hotel Belvoir in Rüschlikon, Switzerland (Reading 4) for providing a photograph of the hotel as Wilder would have known it in 1937.
The two photographs from the College of Wooster's 1950 production of Our Town—the author's photograph on page 197, showing Thornton Wilder playing the Stage Manager in Act I, and the photograph on page 178 of Wilder playing the role of the minister in Act II—appear with the permission of Special Collections, the College of Wooster Libraries, Wooster, Ohio.
Source Material and Subsidiary Works
(available since 2000)
Sources
Major new resources for the general audience and for teachers and theater professionals who are interested in learning more about Thornton Wilder's life and work have become available since the first edition of this book. For ongoing information visit the Wilder family's website, www.thorntonwilder.com, and the Thornton Wilder Society's website, www.twildersociety.org. Recent titles using extensive archival holdings never before available to researchers include: Thornton Wilder: A Life by Penelope Niven (HarperCollins, 2012); The Selected Letters of Thornton Wilder, edited by Robin G. Wilder and Jackson R. Bryer (HarperCollins, 2008); The Library of America's three-volume edition of Wilder's fiction and drama, edited by J. D. McClatchy (Collected Plays & Writings on Theater [2007], The Bridge of San Luis Rey and Other Novels 1926–1948 [2009], The Eighth Day, Theophilus North & Autobiographical Writings [2011]); HarperCollins/ Harper Perennial individual editions of Wilder's novels and major dramas with Forewords and Afterwords by contemporary authors. For examples of recent scholarship on Wilder see Thornton Wilder: New Perspectives, edited by Jackson R. Bryer and Lincoln Konkle (Northwestern University Press, 2013); Thornton Wilder & Amos Wilder: Writing Religion in Twentieth-Century America, by Christopher J. Wheatley (University of Notre Dame Press, 2011).
It must be underscored that the Our Town material in The Selected Letters and Penelope Niven's treatment of the play's sources in her groundbreaking biography represent essential new information, and thus required reading for a fuller understanding of the work.
Subsidiary Works
The Our Town opera, composed by Ned Rorem with libretto by J. D. McClatchy and managed by Boosey and Hawkes, had its world premiere at Indiana University on February 25, 2006; The Return, a modern dance interpretation from GroundWorks DanceTheater inspired by Our Town and developed by David Shimotakahara, premiered on February 4, 2011 in Cleveland, Ohio; OT: Our Town, a documentary by Scott Kennedy on the making of Our Town in inner-city Dominguez High School in Compton, California, was released by Black Valley Films in 2002.
About the Author
In his quiet way, THORNTON NIVEN WILDER was a revolutionary writer who experimented boldly with literary forms and themes, from the beginning to the end of his long career. "Every novel is different from the others," he wrote when he was seventy-five. "The theater (ditto). . . . The thing I'm writing now is again totally unlike anything that preceded it." Wilder's richly diverse settings, characters, and themes are at once specific and global. Deeply immersed in classical as well as contemporary literature, he often fused the traditional and the modern in his novels and plays, all the while exploring the cosmic in the commonplace. In a January 12, 1953, cover story, Time took note of Wilder's unique "planetary mind"—his ability to write from a vision that was at once American and universal.
A pivotal figure in the history of twentieth-century letters, Wilder was a novelist and playwright whose works continue to be widely read and produced in this new century. He is the only writer to have won the Pulitzer Prize for both fiction and drama. His second novel, The Bridge of San Luis Rey, received the fiction award in 1928, and he won the prize twice in drama, for Our Town in 1938 and The Skin of Our Teeth in 1943. His other novels are The Cabala, The Woman of Andros, Heaven's My Destination, The Ides of March, The Eighth Day, and Theophilus North. His other major dramas include The Matchmaker, which was adapted as the internationally acclaimed musical comedy Hello, Dolly!, and The Alcestiad. Among his innovative, frequently performed shorter plays are The Happy Journey to Trenton and Camden and The Long Christmas Dinner (1931). In the 1950s, he conceived a unique dramatic series, The Seven Ages of Man and The Seven Deadly Sins, completing four of the plays he envisioned in each group. Three of the plays were first performed in 1962 as Plays for Bleecker Street.
Wilder and his work received many honors, highlighted by the three Pulitzer Prizes, the Gold Medal for Fiction from the American Academy of Arts and Letters, the Order of Merit (Peru), the Goethe-Plakette der Stadt (Germany, 1959), the Presidential Medal of Freedom (1963), the National Book Committee's first National Medal for Literature (1965), and the National Book Award for Fiction (1967).
He was born in Madison, Wisconsin, on April 17, 1897, to Amos Parker Wilder and Isabella Niven Wilder. The family later lived in China and in California, where Wilder was graduated from Berkeley High School. After two years at Oberlin College, he went on to Yale, where he received his undergraduate degree in 1920. A valuable part of his education took place during summers spent working hard on farms in California, Kentucky, Vermont, Connecticut, and Massachusetts. His father arranged these rigorous "shirtsleeve" jobs for Wilder and his older brother, Amos, as part of their initiation into the American experience.
Thornton Wilder studied archaeology and Italian as a special student at the Amerian Academy in Rome (1920–21) and earned a master of arts degree in French literature at Princeton in 1926.
In addition to his talents as playwright and novelist, Wilder was an accomplished teacher, essayist, translator, scholar, lecturer, librettist, and screenwriter. In 1942, he teamed with Alfred Hitchcock to write the first draft of the screenplay for the classic thriller Shadow of a Doubt, receiving credit as principal writer and a special screen credit for his "contribution to the preparation" of the production. All but fluent in four languages, Wilder translated and adapted plays by such varied authors as Henrik Ibsen, Jean-Paul Sartre, and André Obey. As a scholar, he conducted significant research on James Joyce's Finnegans Wake and the plays of Spanish dramatist Lope de Vega.
Wilder's friends included a broad spectrum of figures on both sides of the Atlantic—Hemingway, Fitzgerald, Alexander Woollcott, Gene Tunney, Sigmund Freud, producer Max Reinhardt, Katharine Cornell, Ruth Gordon, and Garson Kanin. Beginning in the mid-1930s, Wilder was especially close to Gertrude Stein and became one of her most effective interpreters and champions. Many of Wilder's friendships are documented in his prolific correspondence. Wilder believed that great letters constitute a "great branch of literature." In a lecture entitled "On Reading the Great Letter Writers," he wrote that a letter can function as a "literary exercise," the "profile of a personality," and "news of the soul," apt descriptions of thousands of letters he wrote to his own friends and family.
Wilder enjoyed acting and played major roles in several of his own plays in summer theater productions. He also possessed a lifelong love of music; reading musical scores was a hobby, and he wrote librettos for two operas based on his work: The Long Christmas Dinner, with composer Paul Hindemith, and The Alcestiad, with compuser Louise Talma. Both works premiered in Germany.
Teaching was one of Wilder's deepest passions. He began his teaching career in 1921 as an instructor in French at Lawrenceville, a private secondary school in New Jersey. Financial independence after the publication of The Bridge of San Luis Rey permitted him to leave the classroom in 1928, but he returned to teaching in the 1930s at the University of Chicago. For six years, on a part-time basis, he taught courses in comparative literature, classics in translation, and composition. In 1950–51, he served as the Charles Eliot Norton Professor of Poetry at Harvard. Wilder's gifts for scholarship and teaching (he treated the classroom as all but a theater) made him a consummate, much sought-after lecturer in his own country and abroad. After World War II, he held special standing, especially in Germany, as an interpreter of his own country's intellectual traditions and their influence on cultural expression.
During World War I, Wilder had served a three-month stint as an enlisted man in the Coast Artillery section of the army, stationed at Fort Adams, Rhode Island. He volunteered for service in World War II, advancing to the rank of lieutenant colonel in Army Air Force Intelligence. For his service in North Africa and Italy, he was awarded the Legion of Merit, the Bronze Star, the Chevalier Legion d'Honneur, and honorary officership in the Military Order of the British Empire (M.B.E.).
From royalties received from The Bridge of San Luis Rey, Wilder built a house for his family in 1930 in Hamden, Connecticut, just outside New Haven. But he typically spent as many as two hundred days a year away from Hamden, traveling to and settling in a variety of places that provided the stimulation and solitude he needed for his work. Sometimes his destination was the Arizona desert, the MacDowell Colony in New Hampshire, Martha's Vineyard, Saratoga Springs, Vienna, or Baden-Baden. He wrote aboard ships, and he often chose to stay in "spas in off-season." He needed a certain refuge when he was deeply immersed in writing a novel or play. Wilder explained his habit to a New Yorker journalist in 1959: "The walks, the quiet—all the elegance is present, everything is there but the people. That's it! A spa in off-season! I'll make a practice of it."
But Wilder always returned to "the house The Bridge built," as it is still known to this day. He died there of a heart attack on December 7, 1975.
Visit www.AuthorTracker.com for exclusive information on your favorite HarperCollins authors.
Books by Thornton Wilder
Novels
The Cabala and the Woman of Andros
The Bridge of San Luis Rey
Heaven's My Destination
The Ides of March
The Eighth Day
Theophilus North
Collections of Short Plays
The Angel That Troubled the Waters
The Long Christmas Dinner & Other Plays in One Act
Plays
The Merchant of Yonkers
The Skin of Our Teeth
The Matchmaker
The Alcestiad
The Beaux' Stratagem (with Ken Ludwig)
Essays
American Characteristics & Other Essays
The Journals of Thornton Wilder, 1939–1961
Back Ad
Copyright
Caution: Professionals and amateurs are hereby warned that Our Town, being fully protected under the copyright laws of the United States of America, the United Kingdom, Canada, and all other countries of the Copyright Union, is subject to a royalty. All rights, including, but not limited to, professional, amateur, motion picture, recitation, lecturing, public reading, radio broadcasting, television, video or sound taping, all other forms of mechanical or electronic reproduction, such as information storage and retrieval systems and photocopying, and the rights of translation into foreign languages are strictly reserved. All inquiries concerning all rights (other than amateur) should be addressed to the author's agent, Alan Brodie Representation, Paddock Suite, The Courtyard, 55 Charterhouse Street, London EC1M 6HA, U.K., without whose permission in writing no performance of the play must be made. All inquiries concerning the amateur acting rights should be addressed to Samuel French, Inc., 45 West 25th Street, New York, NY 10010. No amateur performance of the play may be given without obtaining in advance the written permission of Samuel French, Inc., and paying the requisite royalty fee.
A hardcover edition of this book was published by Coward-McCann, Inc., in 1939. It is reprinted here by arrangement with the Wilder Family LLC.
OUR TOWN. Copyright © 1938, 1965 by the Wilder Family LLC. Foreword copyright © 2003, 2013 by Donald Margulies. Afterword copyright © 2003, 2013 by Tappan Wilder. All rights reserved under International and Pan-American Copyright Conventions. By payment of the required fees, you have been granted the nonexclusive, nontransferable right to access and read the text of this e-book on-screen. No part of this text may be reproduced, transmitted, downloaded, decompiled, reverse-engineered, or stored in or introduced into any information storage and retrieval system, in any form or by any means, whether electronic or mechanical, now known or hereinafter invented, without the express written permission of HarperCollins e-books.
First Perennial Library edition published 1985.
First Perennial Classics edition published 1998; reissued 2003.
First Harper Perennial Modern Classics edition published 2013.
* * *
The Library of Congress has catalogued a previous edition of this book as follows: Wilder, Thornton.
Our town : a play in three acts / Thornton Wilder.—Current Perennial Classics ed.
p. cm.—(Perennial classics)
ISBN 0-06-051263-6
1. New Hampshire—Drama. 2. City and town life—Drama.
3. Young women—Drama. I. Title. II. Perennial classic.
PS3545.I34509 2003
812'.52—dc22 2003055676
* * *
ISBN 978-0-06-228081-7 (pbk.)
EPUB Edition FEBRUARY 2014 ISBN 9780062232632
Version 03072014
13 14 15 16 17 DIX/RRD 10 9 8 7 6 5 4 3 2 1
About the Publisher
Australia
HarperCollins Publishers (Australia) Pty. Ltd.
Level 13, 201 Elizabeth Street
Sydney, NSW 2000, Australia
http://www.harpercollins.com.au
Canada
HarperCollins Canada
2 Bloor Street East - 20th Floor
Toronto, ON, M4W, 1A8, Canada
<http://www.harpercollins.ca>
New Zealand
HarperCollins Publishers New Zealand
Unit D, 63 Apollo Drive
Rosedale 0632
Auckland, New Zealand
<http://www.harpercollins.co.nz>
United Kingdom
HarperCollins Publishers Ltd.
77-85 Fulham Palace Road
London, W6 8JB, UK
<http://www.harpercollins.co.uk>
United States
HarperCollins Publishers Inc.
10 East 53rd Street
New York, NY 10022
<http://www.harpercollins.com>
* The Barrow Street production opened on February 17, 2009. It closed on September 12, 2010, after 654 performances, easily eclipsing the original Broadway record of 336 performances and becoming the longest running Our Town in history. Five actors spelled Cromer, who played the Stage Manager during the run. One of them, the Oscar winner Helen Hunt, later reprised her role for a four-week limited engagement of the production at The Broad Stage in Santa Monica, California, in the winter of 2012. David Cromer directed and again played the Stage Manager role at the Huntington Theatre in Boston at the end of 2012.
|
This invention relates to a ski or ski board adapted for use singly by a rider who places his feet on the board and guides the path of the board by tilting the board from side to side in response to a shift of his weight from one side to another. More particularly, this invention relates to an improved foot receiving means for the board comprising at least a pair of skid resistant, generally L-shaped members, preferably arranged for receiving the feet of the user in a position spaced from one another normal to the transverse axis of the ski. Still more particularly, this invention relates to a ski of the type described having a metallic base plate particularly adapting the ski for use on sand. Still more particularly, this invention relates to a ski of the type described having an improved handle member.
U.S. Pat. Nos. 3,378,274 and 3,378,275, both assigned to the assignee of this invention, describe a ski or ski board adapted for use singly, rather than in pairs, by a rider who places his feet on the board one in front of the other and guides the path of the board by tilting the board from side to side in response to a shift in his weight from one side to the other, in a manner similar to that in which surfboards or skateboards are ridden. Preferably, in order to provide the rider with a high degree of stability, the board is provided with a rope or tether having one end attached to the front of the board and a length sufficient for the skier to hold the other end.
Surf-type skis of the type described are defined by a ski member having a longitudinal axis, a relatively narrow width, a generally planar intermediate portion, and a front portion extending mildly upwardly and inwardly from the intermediate portion to a front end. The front portion and the intermediate portion have a substantially rectangular cross section in the direction perpendicular to the longitudinal axis. The rear portion of the ski extends rearwardly from the intermediate portion to a rear end and, as disclosed in the '275 patent, has a cross section transverse to the longitudinal axis of a generally V-shape extending rearwardly from the intermediate portion to the rear end with gradually increasing depth.
It is an overall object of this invention to provide an improved ski of the type described in the aforementioned patents. The '275 patent discloses footrest means comprising a frictional resistant device to prevent skidding of the rider's boot or shoe on the ski. Preferably, such non-skid means take the form of a plurality of rows of inverted U-shaped staples driven into and embedded in the ski with a cross piece of the U in the upper surface of the ski. In addition to resisting slippage, the staples described are self cleaning and if the skier removes his weight from the shoe and slides the shoe longitudinally of the ski, both the shoe and the ski are cleaned from accumulated snow. The '274 patent, on the other hand, discloses antiskid foot treads bonded to the upper surface of the ski in a position so that the skier's boots are situated on the treads and the feet of the skier are manipulated to control the ski. In each embodiment, the feet of the skier have no bindings and therefore control forces must be downward or else transmitted to the ski through lateral friction at the upper surface thereof.
Because control of a ski of the type described is substantially achieved by shifting the weight of the user, binders or locking type footrests are not readily usable on this type of ski for the reason that it is generally desirable to be able to remove or shift the weight of the skier from one foot to the other, which control is not readily achieved by the use of locking type binders or shoe type bindings attached to the ski. On the other hand, foot receiving means on the ski of the type described, particularly when used on ice and snow, have sometimes been susceptible to permitting the foot of the skier to slide fore or aft along the longitudinal axis causing the loss of control of the ski. Thus, it is a problem in providing a ski of the type described to include an adequate friction engaging foot receiving means free from permanent bindings for the foot of the user to permit control of the ski while inhibiting and preventing lateral slippage of the foot of the user along the longitudinal axis of the ski.
In addition, skis of the type described have principally and virtually exclusively been used on snow or ice. Because such skis are generally made of laminated wood, such skis have not had sufficiently long life to use on sand, such as in the dunes of sands adjacent to bodies of water. Thus, a second overall object of the invention is to provide a ski of the type described having a metallic base member secured to the bottom of the ski.
In still another area, such skis have been provided with a control rope. Because of variations in the height of the user, it is desirable to be able to adjust the positioning of a control member secured to the tether or control line which in turn is secured to the front of the ski. Thus, it is still another overall object of this invention to provide an improved handle member which is readily adjustable along the control line to accommodate various heights or preferences of the users.
These and other objects of the invention will become apparent from a review of the accompanying written description of the invention taken in conjunction with the accompanying drawings. |
<reponame>adroit48Dev/demo-ang
import { DefaultHolidayComponent } from './defaultholiday/defaultholiday.component';
import { HolidayManagementComponent } from './holiday-management.component';
import { SpecialHolidayComponent } from './specialholiday/specialholiday.component';
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { CreateDefaultHolidayComponent } from './defaultholiday/create-default-holiday/create-default-holiday.component';
import { CreateSpecialHolidayComponent } from './specialholiday/create-special-holiday/create-special-holiday.component';
import { UpdateSpecialHolidayComponent } from './specialholiday/update-special-holiday/update-special-holiday.component';
import { UpdateDefaultHolidayComponent } from './defaultholiday/update-default-holiday/update-default-holiday.component';
const routes: Routes = [
{
path: '',
component: HolidayManagementComponent,
children: [
{
path: 'defaultholiday',
component: DefaultHolidayComponent
},
{
path: 'defaultholiday/create-default-holiday',
component: CreateDefaultHolidayComponent
},
{
path: 'defaultholiday/update-default-holiday/:id',
component: UpdateDefaultHolidayComponent
},
{
path: 'specialholiday',
component: SpecialHolidayComponent
},
{
path: 'specialholiday/create-special-holiday',
component: CreateSpecialHolidayComponent
},
{
path: 'specialholiday/update-special-holiday/:id',
component: UpdateSpecialHolidayComponent
},
]
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class HolidayManagementRoutingModule { }
|
import csv
def to18(idstr):
if len(idstr) == 15:
# To construct the 18 character Salesforce id, we're going to build a 15-bit checksum
# expressed as three alphanumeric characters.
# We do this by constructing 3 five-bit indices into the alnum character range
# Each five-bit index corresponds to the case (1 = uppercase) of five characters
# of the 15-digit Salesforce Id, in reverse order (LSB is the first character)
# Build up a bitstring
bitstring = 0
for i in range(0, 15):
if idstr[i] >= 'A' and idstr[i] <= 'Z':
bitstring |= 1 << i
# Take three slices of the bitstring and use them as 5-bit indices into the alnum sequence.
alnums = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ012345'
return idstr + alnums[bitstring & 0x1F] + alnums[bitstring>>5 & 0x1F] + alnums[bitstring>>10]
elif len(idstr) == 18:
return idstr
elif len(idstr) == 0:
return idstr
else:
raise ValueError('Salesforce Ids must be 15 or 18 characters.')
def process_file(input_file, output_file, columns=[], skip_headers=False, progress=None):
if len(columns) == 0 or type(columns[0]) is int:
# Numbered columns mode.
mode = 'index'
reader = csv.reader(input_file)
writer = csv.writer(output_file)
else:
mode = 'dict'
reader = csv.DictReader(input_file)
writer = csv.DictWriter(output_file, fieldnames=reader.fieldnames)
writer.writeheader()
bytes_read = 0
skipped = False
for row in reader:
if not skipped and skip_headers and mode == 'index':
# We're in column-index (non-dictionary) mode
# Skip the presumable header row.
skipped = True
writer.writerow(row)
bytes_read += sum([len(x) for x in row])
if progress is not None:
progress(bytes_read)
continue
# Convert the specified columns
for col in columns:
row[col] = to18(row[col])
writer.writerow(row)
bytes_read += sum([len(x) for x in row])
if progress is not None:
progress(bytes_read)
|
/**
* Initializes the configuration from the specified file. If the file does not exist, it will be created.
*
* @param file The file to load the configuration from.
*
* @throws IOException Thrown in case that any I/O error occurs.
*/
public void initialize( File file ) throws IOException {
if ( !file.exists() ) {
try ( Writer writer = new FileWriter( file ) ) {
this.write( writer );
}
} else {
try ( Reader reader = new FileReader( file ) ) {
this.read( reader );
}
}
} |
Detergent-aided polymersome preparation. Until now, most preparative methods used to form polymeric vesicles involve either organic cosolvents or sonication. In this communication, we demonstrate for the first time a detergent-aided method to produce polymersomes. Peptidic polymersomes were formed from the rod-rod block copolymer PBLG-E, where PBLG is hydrophobic poly(gamma-benzyl l-glutamate) and E is a hydrophilic designed peptide. The block copolymer was first solubilized by detergent micelles in aqueous buffer, after which the concentration of detergent was reduced by dilution, transforming the particle morphology in solution from mixed micelles to polymersomes. The polymersome formation was monitored with dynamic light scattering and confirmed with transmission electron microscopy. Polymersomes with average diameters of approximately 300 nm were obtained as well as discs with average diameters of approximately 100 nm. This detergent-based method can be used to create polymersomes with a range of properties, as verified by its application to another biocompatible block copolymer, the flexible polybutadiene-b-poly(ethylene glycol). The technique will be particularly useful when delicate biomacromolecules such as (membrane) proteins, peptides, or nucleic acids are to be encapsulated in the polymersomes because the detergents used are compatible with these compounds, and the possible denaturing effect of sonication or organic solvents on the biological activity of the molecule of interest is avoided. |
package io.github.damt.thread;
import io.github.damt.Viper;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
public class ViperThread extends Thread {
private final Viper instance;
public ViperThread(Viper instance) {
this.instance = instance;
this.setDaemon(false);
this.start();
}
@Override
public void run() {
try {
for (Player player : Bukkit.getServer().getOnlinePlayers()) {
this.instance.createScoreboard(player);
}
Thread.sleep(this.instance.getTime() * 50);
} catch (InterruptedException exception) {
exception.printStackTrace();
}
}
}
|
Crystal growth, structural, electrical, and magnetic properties of mixed-valent compounds YbOs2Al10 and LuOs2Al10. Single crystals of YbOs2Al10 and LuOs2Al10 were grown for the first time using an aluminum self-flux method. The compounds crystallized into a cagelike structure in space group Cmcm, similar to the prototype compound YbFe2Al10. YbOs2Al10 exhibited a mixed-valent nature, as determined by magnetic susceptibility measurements over a wide temperature range from 2 to 900 K, in which the inter-configuration-fluctuation model revealed a broad peak around 400 K. In contrast, LuOs2Al10 displayed Pauli-like paramagnetic behavior over the same temperature range. Both compounds were metallic in nature between 2 and 300 K. The electronic specific heat coefficient of 21.3 mJ mol(-1) K(-2) for YbOs2Al10 was determined to be larger than that for LuOs2Al10 , reflecting the mixed-valent nature of the former. First-principles calculations predicted the presence of a mixed-valent state in YbOs2Al10, in agreement with the experimental observations. The novel compound YbOs2Al10 elucidates the evolution of the mixed-valent nature of the Yb-based ternary transition metal aluminides from the 3d to 5d elements. |
import React from 'react';
import Line from "../../../math/Line/Line";
interface Props {
x: number;
y: number;
units: number
label?: string;
color?: string;
origin: { x: number, y: number }
}
export default class VectorComponent extends React.PureComponent<Props> {
static id = 0;
private _id = 0;
get color() {
return this.props.color || "#000";
}
constructor(props: Props) {
super(props);
this._id = VectorComponent.id;
VectorComponent.id += 1;
}
getLabelCoordinates = () => {
const line = new Line(0, 0, this.props.x, this.props.y);
const fixMargin = 0.3;
const fixX = this.props.x > 0 ? this.props.x + fixMargin : this.props.x - fixMargin * 2;
const lineY = line.getY(this.props.x) || this.props.y;
const fixY = lineY > 0 ? lineY + fixMargin : lineY - fixMargin * 2;
return {
x: this.toPointX(fixX),
y: this.toPointY(fixY),
};
};
toPointX = (k: number) => this.props.origin.x + k * this.props.units;
toPointY = (k: number) => this.props.origin.y - k * this.props.units;
render() {
return (
<>
<defs>
<marker
id={`arrowhead-${this._id}`}
markerWidth="6"
markerHeight="4"
refX="5.5"
refY="2"
orient="auto"
>
<polygon fill={this.color} points="0 0, 6 2, 0 4"/>
</marker>
</defs>
<line
x1={this.toPointX(0)}
y1={this.toPointY(0)}
x2={this.toPointX(this.props.x)}
y2={this.toPointY(this.props.y)}
stroke={this.color}
strokeWidth="1.5"
markerEnd={`url(#arrowhead-${this._id})`}
/>
<text {...this.getLabelCoordinates()} stroke={this.color}>{this.props.label}</text>
</>
);
}
} |
<gh_stars>1-10
/*
Copyright (C) 2000,2002,2004 Silicon Graphics, Inc. All Rights Reserved.
Portions Copyright 2011 <NAME>. All Rights Reserved.
This program is free software; you can redistribute it and/or modify it
under the terms of version 2.1 of the GNU Lesser General Public License
as published by the Free Software Foundation.
This program is distributed in the hope that it would be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Further, this software is distributed without any warranty that it is
free of the rightful claim of any third person regarding infringement
or the like. Any license provided herein, whether implied or
otherwise, applies only to this software file. Patent licenses, if
any, provided herein do not apply to combinations of this program with
other software, or any other product whatsoever.
You should have received a copy of the GNU Lesser General Public
License along with this program; if not, write the Free Software
Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston MA 02110-1301,
USA.
Contact information: Silicon Graphics, Inc., 1500 Crittenden Lane,
Mountain View, CA 94043, or:
http://www.sgi.com
For further information regarding this notice, see:
http://oss.sgi.com/projects/GenInfo/NoticeExplan
*/
#include "config.h"
#include "libdwarfdefs.h"
#ifdef HAVE_ELF_H
#include <elf.h>
#endif
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <stdlib.h>
#include "pro_incl.h"
extern char *_dwarf_errmsgs[];
/*
This function performs error handling as described in the
libdwarf consumer document section 3. Dbg is the Dwarf_P_debug
structure being processed. Error is a pointer to the pointer
to the error descriptor that will be returned. Errval is an
error code listed in dwarf_error.h.
The error number may be retrieved from the Dwarf_Error
by calling dwarf_errno().
The error string implied by the error number may be retrieved
from the Dwarf_Error by calling dwarf_errmsg().
*/
void
_dwarf_p_error(Dwarf_P_Debug dbg,
Dwarf_Error * error, Dwarf_Word errval)
{
Dwarf_Error errptr;
if (errval > DW_DLE_LAST) {
/* We do not expect to ever see such an error number,
DW_DLE_LO_USER is not used. */
/* The 'standard' typedef for Dwarf_Word is "unsigned long". */
fprintf(stderr,"ERROR VALUE: %lu - %s\n",
(unsigned long) errval, "this error value is unknown to libdwarf.");
}
/* Allow NULL dbg on entry, since sometimes that can happen and we
want to report the upper-level error, not this one. */
if (error != NULL) {
errptr = (Dwarf_Error)
_dwarf_p_get_alloc(dbg, sizeof(struct Dwarf_Error_s));
if (errptr == NULL) {
fprintf(stderr,
"Could not allocate Dwarf_Error structure\n");
abort();
}
errptr->er_errval = (Dwarf_Sword) errval;
*error = errptr;
return;
}
if (dbg != NULL && dbg->de_errhand != NULL) {
errptr = (Dwarf_Error)
_dwarf_p_get_alloc(dbg, sizeof(struct Dwarf_Error_s));
if (errptr == NULL) {
fprintf(stderr,
"Could not allocate Dwarf_Error structure\n");
abort();
}
errptr->er_errval = (Dwarf_Sword) errval;
dbg->de_errhand(errptr, dbg->de_errarg);
return;
}
abort();
}
|
def choose_turn():
left_dist, left_angle = find_golden_token_dist(-90)
right_dist, right_angle = find_golden_token_dist(90)
if left_dist < right_dist:
return right_dist,right_angle
else:
return left_dist, left_angle |
It’s matchday!
Albeit a bizarre 8pm Friday night kick off, but nothing beats some football under the lights. Right?
Nothing is certain from this Vancouver Whitecaps team this season. We could be in for an entertaining end to end cracker, or a drab dull and dreary game of patience and counter attacks.
What will it be this week? Well fear not, no matter what we end up with, we have something here at AFTN that’s guaranteed to add excitement to your ‘Caps viewing experience, no matter whether you’re sitting there live at the match or watching the game at home or in the bar.
It’s AFTN’s Vancouver Whitecaps Bingo Card….
36 squares of “that’s so Vancouver” malarkey. How many will you be able to cross off tonight? Will you be able to complete your card in just one match or will you need to carry it on to Sporting KC next week and maybe even beyond that? Will you turn it into a drinking game and be hammered by half time?
You can use the card we’ve provided here, or for even more fun and frolics, head along to HERE and you can print off any number of random generated Bingo Cards to play along with all your friends and family. Did someone say Bingo Beach Party? Probably not, but don’t be shy, give it a try.
Fun for kids and the young at heart of all ages, and guaranteed to be a load of balls. |
Effect of sotalol withdrawal on serum lipids and lipoprotein lipase activity. Serum total cholesterol, HDL cholesterol, triglycerides, and adipose tissue lipoprotein lipase activity were analyzed in seven hypertensive subjects using 160-480 mg sotalol daily, before and after a 3-week pause in the treatment. Triglycerides decreased and HDL cholesterol increased significantly during the break in sotalol treatment, whereas no changes occurred in total cholesterol and lipoprotein lipase. A positive correlation was found after the interruption between the lipoprotein lipase activity and the HDL cholesterol concentration. This correlation did not exist before the break in the drug treatment. On the basis of these results the effects of sotalol on lipoprotein metabolism do not seem to be mediated by lipoprotein lipase. |
package trigger;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import javax.print.attribute.standard.RequestingUserName;
import csvutils.DataSet;
import csvutils.FeatureVector;
import csvutils.Stat;
import stocks.Candlestick;
import stocks.Numerics;
import stocks.Trade;
//A trigger being an event that happens with the stocks. An example of a trigger would be a pump
public abstract class Trigger {
private DataSet set;
public static final int FIVE_MINUTES = 300;
public static final int QUARTER_HOUR = 900;
public static final int HALF_HOUR = 1800;
public static final int ONE_HOUR = 3600;
public static final int TWO_HOURS = 7200;
public static final int FOUR_HOURS = 14400;
public static final int SIX_HOURS = ONE_HOUR * 6;
public static final int TWELVE_HOURS = ONE_HOUR * 12;
public static final int ONE_DAY = 86400;
public static final int TWO_DAYS = ONE_DAY * 2;
public static final int THREE_DAYS = ONE_DAY * 3;
public static final int FIVE_DAYS = ONE_DAY * 5;
public static final int ONE_WEEK = ONE_DAY * 7;
public static final int FORTNIGHT = ONE_WEEK * 2;
public static final int ONE_MONTH = ONE_DAY * 28;
private int timePeriod;
private String name;
private boolean calcBasic;
public Trigger(String name, int timePeriod) throws Exception {
this(name, timePeriod, true);
}
public Trigger(String name, int timePeriod, boolean calcBasic) throws Exception {
this.name = name;
this.timePeriod = timePeriod;
this.calcBasic = calcBasic;
set = genDataSet();
}
private DataSet genDataSet() throws Exception{
DataSet set = new DataSet();
addFeaturesToDataSet(set);
if (calcBasic) {
addBasicFeatures(set);
}
return set;
}
public String getName() { return name; }
public String getFileName() { return "output-" + name + ".csv"; }
public int getTimePeriod() { return timePeriod; }
public DataSet getDataSet() { return set; }
//adds a list of the features to be calculated to the DataSet
protected abstract void addFeaturesToDataSet(DataSet set) throws Exception;
//If triggered, adds to DataSet
public boolean addIfTriggered(Candlestick[] candles, Candlestick[] btcCandles, int index, String ticker) throws Exception {
boolean triggered = isTriggered(candles, btcCandles, index);
FeatureVector fv;
if (triggered) {
fv = getDataSet().genBlankVector();
try {
calculateAllFeatures(candles, btcCandles, index, ticker, fv);
getDataSet().insertVector(fv);
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
return triggered;
}
public double[] getInput(FeatureVector fv, String output, ArrayList<String> inputFeatures) throws Exception {
DataSet set = genDataSet();
set.insertVector(fv);
set.markOutput(output);
set.markUnusedUnless(output, inputFeatures);
double[][] inputs = set.getInputs();
double[] input = new double[inputs[0].length];
for (int i = 0; i < input.length; i ++) {
input[i] = inputs[0][i];
}
return input;
}
protected void calculateAllFeatures(Candlestick[] candles, Candlestick[] btcCandles, int index, String ticker, FeatureVector fv) throws Exception {
if (calcBasic) {
calculateBasicFeatures(candles, btcCandles, index, fv, ticker);
}
_calculateFeatures(candles, btcCandles, index, fv, ticker, true);
}
//Checks to see if this event has been triggered i.e if this is PumpInterface then it will return true if a pump has occurred.
public abstract boolean isTriggered(Candlestick[] candles, Candlestick[] btcCandles, int index);
public void calculatePastFeatures(Candlestick[] candles, Candlestick[] btcCandles, int index, FeatureVector fv, String ticker) throws Exception {
calculateBasicFeatures(candles, btcCandles, index, fv, ticker);
_calculateFeatures(candles, btcCandles, index, fv, ticker, false);
}
//Calculates the features
protected abstract void _calculateFeatures(Candlestick[] candles, Candlestick[] btcCandles, int index, FeatureVector fv, String ticker, boolean future) throws Exception;
public DataSet load() throws Exception { return load(getFileName()); }
public DataSet loadTemplate() throws Exception { return loadTemplate(getFileName()); }
public DataSet loadTemplate(String name) throws Exception {
DataSet ds = DataSet.loadFromFile(new File(name));
ds.markUnused("ticker");
//ds.markUnused("timestamp");
markOldTradeFeaturesUnused(ds);
return ds;
}
public void markTradeFeaturesUnused(DataSet ds) throws Exception {
ds.markUnused("ratiobsthirty");
ds.markUnused("pbuyvolsamethirty");
ds.markUnused("pmodalbuyvoltodayvol");
ds.markUnused("psellvolsamethirty");
ds.markUnused("pmodalsellvoltodayvol");
}
public void markOldTradeFeaturesUnused(DataSet ds) throws Exception {
ds.markUnused("pbuyvolsamethirtymone");
ds.markUnused("pmodalbuyvoltodayvolmone");
ds.markUnused("psellvolsamethirtymone");
ds.markUnused("pmodalsellvoltodayvolmone");
ds.markUnused("ratiobsthirtymone");
ds.markUnused("ratiobsthirtymtwo");
ds.markUnused("ratiobsthirtymthree");
}
//Loads this trigger as a DataSet. The output is the percentage which the stock is sold for when the event is over
public DataSet load(String name) throws Exception {
DataSet ds = loadTemplate(name);
_load(ds);
return ds;
}
public DataSet loadMax() throws Exception { return loadMax(getFileName()); }
//Loads this trigger as a DataSet. The output is the max percentage the stock increases by before the event is over
public DataSet loadMax(String name) throws Exception {
DataSet ds = loadTemplate(name);
_loadMax(ds);
return ds;
}
//Marks the % at sell feature as output and others as unused
protected abstract void _load(DataSet ds) throws Exception;
//Marks the max feature as output and others as unused
protected abstract void _loadMax(DataSet ds) throws Exception;
protected void addDefinedEndFeatures(DataSet set) throws Exception {
set.addFeature("percentageatsell"); //the percentage on sell signal
set.addFeature("maxpercentage"); //the maximum percentage this stock reaches before the sell signal
set.addFeature("minpercentage"); //the maximum percentage this stock drops before the sell signal
set.addFeature("minperiod"); //number of periods after buy signal that the stock opens with lowest
set.addFeature("maxperiod"); //number of periods after buy signal that the stock opens with the highest
set.addFeature("sellperiod"); //number of periods after buy signal that sell signal occurs
set.addFeature("minperiodopen"); //the percentage change from the buy signal on the lowest opening before sell
set.addFeature("maxperiodopen"); //the percentage change from the buy signal on the highest opening before sell
}
protected void calculateDidPumpImmediate(Candlestick[] candles, Candlestick[] btcCandles, int index, FeatureVector fv, String ticker, boolean future) throws Exception {
calculateDidPumpImmediate(candles, btcCandles, index, fv, ticker, future, "didpump");
}
protected void calculateDidPumpImmediate(Candlestick[] candles, Candlestick[] btcCandles, int index, FeatureVector fv, String ticker, boolean future, String feature) throws Exception {
if (future) {
boolean first = Numerics.pc(candles[index].open, Candlestick.high(Arrays.copyOfRange(candles, index + 1, index + 1 + getRatio(Trigger.TWO_HOURS, getTimePeriod())))) > 5;
boolean second = Numerics.pc(candles[index].open, Candlestick.high(Arrays.copyOfRange(candles, index + 1, index + 1 + getRatio(Trigger.SIX_HOURS, getTimePeriod())))) > 15;
double didPump = first && second ? 1D : -1D;
fv.setFeature(feature, didPump);
} else {
fv.setFeature(feature, -1D);
}
}
public static int getRatio(double trigger, double timePeriod) {
return (int)Math.ceil(trigger / timePeriod);
}
protected void calculateDidPump(Candlestick[] candles, Candlestick[] btcCandles, int index, FeatureVector fv, String ticker, boolean future) throws Exception {
calculateDidPump(candles, btcCandles, index, fv, ticker, future, "didpump");
}
protected void calculateDidPump(Candlestick[] candles, Candlestick[] btcCandles, int index, FeatureVector fv, String ticker, boolean future, String feature) throws Exception {
if (future) {
double didPump = Numerics.pc(candles[index].getOpen(), Candlestick.high(Arrays.copyOfRange(candles, index + 1, index + 1 + getRatio(Trigger.ONE_DAY * 3D, getTimePeriod())))) > 15 ? 1D : -1D;
fv.setFeature(feature, didPump);
} else {
fv.setFeature(feature, -1D);
}
}
protected void fillDefinedEndFeatures(FeatureVector fv) throws Exception {
calculateDefinedEndFeatures(null, null, 0, null, null, false, 0);
}
protected void calculateFutureDefinedEndFeatures(Candlestick[] candles, Candlestick[] btcCandles, FeatureVector fv, int index, int sellsIndex) throws Exception {
calculateDefinedEndFeatures(candles, btcCandles, index, fv, null, true, sellsIndex);
}
protected void calculateDefinedEndFeatures(Candlestick[] candles, Candlestick[] btcCandles, int index, FeatureVector fv, String ticker, boolean future, int sellsIndex) throws Exception {
if (future) {
double highBeforeSell = Candlestick.high(Arrays.copyOfRange(candles, index + 1, sellsIndex + 1));
double lowBeforeSell = Candlestick.low(Arrays.copyOfRange(candles, index + 1, sellsIndex + 1));
double highOpenIndex = Candlestick.highOpenIndex(Arrays.copyOfRange(candles, index + 1, sellsIndex + 1));
double lowOpenIndex = Candlestick.lowOpenIndex(Arrays.copyOfRange(candles, index + 1, sellsIndex + 1));
double highOpen = Candlestick.highOpen(Arrays.copyOfRange(candles, index + 1, sellsIndex + 1));
double lowOpen = Candlestick.lowOpen(Arrays.copyOfRange(candles, index + 1, sellsIndex + 1));
double sellApprox = candles[sellsIndex + 1].getOpen();
double purchaseApprox = candles[index + 1].getOpen();
fv.setFeature("maxpercentage", Numerics.pc(purchaseApprox, highBeforeSell));
fv.setFeature("percentageatsell", Numerics.pc(purchaseApprox, sellApprox));
fv.setFeature("minpercentage", Numerics.pc(purchaseApprox, lowBeforeSell));
fv.setFeature("minperiod", lowOpenIndex + 1);
fv.setFeature("maxperiod", highOpenIndex + 1);
fv.setFeature("sellperiod", sellsIndex - index + 1);
fv.setFeature("minperiodopen", Numerics.pc(purchaseApprox, lowOpen));
fv.setFeature("maxperiodopen", Numerics.pc(purchaseApprox, highOpen));
} else {
fv.setFeature("maxpercentage", 0);
fv.setFeature("percentageatsell", 0);
fv.setFeature("minpercentage", 0);
fv.setFeature("minperiod", 0);
fv.setFeature("maxperiod", 0);
fv.setFeature("sellperiod", 0);
fv.setFeature("minperiodopen", 0);
fv.setFeature("maxperiodopen", 0);
}
}
//Adds a set of basic features used by all triggers
private void addBasicFeatures(DataSet set) throws Exception {
set.addFeature("timestamp"); //the timestamp of a stock
set.addFeature("ticker"); //the stock ticker
set.addFeature("pddailyavg"); //percentage difference from the daily avg
set.addFeature("pdthreedayavg"); //percentage difference from the 3 day avg
set.addFeature("pdweeklyavg"); //percentage difference from the weekly avg
set.addFeature("pdmonthlyavg"); //percentage difference from the monthly avg
set.addFeature("sdvolthirty"); //number of standard deviations away from volume mean for past 3 days in the past 30 minutes
set.addFeature("pvolonethirty"); //percentage of daily volume in past 30 minutes
set.addFeature("relativeinteresttwelve"); //the twelve hour volume divided by the previous twelve hour volume
set.addFeature("relativeinterestday"); //the day volume divided by the previous day volume
set.addFeature("relativeinterestthreeday"); //the three day volume divided by the previous three day volume
set.addFeature("relativeinterestweek"); //the week volume divided by the previous week volume
set.addFeature("relativeinterestfort"); //the fortnight volume divided by the previous fortnight volume
set.addFeature("ratiopricedeltatovol"); //the ratio of the price delta to volume
set.addFeature("ratiopricedeltatovolmone"); //the ratio of the price delta to volume
set.addFeature("ratiopricedeltatovolmtwo"); //the ratio of the price delta to volume
set.addFeature("ratiopricedeltatovolmthree"); //the ratio of the price delta to volume
set.addFeature("ratiobsthirty"); //the ratio of buy trades to sell trades in the past 30 minutes
set.addFeature("pbuyvolsamethirty"); //modal percentage of buy volume for the same price in the past 30 minutes
set.addFeature("pmodalbuyvoltodayvol"); //percentage of the modal buy volume to the volume past 24 hours in the past 30 minutes
set.addFeature("psellvolsamethirty"); //modal percentage of sell volume for the same price in the past 30 minutes
set.addFeature("pmodalsellvoltodayvol"); //percentage of the modal sell volume to the volume past 24 horus in the past 30 minutes
set.addFeature("pcbtcthirty"); //percentage change of bitcoin in the past 30 minutes
set.addFeature("pcbtcthirtymone"); //percentage change of bitcoin in the previous 30 minutes
set.addFeature("pcbtcone"); //percentage change of bitcoin in the previous hour
set.addFeature("pcbtctwo"); //percentage change of bitcoin in the past 2 hours
set.addFeature("pcbtcsix"); //percentage change of bitcoin in the past 6 hours
set.addFeature("pcbtctwelve"); //percentage change of bitcoin in the past 12 hours
set.addFeature("pcbtctwofour"); //percentage change of bitcoin in the past 24 hours
set.addFeature("pcbtcthree"); //percentage change of bitcoin in the past 3 days
set.addFeature("pcbtcweek"); //percentage change of bitcoin in the past week
set.addFeature("pcbtcfort"); //percentage change of bitcoin in the past fortnight
set.addFeature("pcbtcmonth"); //percentage change of bitcoin in the past month
set.addFeature("pcthirty"); //percentage increase in the past 30 minutes (diff open to close)
set.addFeature("pcthirtymone"); //percentage change of -1 30 minutes
set.addFeature("pcthirtymtwo"); //percentage change of -2 30 minutes
set.addFeature("pcthirtymthree"); //percentage change of -3 30 minutes
set.addFeature("pbuyvolsamethirtymone"); //modal percentage of buy volume for the same price in -2 30 minutes
set.addFeature("pmodalbuyvoltodayvolmone"); //percentage of the modal buy volume to the volume past 24 hours in -2 30 minutes
set.addFeature("psellvolsamethirtymone"); //modal percentage of sell volume for the same price in -2 30 minutes
set.addFeature("pmodalsellvoltodayvolmone"); //percentage of the modal sell volume to the volume past 24 hours in -2 30 minutes
set.addFeature("ratiobsthirtymone"); //the ratio of buy trades to sell trades in past -2 30 minutes
set.addFeature("ratiobsthirtymtwo"); //the ratio of buy trades to sell trades in past -3 30 minutes
set.addFeature("ratiobsthirtymthree"); //the ratio of buy trades to sell trades in past -4 30 minutes
set.addFeature("sdvolthirtymone"); //number of standard deviations away from volume mean for past 3 days in -2 30 minutes
set.addFeature("sdvolthirtymtwo"); //number of standard deviations away from volume mean for past 3 days in -3 30 minutes
set.addFeature("sdvolthirtymthree"); //number of standard deviations away from volume mean for past 3 days in -4 30 minutes
set.addFeature("pvolonethirtymone"); //percentage of daily volume in past -2 30 minutes
set.addFeature("pvolonethirtymtwo"); //percentage of daily volume in past -3 30 minutes
set.addFeature("pvolonethirtymthree"); //percentage of daily volume in past -4 30 minutes
set.addFeature("pvolonesixty"); //percentage of the daily volume in the past 60 minutes
set.addFeature("pvoloneonetwenty"); //percentage of the daily volume in the past 2 hours
set.addFeature("pvolonesix"); //percentage of the daily volume in the past 6 hours
set.addFeature("npumpfive"); //number of pumps in the past 5 days
set.addFeature("ndumpfive"); //number of dumps in the past 5 days
set.addFeature("pcone"); //percentage change over hour
set.addFeature("pctwo"); //percentage change over two hours
set.addFeature("pcsix"); //percentage change over six hours
set.addFeature("pctwelve"); //percentage change over 12 hours
set.addFeature("pctwofour"); //percentage change over 1 day
set.addFeature("pctwoday"); //percentage change over 2 days
set.addFeature("pcthreeday"); //percentage change over 3 days
set.addFeature("pcfiveday"); //percentage change over 5 days
set.addFeature("pcweek"); //percentage change over 7 days
set.addFeature("pcfort"); //percentage change over 2 weeks
set.addFeature("pcmonth"); //percentage change over 1 month
set.addFeature("pddh"); //percentage difference of the close price of past 30 to the daily high
set.addFeature("pddm"); //percentage difference of the close price of past 30 to the daily mean
set.addFeature("pddl"); //percentage difference of the close price of past 30 to the daily low
set.addFeature("pdthreedh"); //percentage difference of the close price of past 30 to the 3 day high
set.addFeature("pdthreedl"); //percentage difference of the close price of past 30 to the 3 day low
set.addFeature("pdwh"); //percentage difference of the close price of past 30 to the weekly high
set.addFeature("pdwl"); //percentage difference of the close price of past 30 to the weekly low
set.addFeature("pdfh"); //percentage difference of the close price of past 30 to the fortnightly high
set.addFeature("pdfl"); //percentage difference of the close price of past 30 to the fortnightly low
set.addFeature("pdmh"); //percentage difference of the close price of past 30 to the monthly high
set.addFeature("pdml"); //percentage difference of the close price of past 30 to the monthly low
set.addFeature("labtcpriceday"); //ln of the average price against the bitcoin for the day
set.addFeature("lvoltwofour"); //ln of the volume for the day
set.addFeature("labtcpriceonetofourdaymone"); //ln(average price against bitcoin day/average price against bitcoin 4 days (not including last))
set.addFeature("shadowtobodythirty"); //(ratio of shadow to body) previous 30 minutes(CAN CAUSE DIVIDE BY ZERO SO MAX 5x)
set.addFeature("shadowpositionthirty"); //position of the shadow +1 for all above, -1 for all below. Reverse if stock closed higher than opened (red bar) previous 30 minutes
set.addFeature("shadowtobodythirtymone"); //(ratio of shadow to body) previous 30 minutes(CAN CAUSE DIVIDE BY ZERO SO MAX 5x)
set.addFeature("shadowpositionthirtymone"); //position of the shadow +1 for all above, -1 for all below previous 30 minutes
set.addFeature("shadowtobodythirtymtwo"); //(ratio of shadow to body) previous 30 minutes(CAN CAUSE DIVIDE BY ZERO SO MAX 5x)
set.addFeature("shadowpositionthirtymtwo"); //position of the shadow +1 for all above, -1 for all below previous 30 minutes
set.addFeature("shadowtobodythirtymthree"); //(ratio of shadow to body) previous 30 minutes(CAN CAUSE DIVIDE BY ZERO SO MAX 5x)
set.addFeature("shadowpositionthirtymthree"); //position of the shadow +1 for all above, -1 for all below previous 30 minutes
set.addFeature("stabsix"); //stability (std deviation)/mean over past 6 hours
set.addFeature("stabtwelve"); //stability (std deviation)/mean over past 12 hours
set.addFeature("stabone"); //stability (std deviation)/mean over past day
set.addFeature("stabthree"); //stability (std deviation)/mean over past 3 days
set.addFeature("stabweek"); //stability (std deviation)/mean over past week
set.addFeature("stabfort"); //stability (std deviation)/mean over past 2 weeks
set.addFeature("stabmonth"); //stability (std deviation)/mean over past month
set.addFeature("pdbitcointhirty"); //percentage change difference between this stock and bitcoin previous 30 minutes
set.addFeature("pdbitcoinsixty"); //percentage change difference between this stock and bitcoin previous 60 minutes
set.addFeature("pdbitcoinonetwenty"); //percentage change difference between this stock and bitcoin previous 120 minutes
set.addFeature("pdbitcointwoforty"); //percentage change difference between this stock and bitcoin previous 240 minutes
set.addFeature("pdbitcoinsix"); //percentage change difference between this stock and bitcoin previous 6 hours
set.addFeature("pdbitcointwelve"); //percentage change difference between this stock and bitcoin previous 12 hours
set.addFeature("pdbitcointwentyfour"); //percentage change difference between this stock and bitcoin previous day
set.addFeature("pdbitcointhree"); //percentage change difference between this stock and bitcoin previous 3 days
set.addFeature("pdbitcoinweek"); //percentage change difference between this stock and bitcoin previous week
set.addFeature("pdbitcoinfort"); //percentage change difference between this stock and bitcoin previous fortnight
set.addFeature("pdbitcoinmonth"); //percentage change difference between this stock and bitcoin previous month
set.addFeature("waposthirty"); //Position of the weighted average in the previous 30 mins
set.addFeature("waposthirtymone"); //Position of the weighted average in the -1 30 mins
set.addFeature("waposthirtymtwo"); //Position of the weighted average in the -2 30 mins
set.addFeature("waposthirtymthree"); //Position of the weighted average in the -3 30 mins
set.addFeature("aroonup"); //Aroon up in the previous 30 minutes
set.addFeature("aroondown"); //Aroon down in the previous 30 mins
set.addFeature("aroondelta"); //Difference between aroon up and aroon down
set.addFeature("aroonupmone"); //Aroon up in the -1 30 mins
set.addFeature("aroondownmone"); //Aroon down in the -1 30 mins
set.addFeature("aroondeltamone"); //Difference between aroon up and aroon down -1 30 mins
set.addFeature("aroonupdiffmone"); //Difference between aroon up previous 30 mins and -1 30 mins
set.addFeature("aroondowndiffmone"); //Difference between aroon down previous 30 mins and -1 30 mins
set.addFeature("aroondeltadiffmone"); //Difference between aroon delta previous 30 mins and -1 30 mins
set.addFeature("aroonupmtwo"); //Aroon up in the -2 30 mins
set.addFeature("aroondownmtwo"); //Aroon down in the -2 30 mins
set.addFeature("aroondeltamtwo"); //Difference between aroon up and aroon down -2 30 mins
set.addFeature("aroonupdiffmtwo"); //Difference between aroon up previous 30 mins and -2 30 mins
set.addFeature("aroondowndiffmtwo"); //Difference between aroon down previous 30 mins and -2 30 mins
set.addFeature("aroondeltadiffmtwo"); //Difference between aroon delta previous 30 mins and -2 30 mins
set.addFeature("aroonupmthree"); //Aroon up in the -3 30 mins
set.addFeature("aroondownmthree"); //Aroon down in the -3 30 mins
set.addFeature("aroondeltamthree"); //Difference between aroon up and aroon down -3 30 mins
set.addFeature("aroonupdiffmthree"); //Difference between aroon up previous 30 mins and -3 30 mins
set.addFeature("aroondowndiffmthree"); //Difference between aroon down previous 30 mins and -3 30 mins
set.addFeature("aroondeltadiffmthree"); //Difference between aroon delta previous 30 mins and -3 30 mins
set.addFeature("rsi"); //RSI in previous 30 mins
set.addFeature("stochrsi"); //stoch rsi in previous 30 mins
set.addFeature("rsimone"); //rsi in -1 30 mins
set.addFeature("stochrsimone"); //stoch rsi in -1 30 mins
set.addFeature("rsidiffmone"); //diff rsi previous 30 mins and -1 30 mins
set.addFeature("stochrsidiffmone"); //diff stoch rsi previous 30 mins and -1 30 mins
set.addFeature("rsimtwo"); //rsi in -2 30 mins
set.addFeature("stochrsimtwo"); //stoch rsi in -2 30 mins
set.addFeature("rsidiffmtwo"); //diff rsi previous 30 mins and -2 30 mins
set.addFeature("stochrsidiffmtwo"); //diff stoch rsi previous 30 mins and -2 30 mins
set.addFeature("rsimthree"); //rsi in -3 30 mins
set.addFeature("stochrsimthree"); //stoch rsi in -3 30 mins
set.addFeature("rsidiffmthree"); //diff rsi previous 30 mins and -3 30 mins
set.addFeature("stochrsidiffmthree"); //diff stoch rsi previous 30 mins and -3 30 mins
set.addFeature("tmf"); //twiggs money flow in previous 30 mins
set.addFeature("tmfmone"); //twiggs money flow in -1 30 mins
set.addFeature("tmfdiffmone"); //diff tmf previous 30 mins and -1 30 mins
set.addFeature("tmfmtwo"); //twiggs money flow in -2 30 mins
set.addFeature("tmfdiffmtwo"); //diff tmf previous 30 mins and -2 30 mins
set.addFeature("tmfmthree"); //twiggs money flow in -3 30 mins
set.addFeature("tmfdiffmthree"); //diff tmf previous 30 mins and -3 30 mins
set.addFeature("percoutsidebandtwo"); //percentage outside bollinger bands past 2 hours (percentage of total candlestick areas outside bands)
set.addFeature("percoutsidebandsix"); //percentage outside bollinger bands past 6 hours
set.addFeature("percoutsidebandtwelve"); //percentage outside bollinger bands past 12 hours
set.addFeature("percoutsidebandday"); //percentage outside bollinger bands past 24 hours
set.addFeature("percabovebandtwo"); //percentage above bollinger bands past 2 hours
set.addFeature("percabovebandsix"); //percentage above bollinger bands past 6 hours
set.addFeature("percabovebandtwelve"); //percentage above bollinger bands past 12 hours
set.addFeature("percabovebandday"); //percentage above bollinger bands past 24 hours
set.addFeature("percbelowbandtwo"); //percentage below bollinger bands past 2 hours
set.addFeature("percbelowbandsix"); //percentage below bollinger bands past 6 hours
set.addFeature("percbelowbandtwelve"); //percentage below bollinger bands past 12 hours
set.addFeature("percbelowbandday"); //percentage below bollinger bands past 24 hours
set.addFeature("standardiseddpo"); //the standardised dpo
set.addFeature("standardiseddpomone"); //the standardised dpo 1 period before
set.addFeature("standardiseddpomtwo"); //the standardised dpo 2 periods before
set.addFeature("standardiseddpomthree"); //the standardised dpo 3 periods before
set.addFeature("standardiseddpodiffmone"); //the diff between the standardised dpo mone and current
set.addFeature("standardiseddpodiffmtwo"); //the diff between the standardised dpo mtwo and current
set.addFeature("standardiseddpodiffmthree"); //the diff between the standardised dpo mtwo and current
set.addFeature("rvi"); //relative vigor index
set.addFeature("rvimone"); //relative vigor index 1 period before
set.addFeature("rvimtwo"); //relative vigor index 2 periods before
set.addFeature("rvimthree"); //relative vigor index 3 periods before
set.addFeature("rvidiffmone"); //the diff between the rvi mone and current
set.addFeature("rvidiffmtwo"); //the diff between the rvi mtwo and current
set.addFeature("rvidiffmthree"); //the diff between the rvi mthree and current
set.addFeature("rvihist"); //relative vigor index histogram
set.addFeature("rvihistmone"); //relative vigor index histogram 1 period before
set.addFeature("rvihistmtwo"); //relative vigor index histogram 2 periods before
set.addFeature("rvihistmthree"); //relative vigor index histogram 3 periods before
set.addFeature("rvihistdiffmone"); //the diff between the rvi hist mone and current
set.addFeature("rvihistdiffmtwo"); //the diff between the rvi hist mone and current
set.addFeature("rvihistdiffmthree"); //the diff between the rvi hist mone and current
set.addFeature("stochastic"); //the stochastic oscillator for the current period
set.addFeature("stochasticmone"); //the stochastic oscillator 1 period before
set.addFeature("stochasticmtwo"); //the stochastic oscillator 2 periods before
set.addFeature("stochasticmthree"); //the stochastic oscillator 3 periods before
set.addFeature("stochasticdiffmone"); //the diff between stochastic oscillator mone and current
set.addFeature("stochasticdiffmtwo"); //the diff between stochastic oscillator mtwo and current
set.addFeature("stochasticdiffmthree"); //the diff between stochastic oscillator mthree and current
set.addFeature("stochastichist"); //the stochastic oscillator histogram
set.addFeature("stochastichistmone"); //the stochastic oscillator 1 period before
set.addFeature("stochastichistmtwo"); //the stochastic oscillator 2 periods before
set.addFeature("stochastichistmthree"); //the stochastic oscillator 3 periods before
set.addFeature("stochastichistdiffmone"); //the diff between stochastic oscillator histogram mone and current
set.addFeature("stochastichistdiffmtwo"); //the diff between stochastic oscillator histogram mtwo and current
set.addFeature("stochastichistdiffmthree"); //the diff between stochastic oscillator histogram mthree and current
set.addFeature("pmmcvolsix"); //The PMMC of the volume in the past six hours
set.addFeature("pmmcvoltwelve"); //The PMMC of the volume in the past twelve hours
set.addFeature("pmmcvolday"); //The PMMC of the volume in the past day
set.addFeature("pmmcvolthreeday"); //The PMMC of the volume in the past three days
set.addFeature("pmmcvolweek"); //The PMMC of the volume in the past week
set.addFeature("pmmcvolfort"); //The PMMC of the volume in the past fortnight
set.addFeature("pmmcvolmonth"); //The PMMC of the volume in the past month
set.addFeature("pmmcpricesix"); //The PMMC of the price in the past six hours
set.addFeature("pmmcpricetwelve"); //The PMMC of the price in the last twelve hours
set.addFeature("pmmcpriceday"); //The PMMC of the price in the last day
set.addFeature("pmmcpricethreeday"); //The PMMC of the price in the last three days
set.addFeature("pmmcpriceweek"); //The PMMC of the price in the last week
set.addFeature("pmmcpricefort"); //The PMMC of the price in the last fortnight
set.addFeature("pmmcpricemonth"); //The PMMC of the price in the last month
set.addFeature("pmmcdiffvolpricesix"); //The PMMC of the volume against the price in the past six hours
set.addFeature("pmmcdiffvolpricetwelve"); //The PMMC of the volume against the price in the past twelve hours
set.addFeature("pmmcdiffvolpriceday"); //The PMMC of the volume against the price in the past day
set.addFeature("pmmcdiffvolpricethreeday"); //The PMMC of the volume against the price in the past three days
set.addFeature("pmmcdiffvolpriceweek"); //The PMMC of the volume against the price in the past week
set.addFeature("pmmcdiffvolpricefort"); //The PMMC of the volume against the price in the past fortnight
set.addFeature("pmmcdiffvolpricemonth"); //The PMMC of the volume against the price in the past month
set.addFeature("pmmctmfsix"); //The PMMC of the tmf in the past six hours
set.addFeature("pmmctmftwelve"); //The PMMC of the tmf in the past twelve hours
set.addFeature("pmmctmfday"); //The PMMC of the tmf in the past day
set.addFeature("pmmctmfthreeday"); //The PMMC of the tmf in the past three days
set.addFeature("pmmctmfweek"); //The PMMC of the tmf in the past week
set.addFeature("pmmctmffort"); //The PMMC of the tmf in the past fortnight
set.addFeature("pmmctmfmonth"); //The PMMC of the tmf in the past month
set.addFeature("pmmcdifftmfpricesix"); //The PMMC of the tmf against the price in the past six hours
set.addFeature("pmmcdifftmfpricetwelve"); //The PMMC of the tmf against the price in the past twelve hours
set.addFeature("pmmcdifftmfpriceday"); //The PMMC of the tmf against the price in the past day
set.addFeature("pmmcdifftmfpricethreeday"); //The PMMC of the tmf against the price in the past three days
set.addFeature("pmmcdifftmfpriceweek"); //The PMMC of the tmf against the price in the past week
set.addFeature("pmmcdifftmfpricefort"); //The PMMC of the tmf against the price in the past fortnight
set.addFeature("pmmcdifftmfpricemonth"); //The PMMC of the tmf against the price in the past month
set.addFeature("ichimoku");
set.addFeature("ichimokumone");
set.addFeature("ichimokumtwo");
set.addFeature("pmmcichimokusix");
set.addFeature("pmmcichimokutwelve");
set.addFeature("pmmcichimokuday");
set.addFeature("pmmcichimokuthreeday");
set.addFeature("pmmcichimokuweek");
set.addFeature("pmmcichimokufort");
set.addFeature("pmmcichimokumonth");
}
public Trade[] thirty;
public Trade[] thirtymone;
public Trade[] thirtymtwo;
public Trade[] thirtymthree;
//Calculates a set of basic features used by all triggers
private void calculateBasicFeatures(Candlestick[] candles, Candlestick[] btcCandles, int index, FeatureVector fv, String ticker) throws Exception {
Candlestick[] pastCandles = Arrays.copyOfRange(candles, 0, index + 1);
fv.setFeature("timestamp", candles[index].getDate());
String tickerChar = "";
for (int i = 0; i < ticker.length(); i ++) {
tickerChar += (int)ticker.charAt(i) + "";
}
fv.setFeature("ticker", Double.parseDouble(tickerChar));
fv.setFeature("pddailyavg", Numerics.pc(Candlestick.weightedAverage(Arrays.copyOfRange(candles, index - getRatio(Trigger.ONE_DAY, getTimePeriod()), index)), candles[index].getClose()));
fv.setFeature("pdthreedayavg", Numerics.pc(Candlestick.weightedAverage(Arrays.copyOfRange(candles, index - getRatio(Trigger.THREE_DAYS, getTimePeriod()), index)), candles[index].getClose()));
fv.setFeature("pdweeklyavg", Numerics.pc(Candlestick.weightedAverage(Arrays.copyOfRange(candles, index - getRatio(Trigger.ONE_WEEK, getTimePeriod()), index)), candles[index].getClose()));
fv.setFeature("pdmonthlyavg", Numerics.pc(Candlestick.weightedAverage(Arrays.copyOfRange(candles, index - getRatio(Trigger.ONE_MONTH, getTimePeriod()), index)), candles[index].getClose()));
Stat s = Candlestick.getVolStat(Arrays.copyOfRange(candles, index - getRatio(Trigger.THREE_DAYS, getTimePeriod()) / getTimePeriod(), index));
if (s.std != 0) {
fv.setFeature("sdvolthirty", (candles[index].getVolume() - s.mean) / s.std);
} else {
fv.setFeature("sdvolthirty", 0);
}
double dailyVolume = Candlestick.getVolSum(Arrays.copyOfRange(candles, index - getRatio(Trigger.ONE_DAY, getTimePeriod()), index));
fv.setFeature("pvolonethirty", Numerics.perc(candles[index].getVolume(), dailyVolume));
fv.setFeature("relativeinteresttwelve", getRelativeVolume(candles, index, Trigger.TWELVE_HOURS));
fv.setFeature("relativeinterestday", getRelativeVolume(candles, index, Trigger.ONE_DAY));
fv.setFeature("relativeinterestthreeday", getRelativeVolume(candles, index, Trigger.THREE_DAYS));
fv.setFeature("relativeinterestweek", getRelativeVolume(candles, index, Trigger.ONE_WEEK));
fv.setFeature("relativeinterestfort", getRelativeVolume(candles, index, Trigger.FORTNIGHT));
fv.setFeature("ratiopricedeltatovol", candles[index].volume == 0 ? 0 : (candles[index].getClose() - candles[index].getOpen()) / candles[index].volume);
fv.setFeature("ratiopricedeltatovolmone", candles[index - 1].volume == 0 ? 0 :(candles[index - 1].getClose() - candles[index - 1].getOpen()) / candles[index - 1].volume);
fv.setFeature("ratiopricedeltatovolmtwo", candles[index - 2].volume == 0 ? 0 :(candles[index - 2].getClose() - candles[index - 2].getOpen()) / candles[index - 2].volume);
fv.setFeature("ratiopricedeltatovolmthree", candles[index - 3].volume == 0 ? 0 : (candles[index - 3].getClose() - candles[index - 3].getOpen()) / candles[index - 3].volume);
if (candles[index].volume == 0) { fv.setFeature("ratiopricedeltatovol", 0); }
if (candles[index - 1].volume == 0) { fv.setFeature("ratiopricedeltatovolmone", 0); }
if (candles[index - 2].volume == 0) { fv.setFeature("ratiopricedeltatovolmtwo", 0); }
if (candles[index - 3].volume == 0) { fv.setFeature("ratiopricedeltatovolmthree", 0); }
//thirty = Trade.loadTrades(ticker, candles[index].getDate(), candles[index].getDate() + timePeriod);
//thirtymone = Trade.loadTrades(ticker, candles[index - 1].getDate(), candles[index - 1].getDate() + timePeriod);
/*thirtymtwo = Trade.loadTrades(ticker, candles[index - 2].getDate(), candles[index - 2].getDate() + timePeriod);
thirtymthree = Trade.loadTrades(ticker, candles[index - 3].getDate(), candles[index - 3].getDate() + timePeriod);*/
thirty = new Trade[0];
thirtymone = new Trade[0];
thirtymtwo = new Trade[0];
thirtymthree = new Trade[0];
fv.setFeature("ratiobsthirty", Numerics.lockRange(0, Trade.ratioBuySell(thirty), 100));
fv.setFeature("pbuyvolsamethirty", Trade.percentageBuySamePrice(thirty));
fv.setFeature("pmodalbuyvoltodayvol", Numerics.perc(Trade.modalBuyVol(thirty), dailyVolume));
fv.setFeature("psellvolsamethirty", Trade.percentageSellSamePrice(thirty));
fv.setFeature("pmodalsellvoltodayvol", Numerics.perc(Trade.modalSellVol(thirty), dailyVolume));
fv.setFeature("pbuyvolsamethirtymone", Trade.percentageBuySamePrice(thirtymone));
fv.setFeature("pmodalbuyvoltodayvolmone", Numerics.perc(Trade.modalBuyVol(thirtymone), dailyVolume));
fv.setFeature("psellvolsamethirtymone", Trade.percentageBuySamePrice(thirtymone));
fv.setFeature("pmodalsellvoltodayvolmone", Numerics.perc(Trade.modalSellVol(thirtymone), dailyVolume));
fv.setFeature("ratiobsthirtymone", Trade.ratioBuySell(thirtymone));
fv.setFeature("ratiobsthirtymtwo", Trade.ratioBuySell(thirtymtwo));
fv.setFeature("ratiobsthirtymthree", Trade.ratioBuySell(thirtymthree));
fv.setFeature("pcbtcthirty", btcCandles[index].delta());
fv.setFeature("pcbtcthirtymone", btcCandles[index - 1].delta());
fv.setFeature("pcbtcone", Numerics.pc(btcCandles[index + 1 - getRatio(Trigger.ONE_HOUR, getTimePeriod())].getOpen(), btcCandles[index].getClose()));
fv.setFeature("pcbtctwo", Numerics.pc(btcCandles[index + 1 - getRatio(Trigger.TWO_HOURS, getTimePeriod())].getOpen(), btcCandles[index].getClose()));
fv.setFeature("pcbtcsix", Numerics.pc(btcCandles[index + 1 - getRatio(Trigger.SIX_HOURS, getTimePeriod())].getOpen(), btcCandles[index].getClose()));
fv.setFeature("pcbtctwelve", Numerics.pc(btcCandles[index + 1 - getRatio(Trigger.TWELVE_HOURS, getTimePeriod())].getOpen(), btcCandles[index].getClose()));
fv.setFeature("pcbtctwofour", Numerics.pc(btcCandles[index + 1 - Trigger.ONE_DAY / getTimePeriod()].getOpen(), btcCandles[index].getClose()));
fv.setFeature("pcbtcthree", Numerics.pc(btcCandles[index + 1 - Trigger.THREE_DAYS / getTimePeriod()].getOpen(), btcCandles[index].getClose()));
fv.setFeature("pcbtcweek", Numerics.pc(btcCandles[index + 1 - Trigger.ONE_WEEK / getTimePeriod()].getOpen(), btcCandles[index].getClose()));
fv.setFeature("pcbtcfort", Numerics.pc(btcCandles[index + 1 - Trigger.FORTNIGHT / getTimePeriod()].getOpen(), btcCandles[index].getClose()));
fv.setFeature("pcbtcmonth", Numerics.pc(btcCandles[index + 1 - Trigger.ONE_MONTH / getTimePeriod()].getOpen(), btcCandles[index].getClose()));
fv.setFeature("pcthirty", candles[index].delta());
fv.setFeature("pcthirtymone", candles[index - 1].delta());
fv.setFeature("pcthirtymtwo", candles[index - 2].delta());
fv.setFeature("pcthirtymthree", candles[index - 3].delta());
if (s.std != 0) {
fv.setFeature("sdvolthirtymone", (candles[index - 1].getVolume() - s.mean) / s.std);
fv.setFeature("sdvolthirtymtwo", (candles[index - 2].getVolume() - s.mean) / s.std);
fv.setFeature("sdvolthirtymthree", (candles[index - 3].getVolume() - s.mean) / s.std);
} else {
fv.setFeature("sdvolthirtymone", 0);
fv.setFeature("sdvolthirtymtwo", 0);
fv.setFeature("sdvolthirtymthree", 0);
}
fv.setFeature("pvolonethirtymone", Numerics.perc(candles[index - 1].getVolume(), dailyVolume));
fv.setFeature("pvolonethirtymtwo", Numerics.perc(candles[index - 2].getVolume(), dailyVolume));
fv.setFeature("pvolonethirtymthree", Numerics.perc(candles[index - 3].getVolume(), dailyVolume));
fv.setFeature("pvolonesixty", Numerics.perc(Candlestick.getVolSum(Arrays.copyOfRange(candles, index + 1 - getRatio(Trigger.ONE_HOUR, getTimePeriod()), index + 1)), dailyVolume));
fv.setFeature("pvoloneonetwenty", Numerics.perc(Candlestick.getVolSum(Arrays.copyOfRange(candles, index + 1 - getRatio(Trigger.TWO_HOURS, getTimePeriod()), index + 1)), dailyVolume));
fv.setFeature("pvolonesix", Numerics.perc(Candlestick.getVolSum(Arrays.copyOfRange(candles, index + 1 - getRatio(Trigger.SIX_HOURS, getTimePeriod()), index + 1)), dailyVolume));
fv.setFeature("npumpfive", Candlestick.totalPumps(Arrays.copyOfRange(candles, index - Trigger.FIVE_DAYS / getTimePeriod(), index)));
fv.setFeature("ndumpfive", Candlestick.totalDumps(Arrays.copyOfRange(candles, index - Trigger.FIVE_DAYS / getTimePeriod(), index)));
fv.setFeature("pcone", Numerics.pc(candles[index + 1 - getRatio(Trigger.ONE_HOUR, getTimePeriod())].getOpen(), candles[index].getClose()));
fv.setFeature("pctwo", Numerics.pc(candles[index + 1 - getRatio(Trigger.TWO_HOURS, getTimePeriod())].getOpen(), candles[index].getClose()));
fv.setFeature("pcsix", Numerics.pc(candles[index + 1 - getRatio(Trigger.SIX_HOURS, getTimePeriod())].getOpen(), candles[index].getClose()));
fv.setFeature("pctwelve", Numerics.pc(candles[index + 1 - getRatio(Trigger.TWELVE_HOURS, getTimePeriod())].getOpen(), candles[index].getClose()));
fv.setFeature("pctwofour", Numerics.pc(candles[index + 1 - Trigger.ONE_DAY / getTimePeriod()].getOpen(), candles[index].getClose()));
fv.setFeature("pctwoday", Numerics.pc(candles[index + 1 - Trigger.TWO_DAYS / getTimePeriod()].getOpen(), candles[index].getClose()));
fv.setFeature("pcthreeday", Numerics.pc(candles[index + 1 - Trigger.THREE_DAYS / getTimePeriod()].getOpen(), candles[index].getClose()));
fv.setFeature("pcfiveday", Numerics.pc(candles[index + 1 - Trigger.FIVE_DAYS / getTimePeriod()].getOpen(), candles[index].getClose()));
fv.setFeature("pcweek", Numerics.pc(candles[index + 1 - Trigger.ONE_WEEK / getTimePeriod()].getOpen(), candles[index].getClose()));
fv.setFeature("pcfort", Numerics.pc(candles[index + 1 - Trigger.FORTNIGHT / getTimePeriod()].getOpen(), candles[index].getClose()));
fv.setFeature("pcmonth", Numerics.pc(candles[index + 1 - Trigger.ONE_MONTH / getTimePeriod()].getOpen(), candles[index].getClose()));
double dailyHigh = Candlestick.high(Arrays.copyOfRange(candles, index + 1 - Trigger.ONE_DAY / getTimePeriod(), index + 1));
fv.setFeature("pddh", Numerics.pc(dailyHigh, candles[index].getClose()));
double dailyMean = Candlestick.weightedAverage(Arrays.copyOfRange(candles, index + 1 - Trigger.ONE_DAY / getTimePeriod(), index + 1));
fv.setFeature("pddm", Numerics.pc(dailyMean, candles[index].getClose()));
double dailyLow = Candlestick.low(Arrays.copyOfRange(candles, index + 1 - Trigger.ONE_DAY / getTimePeriod(), index + 1));
fv.setFeature("pddl", Numerics.pc(dailyLow, candles[index].getClose()));
double threeDayHigh = Candlestick.high(Arrays.copyOfRange(candles, index + 1 - Trigger.THREE_DAYS / getTimePeriod(), index + 1));
fv.setFeature("pdthreedh", Numerics.pc(threeDayHigh, candles[index].getClose()));
double threeDayLow = Candlestick.low(Arrays.copyOfRange(candles, index + 1 - Trigger.THREE_DAYS / getTimePeriod(), index + 1));
fv.setFeature("pdthreedl", Numerics.pc(threeDayLow, candles[index].getClose()));
double weeklyHigh = Candlestick.high(Arrays.copyOfRange(candles, index + 1 - Trigger.ONE_WEEK / getTimePeriod(), index + 1));
fv.setFeature("pdwh", Numerics.pc(weeklyHigh, candles[index].getClose()));
double weeklyLow = Candlestick.low(Arrays.copyOfRange(candles, index + 1 - Trigger.ONE_WEEK / getTimePeriod(), index + 1));
fv.setFeature("pdwl", Numerics.pc(weeklyLow, candles[index].getClose()));
double fortnightHigh = Candlestick.high(Arrays.copyOfRange(candles, index + 1 - Trigger.FORTNIGHT / getTimePeriod(), index + 1));
fv.setFeature("pdfh", Numerics.pc(fortnightHigh, candles[index].getClose()));
double fortnightLow = Candlestick.low(Arrays.copyOfRange(candles, index + 1 - Trigger.FORTNIGHT / getTimePeriod(), index + 1));
fv.setFeature("pdfl", Numerics.pc(fortnightLow, candles[index].getClose()));
double monthlyHigh = Candlestick.high(Arrays.copyOfRange(candles, index + 1 - Trigger.ONE_MONTH / getTimePeriod(), index + 1));
fv.setFeature("pdmh", Numerics.pc(monthlyHigh, candles[index].getClose()));
double monthlyLow = Candlestick.low(Arrays.copyOfRange(candles, index + 1 - Trigger.ONE_MONTH / getTimePeriod(), index + 1));
fv.setFeature("pdml", Numerics.pc(monthlyLow, candles[index].getClose()));
fv.setFeature("labtcpriceday", Math.log(Candlestick.weightedAverage(Arrays.copyOfRange(candles, index + 1 - Trigger.ONE_DAY / getTimePeriod(), index + 1))));
fv.setFeature("lvoltwofour", Math.max(0, Math.log(dailyVolume)));
fv.setFeature("labtcpriceonetofourdaymone", Math.min(3, Math.log(Candlestick.weightedAverage(Arrays.copyOfRange(candles, index + 1 - Trigger.ONE_DAY / getTimePeriod(), index + 1)) / Candlestick.weightedAverage(Arrays.copyOfRange(candles, index - (Trigger.ONE_DAY / getTimePeriod()) * 5 + 1, index - (Trigger.ONE_DAY / getTimePeriod()) + 1)))));
fv.setFeature("shadowtobodythirty", candles[index].shadowToBody());
fv.setFeature("shadowpositionthirty", candles[index].shadowPosition());
fv.setFeature("shadowtobodythirtymone", candles[index-1].shadowToBody());
fv.setFeature("shadowpositionthirtymone", candles[index-1].shadowPosition());
fv.setFeature("shadowtobodythirtymtwo", candles[index-2].shadowToBody());
fv.setFeature("shadowpositionthirtymtwo", candles[index-2].shadowPosition());
fv.setFeature("shadowtobodythirtymthree", candles[index-3].shadowToBody());
fv.setFeature("shadowpositionthirtymthree", candles[index-3].shadowPosition());
fv.setFeature("stabsix", Candlestick.stability(Arrays.copyOfRange(candles, index - getRatio(Trigger.SIX_HOURS, getTimePeriod()), index)));
fv.setFeature("stabtwelve", Candlestick.stability(Arrays.copyOfRange(candles, index - getRatio(Trigger.TWELVE_HOURS, getTimePeriod()), index)));
fv.setFeature("stabone", Candlestick.stability(Arrays.copyOfRange(candles, index - Trigger.ONE_DAY / getTimePeriod(), index)));
fv.setFeature("stabthree", Candlestick.stability(Arrays.copyOfRange(candles, index - Trigger.THREE_DAYS / getTimePeriod(), index)));
fv.setFeature("stabweek", Candlestick.stability(Arrays.copyOfRange(candles, index - Trigger.ONE_WEEK / getTimePeriod(), index)));
fv.setFeature("stabfort", Candlestick.stability(Arrays.copyOfRange(candles, index - Trigger.FORTNIGHT / getTimePeriod(), index)));
fv.setFeature("stabmonth", Candlestick.stability(Arrays.copyOfRange(candles, index - Trigger.ONE_MONTH / getTimePeriod(), index)));
fv.setFeature("pdbitcointhirty", Numerics.pc(candles[index + 1 - getRatio(Trigger.HALF_HOUR, getTimePeriod())].getOpen(), candles[index].getClose()) - Numerics.pc(btcCandles[index + 1 - getRatio(Trigger.HALF_HOUR, getTimePeriod())].getOpen(), btcCandles[index].getClose()));
fv.setFeature("pdbitcoinsixty", Numerics.pc(candles[index + 1 - getRatio(Trigger.ONE_HOUR, getTimePeriod())].getOpen(), candles[index].getClose()) - Numerics.pc(btcCandles[index + 1 - getRatio(Trigger.ONE_HOUR, getTimePeriod())].getOpen(), btcCandles[index].getClose()));
fv.setFeature("pdbitcoinonetwenty", Numerics.pc(candles[index + 1 - getRatio(Trigger.TWO_HOURS, getTimePeriod())].getOpen(), candles[index].getClose()) - Numerics.pc(btcCandles[index + 1 - getRatio(Trigger.TWO_HOURS, getTimePeriod())].getOpen(), btcCandles[index].getClose()));
fv.setFeature("pdbitcointwoforty", Numerics.pc(candles[index + 1 - getRatio(Trigger.FOUR_HOURS, getTimePeriod())].getOpen(), candles[index].getClose()) - Numerics.pc(btcCandles[index + 1 - getRatio(Trigger.FOUR_HOURS, getTimePeriod())].getOpen(), btcCandles[index].getClose()));
fv.setFeature("pdbitcoinsix", Numerics.pc(candles[index + 1 - getRatio(Trigger.SIX_HOURS, getTimePeriod())].getOpen(), candles[index].getClose()) - Numerics.pc(btcCandles[index + 1 - getRatio(Trigger.SIX_HOURS, getTimePeriod())].getOpen(), btcCandles[index].getClose()));
fv.setFeature("pdbitcointwelve", Numerics.pc(candles[index + 1 - getRatio(Trigger.TWELVE_HOURS, getTimePeriod())].getOpen(), candles[index].getClose()) - Numerics.pc(btcCandles[index + 1 - getRatio(Trigger.TWELVE_HOURS, getTimePeriod())].getOpen(), btcCandles[index].getClose()));
fv.setFeature("pdbitcointwentyfour", Numerics.pc(candles[index + 1 - Trigger.ONE_DAY / getTimePeriod()].getOpen(), candles[index].getClose()) - Numerics.pc(btcCandles[index + 1 - Trigger.ONE_DAY / getTimePeriod()].getOpen(), btcCandles[index].getClose()));
fv.setFeature("pdbitcointhree", Numerics.pc(candles[index + 1 - Trigger.THREE_DAYS / getTimePeriod()].getOpen(), candles[index].getClose()) - Numerics.pc(btcCandles[index + 1 - Trigger.THREE_DAYS / getTimePeriod()].getOpen(), btcCandles[index].getClose()));
fv.setFeature("pdbitcoinweek", Numerics.pc(candles[index + 1 - Trigger.ONE_WEEK / getTimePeriod()].getOpen(), candles[index].getClose()) - Numerics.pc(btcCandles[index + 1 - Trigger.ONE_WEEK / getTimePeriod()].getOpen(), btcCandles[index].getClose()));
fv.setFeature("pdbitcoinfort", Numerics.pc(candles[index + 1 - Trigger.FORTNIGHT / getTimePeriod()].getOpen(), candles[index].getClose()) - Numerics.pc(btcCandles[index + 1 - Trigger.FORTNIGHT / getTimePeriod()].getOpen(), btcCandles[index].getClose()));
fv.setFeature("pdbitcoinmonth", Numerics.pc(candles[index + 1 - Trigger.ONE_MONTH / getTimePeriod()].getOpen(), candles[index].getClose()) - Numerics.pc(btcCandles[index + 1 - Trigger.ONE_MONTH / getTimePeriod()].getOpen(), btcCandles[index].getClose()));
fv.setFeature("waposthirty", candles[index].weightAveragePos());
fv.setFeature("waposthirtymone", candles[index - 1].weightAveragePos());
fv.setFeature("waposthirtymtwo", candles[index - 2].weightAveragePos());
fv.setFeature("waposthirtymthree", candles[index - 3].weightAveragePos());
fv.setFeature("aroonup", Candlestick.calculateAroonUp(Arrays.copyOfRange(candles, 0, index + 1)));
fv.setFeature("aroondown", Candlestick.calculateAroonDown(Arrays.copyOfRange(candles, 0, index + 1)));
fv.setFeature("aroondelta", fv.getFeature("aroonup") - fv.getFeature("aroondown"));
fv.setFeature("aroonupmone", Candlestick.calculateAroonUp(Arrays.copyOfRange(candles, 0, index)));
fv.setFeature("aroondownmone", Candlestick.calculateAroonDown(Arrays.copyOfRange(candles, 0, index)));
fv.setFeature("aroondeltamone", fv.getFeature("aroonupmone") - fv.getFeature("aroondownmone"));
fv.setFeature("aroonupdiffmone", fv.getFeature("aroonup") - fv.getFeature("aroonupmone"));
fv.setFeature("aroondowndiffmone", fv.getFeature("aroondown") - fv.getFeature("aroondownmone"));
fv.setFeature("aroondeltadiffmone", fv.getFeature("aroondelta") - fv.getFeature("aroondeltamone"));
fv.setFeature("aroonupmtwo", Candlestick.calculateAroonUp(Arrays.copyOfRange(candles, 0, index - 1)));
fv.setFeature("aroondownmtwo", Candlestick.calculateAroonDown(Arrays.copyOfRange(candles, 0, index - 1)));
fv.setFeature("aroondeltamtwo", fv.getFeature("aroonupmtwo") - fv.getFeature("aroondownmtwo"));
fv.setFeature("aroonupdiffmtwo", fv.getFeature("aroonup") - fv.getFeature("aroonupmtwo"));
fv.setFeature("aroondowndiffmtwo", fv.getFeature("aroondown") - fv.getFeature("aroondownmtwo"));
fv.setFeature("aroondeltadiffmtwo", fv.getFeature("aroondelta") - fv.getFeature("aroondeltamtwo"));
fv.setFeature("aroonupmthree", Candlestick.calculateAroonUp(Arrays.copyOfRange(candles, 0, index - 2)));
fv.setFeature("aroondownmthree", Candlestick.calculateAroonDown(Arrays.copyOfRange(candles, 0, index - 2)));
fv.setFeature("aroondeltamthree", fv.getFeature("aroonupmthree") - fv.getFeature("aroondownmthree"));
fv.setFeature("aroonupdiffmthree", fv.getFeature("aroonup") - fv.getFeature("aroonupmthree"));
fv.setFeature("aroondowndiffmthree", fv.getFeature("aroondown") - fv.getFeature("aroondownmthree"));
fv.setFeature("aroondeltadiffmthree", fv.getFeature("aroondelta") - fv.getFeature("aroondeltamthree"));
fv.setFeature("rsi", Candlestick.calculateRSI(Arrays.copyOfRange(candles, 0, index + 1)));
fv.setFeature("stochrsi", Candlestick.calculateStochRSI(Arrays.copyOfRange(candles, 0, index + 1)));
fv.setFeature("rsimone", Candlestick.calculateRSI(Arrays.copyOfRange(candles, 0, index)));
fv.setFeature("stochrsimone", Candlestick.calculateStochRSI(Arrays.copyOfRange(candles, 0, index)));
fv.setFeature("rsidiffmone", fv.getFeature("rsi") - fv.getFeature("rsimone"));
fv.setFeature("stochrsidiffmone", fv.getFeature("stochrsi") - fv.getFeature("stochrsimone"));
fv.setFeature("rsimtwo", Candlestick.calculateRSI(Arrays.copyOfRange(candles, 0, index - 1)));
fv.setFeature("stochrsimtwo", Candlestick.calculateStochRSI(Arrays.copyOfRange(candles, 0, index - 1)));
fv.setFeature("rsidiffmtwo", fv.getFeature("rsi") - fv.getFeature("rsimtwo"));
fv.setFeature("stochrsidiffmtwo", fv.getFeature("stochrsi") - fv.getFeature("stochrsimtwo"));
fv.setFeature("rsimthree", Candlestick.calculateRSI(Arrays.copyOfRange(candles, 0, index - 2)));
fv.setFeature("stochrsimthree", Candlestick.calculateStochRSI(Arrays.copyOfRange(candles, 0, index - 2)));
fv.setFeature("rsidiffmthree", fv.getFeature("rsi") - fv.getFeature("rsimthree"));
fv.setFeature("stochrsidiffmthree", fv.getFeature("stochrsi") - fv.getFeature("stochrsimthree"));
fv.setFeature("tmf", Candlestick.calculateTwiggsMoneyFlow(Arrays.copyOfRange(candles, 0, index + 1)));
fv.setFeature("tmfmone", Candlestick.calculateTwiggsMoneyFlow(Arrays.copyOfRange(candles, 0, index)));
fv.setFeature("tmfdiffmone", fv.getFeature("tmf") - fv.getFeature("tmfmone"));
fv.setFeature("tmfmtwo", Candlestick.calculateTwiggsMoneyFlow(Arrays.copyOfRange(candles, 0, index - 1)));
fv.setFeature("tmfdiffmtwo", fv.getFeature("tmf") - fv.getFeature("tmfmtwo"));
fv.setFeature("tmfmthree", Candlestick.calculateTwiggsMoneyFlow(Arrays.copyOfRange(candles, 0, index - 2)));
fv.setFeature("tmfdiffmthree", fv.getFeature("tmf") - fv.getFeature("tmfmthree"));
fv.setFeature("percoutsidebandtwo", Candlestick.percOutsideBollingerBand(pastCandles, getRatio(Trigger.TWO_HOURS, getTimePeriod())));
fv.setFeature("percoutsidebandsix", Candlestick.percOutsideBollingerBand(pastCandles, getRatio(Trigger.SIX_HOURS, getTimePeriod())));
fv.setFeature("percoutsidebandtwelve", Candlestick.percOutsideBollingerBand(pastCandles, getRatio(Trigger.TWELVE_HOURS, getTimePeriod())));
fv.setFeature("percoutsidebandday", Candlestick.percOutsideBollingerBand(pastCandles, Trigger.ONE_DAY / getTimePeriod()));
fv.setFeature("percabovebandtwo", Candlestick.percAboveBollingerBand(pastCandles, Trigger.TWO_HOURS / getTimePeriod()));
fv.setFeature("percabovebandsix", Candlestick.percAboveBollingerBand(pastCandles, Trigger.SIX_HOURS / getTimePeriod()));
fv.setFeature("percabovebandtwelve", Candlestick.percAboveBollingerBand(pastCandles, getRatio(Trigger.TWELVE_HOURS, getTimePeriod())));
fv.setFeature("percabovebandday", Candlestick.percAboveBollingerBand(pastCandles, Trigger.ONE_DAY / getTimePeriod()));
fv.setFeature("percbelowbandtwo", Candlestick.percBelowBollingerBand(pastCandles, Trigger.TWO_HOURS / getTimePeriod()));
fv.setFeature("percbelowbandsix", Candlestick.percBelowBollingerBand(pastCandles, Trigger.SIX_HOURS / getTimePeriod()));
fv.setFeature("percbelowbandtwelve", Candlestick.percBelowBollingerBand(pastCandles, getRatio(Trigger.TWELVE_HOURS, getTimePeriod())));
fv.setFeature("percbelowbandday", Candlestick.percBelowBollingerBand(pastCandles, Trigger.ONE_DAY / getTimePeriod()));
fv.setFeature("standardiseddpo", Candlestick.calculateStandardisedDPO(Arrays.copyOfRange(candles, 0, index + 1)));
fv.setFeature("standardiseddpomone", Candlestick.calculateStandardisedDPO(Arrays.copyOfRange(candles, 0, index)));
fv.setFeature("standardiseddpomtwo", Candlestick.calculateStandardisedDPO(Arrays.copyOfRange(candles, 0, index - 1)));
fv.setFeature("standardiseddpomthree", Candlestick.calculateStandardisedDPO(Arrays.copyOfRange(candles, 0, index - 2)));
fv.setFeature("standardiseddpodiffmone", fv.getFeature("standardiseddpo") - fv.getFeature("standardiseddpomone"));
fv.setFeature("standardiseddpodiffmtwo", fv.getFeature("standardiseddpo") - fv.getFeature("standardiseddpomtwo"));
fv.setFeature("standardiseddpodiffmthree", fv.getFeature("standardiseddpo") - fv.getFeature("standardiseddpomthree"));
fv.setFeature("rvi", Candlestick.calculateRVI(Arrays.copyOfRange(candles, 0, index + 1)));
fv.setFeature("rvimone", Candlestick.calculateRVI(Arrays.copyOfRange(candles, 0, index)));
fv.setFeature("rvimtwo", Candlestick.calculateRVI(Arrays.copyOfRange(candles, 0, index - 1)));
fv.setFeature("rvimthree", Candlestick.calculateRVI(Arrays.copyOfRange(candles, 0, index - 2)));
fv.setFeature("rvidiffmone", fv.getFeature("rvi") - fv.getFeature("rvimone"));
fv.setFeature("rvidiffmtwo", fv.getFeature("rvi") - fv.getFeature("rvimtwo"));
fv.setFeature("rvidiffmthree", fv.getFeature("rvi") - fv.getFeature("rvimthree"));
fv.setFeature("rvihist", Candlestick.calculateRVIHist(Arrays.copyOfRange(candles, 0, index + 1)));
fv.setFeature("rvihistmone", Candlestick.calculateRVIHist(Arrays.copyOfRange(candles, 0, index)));
fv.setFeature("rvihistmtwo", Candlestick.calculateRVIHist(Arrays.copyOfRange(candles, 0, index - 1)));
fv.setFeature("rvihistmthree", Candlestick.calculateRVIHist(Arrays.copyOfRange(candles, 0, index - 2)));
fv.setFeature("rvihistdiffmone", fv.getFeature("rvihist") - fv.getFeature("rvihistmone"));
fv.setFeature("rvihistdiffmtwo", fv.getFeature("rvihist") - fv.getFeature("rvihistmtwo"));
fv.setFeature("rvihistdiffmthree", fv.getFeature("rvihist") - fv.getFeature("rvihistmthree"));
fv.setFeature("stochastic", Candlestick.calculateStochastic(Arrays.copyOfRange(candles, 0, index + 1)));
fv.setFeature("stochasticmone", Candlestick.calculateStochastic(Arrays.copyOfRange(candles, 0, index)));
fv.setFeature("stochasticmtwo", Candlestick.calculateStochastic(Arrays.copyOfRange(candles, 0, index - 1)));
fv.setFeature("stochasticmthree", Candlestick.calculateStochastic(Arrays.copyOfRange(candles, 0, index - 2)));
fv.setFeature("stochasticdiffmone", fv.getFeature("stochastic") - fv.getFeature("stochasticmone"));
fv.setFeature("stochasticdiffmtwo", fv.getFeature("stochastic") - fv.getFeature("stochasticmtwo"));
fv.setFeature("stochasticdiffmthree", fv.getFeature("stochastic") - fv.getFeature("stochasticmthree"));
fv.setFeature("stochastichist", Candlestick.calculateStochasticHist(Arrays.copyOfRange(candles, 0, index + 1)));
fv.setFeature("stochastichistmone", Candlestick.calculateStochasticHist(Arrays.copyOfRange(candles, 0, index)));
fv.setFeature("stochastichistmtwo", Candlestick.calculateStochasticHist(Arrays.copyOfRange(candles, 0, index - 1)));
fv.setFeature("stochastichistmthree", Candlestick.calculateStochasticHist(Arrays.copyOfRange(candles, 0, index - 2)));
fv.setFeature("stochastichistdiffmone", fv.getFeature("stochastichist") - fv.getFeature("stochastichistmone"));
fv.setFeature("stochastichistdiffmtwo", fv.getFeature("stochastichist") - fv.getFeature("stochastichistmtwo"));
fv.setFeature("stochastichistdiffmthree", fv.getFeature("stochastichist") - fv.getFeature("stochastichistmthree"));
double[] tempCandles;
double[] tempCandles2;
tempCandles = Candlestick.weightedAverages(Arrays.copyOfRange(candles, index - getRatio(Trigger.SIX_HOURS, getTimePeriod()), index));
tempCandles2 = Candlestick.volumes(Arrays.copyOfRange(candles, index - getRatio(Trigger.SIX_HOURS, getTimePeriod()), index));
fv.setFeature("pmmcpricesix", Numerics.pearsons(Numerics.generateTime(tempCandles), tempCandles));
fv.setFeature("pmmcvolsix", Numerics.pearsons(Numerics.generateTime(tempCandles2), tempCandles2));
fv.setFeature("pmmcdiffvolpricesix", fv.getFeature("pmmcvolsix") - fv.getFeature("pmmcpricesix"));
tempCandles2 = Candlestick.calculateTMFGraph(pastCandles, getRatio(Trigger.SIX_HOURS, getTimePeriod()));
fv.setFeature("pmmctmfsix", Numerics.pearsons(Numerics.generateTime(tempCandles2), tempCandles2));
fv.setFeature("pmmcdifftmfpricesix", fv.getFeature("pmmctmfsix") - fv.getFeature("pmmcpricesix"));
tempCandles = Candlestick.weightedAverages(Arrays.copyOfRange(candles, index - getRatio(Trigger.TWELVE_HOURS, getTimePeriod()), index));
tempCandles2 = Candlestick.volumes(Arrays.copyOfRange(candles, index - getRatio(Trigger.TWELVE_HOURS, getTimePeriod()), index));
fv.setFeature("pmmcpricetwelve", Numerics.pearsons(Numerics.generateTime(tempCandles), tempCandles));
fv.setFeature("pmmcvoltwelve", Numerics.pearsons(Numerics.generateTime(tempCandles2), tempCandles2));
fv.setFeature("pmmcdiffvolpricetwelve", fv.getFeature("pmmcvoltwelve") - fv.getFeature("pmmcpricetwelve"));
tempCandles2 = Candlestick.calculateTMFGraph(pastCandles, getRatio(Trigger.TWELVE_HOURS, getTimePeriod()));
fv.setFeature("pmmctmftwelve", Numerics.pearsons(Numerics.generateTime(tempCandles2), tempCandles2));
fv.setFeature("pmmcdifftmfpricetwelve", fv.getFeature("pmmctmftwelve") - fv.getFeature("pmmcpricetwelve"));
tempCandles = Candlestick.weightedAverages(Arrays.copyOfRange(candles, index + 1 - Trigger.ONE_DAY / getTimePeriod(), index + 1));
tempCandles2 = Candlestick.volumes(Arrays.copyOfRange(candles, index + 1 - Trigger.ONE_DAY / getTimePeriod(), index + 1));
fv.setFeature("pmmcpriceday", Numerics.pearsons(Numerics.generateTime(tempCandles), tempCandles));
fv.setFeature("pmmcvolday", Numerics.pearsons(Numerics.generateTime(tempCandles2), tempCandles2));
fv.setFeature("pmmcdiffvolpriceday", fv.getFeature("pmmcvolday") - fv.getFeature("pmmcpriceday"));
tempCandles2 = Candlestick.calculateTMFGraph(pastCandles, Trigger.ONE_DAY / getTimePeriod());
fv.setFeature("pmmctmfday", Numerics.pearsons(Numerics.generateTime(tempCandles2), tempCandles2));
fv.setFeature("pmmcdifftmfpriceday", fv.getFeature("pmmctmfday") - fv.getFeature("pmmcpriceday"));
tempCandles = Candlestick.weightedAverages(Arrays.copyOfRange(candles, index + 1 - Trigger.THREE_DAYS / getTimePeriod(), index + 1));
tempCandles2 = Candlestick.volumes(Arrays.copyOfRange(candles, index + 1 - Trigger.THREE_DAYS / getTimePeriod(), index + 1));
fv.setFeature("pmmcpricethreeday", Numerics.pearsons(Numerics.generateTime(tempCandles), tempCandles));
fv.setFeature("pmmcvolthreeday", Numerics.pearsons(Numerics.generateTime(tempCandles2), tempCandles2));
fv.setFeature("pmmcdiffvolpricethreeday", fv.getFeature("pmmcvolthreeday") - fv.getFeature("pmmcpricethreeday"));
tempCandles2 = Candlestick.calculateTMFGraph(pastCandles, Trigger.THREE_DAYS / getTimePeriod());
fv.setFeature("pmmctmfthreeday", Numerics.pearsons(Numerics.generateTime(tempCandles2), tempCandles2));
fv.setFeature("pmmcdifftmfpricethreeday", fv.getFeature("pmmctmfthreeday") - fv.getFeature("pmmcpricethreeday"));
tempCandles = Candlestick.weightedAverages(Arrays.copyOfRange(candles, index + 1 - Trigger.ONE_WEEK / getTimePeriod(), index + 1));
tempCandles2 = Candlestick.volumes(Arrays.copyOfRange(candles, index + 1 - Trigger.ONE_WEEK / getTimePeriod(), index + 1));
fv.setFeature("pmmcpriceweek", Numerics.pearsons(Numerics.generateTime(tempCandles), tempCandles));
fv.setFeature("pmmcvolweek", Numerics.pearsons(Numerics.generateTime(tempCandles2), tempCandles2));
fv.setFeature("pmmcdiffvolpriceweek", fv.getFeature("pmmcvolweek") - fv.getFeature("pmmcpriceweek"));
tempCandles2 = Candlestick.calculateTMFGraph(pastCandles, Trigger.ONE_WEEK / getTimePeriod());
fv.setFeature("pmmctmfweek", Numerics.pearsons(Numerics.generateTime(tempCandles2), tempCandles2));
fv.setFeature("pmmcdifftmfpriceweek", fv.getFeature("pmmctmfweek") - fv.getFeature("pmmcpriceweek"));
tempCandles = Candlestick.weightedAverages(Arrays.copyOfRange(candles, index + 1 - Trigger.FORTNIGHT / getTimePeriod(), index + 1));
tempCandles2 = Candlestick.volumes(Arrays.copyOfRange(candles, index + 1 - Trigger.FORTNIGHT / getTimePeriod(), index + 1));
fv.setFeature("pmmcpricefort", Numerics.pearsons(Numerics.generateTime(tempCandles), tempCandles));
fv.setFeature("pmmcvolfort", Numerics.pearsons(Numerics.generateTime(tempCandles2), tempCandles2));
fv.setFeature("pmmcdiffvolpricefort", fv.getFeature("pmmcvolfort") - fv.getFeature("pmmcpricefort"));
tempCandles2 = Candlestick.calculateTMFGraph(pastCandles, Trigger.FORTNIGHT / getTimePeriod());
fv.setFeature("pmmctmffort", Numerics.pearsons(Numerics.generateTime(tempCandles2), tempCandles2));
fv.setFeature("pmmcdifftmfpricefort", fv.getFeature("pmmctmffort") - fv.getFeature("pmmcpricefort"));
tempCandles = Candlestick.weightedAverages(Arrays.copyOfRange(candles, index + 1 - Trigger.ONE_MONTH / getTimePeriod(), index + 1));
tempCandles2 = Candlestick.volumes(Arrays.copyOfRange(candles, index + 1 - Trigger.ONE_MONTH / getTimePeriod(), index + 1));
fv.setFeature("pmmcpricemonth", Numerics.pearsons(Numerics.generateTime(tempCandles), tempCandles));
fv.setFeature("pmmcvolmonth", Numerics.pearsons(Numerics.generateTime(tempCandles2), tempCandles2));
fv.setFeature("pmmcdiffvolpricemonth", fv.getFeature("pmmcvolmonth") - fv.getFeature("pmmcpricemonth"));
tempCandles2 = Candlestick.calculateTMFGraph(pastCandles, Trigger.ONE_MONTH / getTimePeriod());
fv.setFeature("pmmctmfmonth", Numerics.pearsons(Numerics.generateTime(tempCandles2), tempCandles2));
fv.setFeature("pmmcdifftmfpricemonth", fv.getFeature("pmmctmfmonth") - fv.getFeature("pmmcpricemonth"));
fv.setFeature("ichimoku", Candlestick.ichimokuSignal(pastCandles));
fv.setFeature("ichimokumone", Candlestick.ichimokuSignal(Arrays.copyOfRange(pastCandles, 0, pastCandles.length - 1)));
fv.setFeature("ichimokumtwo", Candlestick.ichimokuSignal(Arrays.copyOfRange(pastCandles, 0, pastCandles.length - 2)));
tempCandles = Candlestick.calculateIchimokuSignalGraph(pastCandles, Trigger.SIX_HOURS / getTimePeriod());
fv.setFeature("pmmcichimokusix", Numerics.pearsons(tempCandles, Numerics.generateTime(tempCandles)));
tempCandles = Candlestick.calculateIchimokuSignalGraph(pastCandles, Trigger.TWELVE_HOURS / getTimePeriod());
fv.setFeature("pmmcichimokutwelve", Numerics.pearsons(tempCandles, Numerics.generateTime(tempCandles)));
tempCandles = Candlestick.calculateIchimokuSignalGraph(pastCandles, Trigger.ONE_DAY / getTimePeriod());
fv.setFeature("pmmcichimokuday", Numerics.pearsons(tempCandles, Numerics.generateTime(tempCandles)));
tempCandles = Candlestick.calculateIchimokuSignalGraph(pastCandles, Trigger.THREE_DAYS / getTimePeriod());
fv.setFeature("pmmcichimokuthreeday", Numerics.pearsons(tempCandles, Numerics.generateTime(tempCandles)));
tempCandles = Candlestick.calculateIchimokuSignalGraph(pastCandles, Trigger.ONE_WEEK / getTimePeriod());
fv.setFeature("pmmcichimokuweek", Numerics.pearsons(tempCandles, Numerics.generateTime(tempCandles)));
tempCandles = Candlestick.calculateIchimokuSignalGraph(pastCandles, Trigger.FORTNIGHT / getTimePeriod());
fv.setFeature("pmmcichimokufort", Numerics.pearsons(tempCandles, Numerics.generateTime(tempCandles)));
tempCandles = Candlestick.calculateIchimokuSignalGraph(pastCandles, Trigger.ONE_MONTH / getTimePeriod());
fv.setFeature("pmmcichimokumonth", Numerics.pearsons(tempCandles, Numerics.generateTime(tempCandles)));
}
private double getRelativeVolume(Candlestick[] candles, int index, int trigger) {
double volume = Candlestick.getVolSum(Arrays.copyOfRange(candles, index - getRatio(trigger, getTimePeriod()), index));
double prevVolume = Candlestick.getVolSum(Arrays.copyOfRange(candles, index - getRatio((trigger * 2), getTimePeriod()), index - getRatio(trigger, getTimePeriod())));
return prevVolume == 0 ? Math.min(100, volume) : volume / prevVolume;
}
} |
<reponame>HajoAhoMantila/DefinitelyTyped
import { jdenticon } from "jdenticon";
function testJdenticon() {
if (typeof jdenticon.version !== 'string') {
throw '.version should be of string type.';
}
jdenticon.update('#jdenticon', 'd6d7705392bc7af633328bea8c4c6904', 8);
}
testJdenticon();
|
A Spatial Location Method for DC Series Arc Faults Based on RSSI and Bayesian Regularization Neural Network Fires caused by DC series arcs are one of the primary threats to the safety of photovoltaic (PV) systems. Accurate fault location is extremely helpful in protecting PV plants, but existing research on locating DC series arc faults is limited. This paper proposes a novel DC series arc spatial location method. The proposed method estimates the distance based on the received signal strength indicator (RSSI) of electromagnetic radiation (EMR) emitted by the arc. The experimental system uses four antennas that form a tetrahedral topology to receive arc EMR signals. Some pretests are implemented before an arc occurs to obtain some known-location arc EMR signals, which are processed to be the candidate data of the arc EMR model. When the arc fault occurs, the candidate data are selected through comparison with the unknown-location signals. The arc EMR model is set up by the Bayesian regularized neural network (BRNN) algorithm. Then, the distances between the arc and antennas are estimated by the BRNN. The spatial coordinates are calculated with the antenna array topology and estimated distances. Finally, the verification results show that the algorithm has a 0.5 m average spatial location error, which is proven to be active and feasible. |
Records and Information Management Sec. 2 Records Retention Schedule. The University of Texas System recognizes the need for orderly management and retrieval of all official State records and a documented records retention schedule in compliance with all State and federal laws and related regulations. All official records (paper, microform, electronic, including all electronically stored information (ESI), or any other media) will be retained for the retention periods stated in the institutional Records Retention Schedule as approved by the Texas State Library and Archives Commission and the Texas State Auditor's Office in compliance with Texas Government Code, Chapter 441. After a specified period of time, official records must be disposed of in a manner that is consistent with, and systematically carried out in accordance with prescribed records and information management guidelines and procedures. |
The Impact of Dropsonde Data on the Performance of the NCEP Global Forecast System During the 2020 Atmospheric Rivers Observing Campaign. Part 1: Precipitation The impact of assimilating dropsonde data from the 2020 Atmospheric River (AR) Reconnaissance (ARR) field campaign on operational numerical precipitation forecasts was assessed. Two experiments were executed for the period from 24 January to 18 March 2020 using the NCEP Global Forecast System version 15 (GFSv15) with a four-dimensional hybrid ensemble-variational (4DEnVar) data assimilation system. The control run (CTRL) used all the routinely assimilated data and included ARR dropsonde data, whereas the denial run (DENY) excluded the dropsonde data. There were 17 Intensive Observing Periods (IOPs) totaling 46 Air Force C-130 and 16 NOAA G-IV missions to deploy dropsondes over targeted regions with potential for downstream high-impact weather associated with the ARs. Data from a total of 628 dropsondes were assimilated in the CTRL. The dropsonde data impact on precipitation forecasts over U.S. West Coast domains is largely positive, especially for day 5 lead time, and appears driven by different model variables on a case-by-case basis. These results suggest that data gaps associated with ARs can be addressed with targeted ARR field campaigns providing vital observations needed for improving U.S. West Coast precipitation forecasts. |
package api
import (
"bytes"
"encoding/json"
"fmt"
"testing"
"github.com/google/uuid"
)
func TestGroup(t *testing.T) {
checkClient(t)
web := NewSP(spClient).Web()
newGroupName := uuid.New().String()
group := &GroupInfo{}
user, err := web.CurrentUser().Select("Id,LoginName").Get()
if err != nil {
t.Error(err)
}
type groupOwner struct {
Owner struct {
ID int
}
}
t.Run("Add", func(t *testing.T) {
data, err := web.SiteGroups().Add(newGroupName, nil)
if err != nil {
t.Error(err)
}
group = data.Data()
})
t.Run("Get", func(t *testing.T) {
data, err := web.SiteGroups().GetByName(newGroupName).Get()
if err != nil {
t.Error(err)
}
if bytes.Compare(data, data.Normalized()) == -1 {
t.Error("response normalization error")
}
})
t.Run("Update", func(t *testing.T) {
metadata := make(map[string]interface{})
metadata["__metadata"] = map[string]string{
"type": "SP.Group",
}
metadata["Description"] = "It's a test group" // ToDo: check if update works
body, _ := json.Marshal(metadata)
if _, err := web.SiteGroups().GetByID(group.ID).Update(body); err != nil {
t.Error(err)
}
})
t.Run("AddUser", func(t *testing.T) {
if err := web.SiteGroups().GetByID(group.ID).AddUser(user.Data().LoginName); err != nil {
t.Error(err)
}
})
t.Run("RemoveUser", func(t *testing.T) {
if err := web.SiteGroups().GetByID(group.ID).RemoveUser(user.Data().LoginName); err != nil {
t.Error(err)
}
})
t.Run("AddUserByID", func(t *testing.T) {
if err := web.SiteGroups().GetByID(group.ID).AddUserByID(user.Data().ID); err != nil {
t.Error(err)
}
})
t.Run("RemoveUserByID", func(t *testing.T) {
if err := web.SiteGroups().GetByID(group.ID).RemoveUserByID(user.Data().ID); err != nil {
t.Error(err)
}
})
t.Run("SetAsOwner/User", func(t *testing.T) {
au, err := web.SiteUsers().Select("Id").Filter(fmt.Sprintf("Id ne %d", user.Data().ID)).Top(1).Get()
if err != nil {
t.Error(err)
}
if len(au) == 0 {
return
}
g := web.SiteGroups().GetByID(group.ID)
if err := g.SetOwner(au.Data()[0].Data().ID); err != nil {
t.Error(err)
}
o, err := g.Select("Owner/Id").Expand("Owner").Get()
if err != nil {
t.Error(err)
}
var owner *groupOwner
if err := json.Unmarshal(o.Normalized(), &owner); err != nil {
t.Error(err)
}
if owner.Owner.ID == user.Data().ID {
t.Error("can't set a user as group owner")
}
})
t.Run("SetAsOwner/Group", func(t *testing.T) {
mg, err := web.AssociatedGroups().Members().Select("Id").Get()
if err != nil {
t.Error(err)
}
g := web.SiteGroups().GetByID(group.ID)
if err := g.SetOwner(mg.Data().ID); err != nil {
t.Error(err)
}
o, err := g.Select("Owner/Id").Expand("Owner").Get()
if err != nil {
t.Error(err)
}
var owner *groupOwner
if err := json.Unmarshal(o.Normalized(), &owner); err != nil {
t.Error(err)
}
if owner.Owner.ID == user.Data().ID {
t.Error("can't set a user as group owner")
}
})
t.Run("SetUserAsOwner", func(t *testing.T) {
if envCode == "2013" {
t.Skip("is not supported with SP 2013")
}
au, err := web.SiteUsers().Select("Id").Filter(fmt.Sprintf("Id ne %d", user.Data().ID)).OrderBy("Id", false).Top(1).Get()
if err != nil {
t.Error(err)
}
if len(au) == 0 {
return
}
g := web.SiteGroups().GetByID(group.ID)
if err := g.SetUserAsOwner(au.Data()[0].Data().ID); err != nil {
t.Error(err)
}
})
t.Run("RemoveByID", func(t *testing.T) {
if err := web.SiteGroups().RemoveByID(group.ID); err != nil {
t.Error(err)
}
})
t.Run("Modifiers", func(t *testing.T) {
if _, err := web.AssociatedGroups().Visitors().Users().Get(); err != nil {
t.Error(err)
}
})
}
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2006, JBoss Inc., and individual contributors as indicated
* by the @authors tag.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.vfs;
import static org.jboss.vfs.VFSMessages.MESSAGES;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLStreamHandler;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.jboss.vfs.protocol.FileURLStreamHandler;
import org.jboss.vfs.protocol.VirtualFileURLStreamHandler;
import org.jboss.vfs.spi.MountHandle;
import org.jboss.vfs.util.PaddedManifestStream;
import org.jboss.vfs.util.PathTokenizer;
import org.jboss.vfs.util.automount.Automounter;
/**
* VFS Utilities
*
* @author <a href="<EMAIL>"><NAME></a>
* @author <a href="<EMAIL>"><NAME></a>
* @author <a href="mailto:<EMAIL>"><NAME></a>
* @version $Revision: 1.1 $
*/
public class VFSUtils {
/**
* The default encoding
*/
private static final String DEFAULT_ENCODING = "UTF-8";
/**
* Constant representing the URL vfs protocol
*/
public static final String VFS_PROTOCOL = "vfs";
/**
* Constant representing the system property for forcing case sensitive
*/
public static final String FORCE_CASE_SENSITIVE_KEY = "jboss.vfs.forceCaseSensitive";
/**
* The {@link URLStreamHandler} for the 'vfs' protocol
*/
public static final URLStreamHandler VFS_URL_HANDLER = new VirtualFileURLStreamHandler();
/**
* The {@link URLStreamHandler} for the 'file' protocol
*/
public static final URLStreamHandler FILE_URL_HANDLER = new FileURLStreamHandler();
/**
* The default buffer size to use for copies
*/
public static final int DEFAULT_BUFFER_SIZE = 65536;
/**
* This variable indicates if the FileSystem should force case sensitive independently if
* the underlying file system is case sensitive or not
*/
private static boolean forceCaseSensitive;
static {
forceCaseSensitive = AccessController.doPrivileged(new PrivilegedAction<Boolean> () {
public Boolean run() {
String forceString = System.getProperty(VFSUtils.FORCE_CASE_SENSITIVE_KEY, "false");
return Boolean.valueOf(forceString);
}
});
}
private VFSUtils() {
}
/**
* Get the paths string for a collection of virtual files
*
* @param paths the paths
* @return the string
* @throws IllegalArgumentException for null paths
*/
public static String getPathsString(Collection<VirtualFile> paths) {
if (paths == null) {
throw MESSAGES.nullArgument("paths");
}
StringBuilder buffer = new StringBuilder();
boolean first = true;
for (VirtualFile path : paths) {
if (path == null) { throw new IllegalArgumentException("Null path in " + paths); }
if (first == false) {
buffer.append(':');
} else {
first = false;
}
buffer.append(path.getPathName());
}
if (first == true) {
buffer.append("<empty>");
}
return buffer.toString();
}
/**
* Add manifest paths
*
* @param file the file
* @param paths the paths to add to
* @throws IOException if there is an error reading the manifest or the virtual file is closed
* @throws IllegalStateException if the file has no parent
* @throws IllegalArgumentException for a null file or paths
*/
public static void addManifestLocations(VirtualFile file, List<VirtualFile> paths) throws IOException {
if (file == null) {
throw MESSAGES.nullArgument("file");
}
if (paths == null) {
throw MESSAGES.nullArgument("paths");
}
boolean trace = VFSLogger.ROOT_LOGGER.isTraceEnabled();
Manifest manifest = getManifest(file);
if (manifest == null) { return; }
Attributes mainAttributes = manifest.getMainAttributes();
String classPath = mainAttributes.getValue(Attributes.Name.CLASS_PATH);
if (classPath == null) {
if (trace) {
VFSLogger.ROOT_LOGGER.tracef("Manifest has no Class-Path for %s", file.getPathName());
}
return;
}
VirtualFile parent = file.getParent();
if (parent == null) {
VFSLogger.ROOT_LOGGER.debugf("%s has no parent.", file);
return;
}
if (trace) {
VFSLogger.ROOT_LOGGER.tracef("Parsing Class-Path: %s for %s parent=%s", classPath, file.getName(), parent.getName());
}
StringTokenizer tokenizer = new StringTokenizer(classPath);
while (tokenizer.hasMoreTokens()) {
String path = tokenizer.nextToken();
try {
VirtualFile vf = parent.getChild(path);
if (vf.exists()) {
if (paths.contains(vf) == false) {
paths.add(vf);
// Recursively process the jar
Automounter.mount(file, vf);
addManifestLocations(vf, paths);
} else if (trace) {
VFSLogger.ROOT_LOGGER.tracef("%s from manifest is already in the classpath %s", vf.getName(), paths);
}
} else if (trace) {
VFSLogger.ROOT_LOGGER.trace("Unable to find " + path + " from " + parent.getName());
}
} catch (IOException e) {
VFSLogger.ROOT_LOGGER.debugf("Manifest Class-Path entry %s ignored for %s reason= %s", path, file.getPathName(), e);
}
}
}
/**
* Get a manifest from a virtual file, assuming the virtual file is the root of an archive
*
* @param archive the root the archive
* @return the manifest or null if not found
* @throws IOException if there is an error reading the manifest or the virtual file is closed
* @throws IllegalArgumentException for a null archive
*/
public static Manifest getManifest(VirtualFile archive) throws IOException {
if (archive == null) {
throw MESSAGES.nullArgument("archive");
}
VirtualFile manifest = archive.getChild(JarFile.MANIFEST_NAME);
if (manifest == null || !manifest.exists()) {
if (VFSLogger.ROOT_LOGGER.isTraceEnabled()) {
VFSLogger.ROOT_LOGGER.tracef("Can't find manifest for %s", archive.getPathName());
}
return null;
}
return readManifest(manifest);
}
/**
* Read the manifest from given manifest VirtualFile.
*
* @param manifest the VF to read from
* @return JAR's manifest
* @throws IOException if problems while opening VF stream occur
*/
public static Manifest readManifest(VirtualFile manifest) throws IOException {
if (manifest == null) {
throw MESSAGES.nullArgument("manifest file");
}
InputStream stream = new PaddedManifestStream(manifest.openStream());
try {
return new Manifest(stream);
} finally {
safeClose(stream);
}
}
/**
* Fix a name (removes any trailing slash)
*
* @param name the name to fix
* @return the fixed name
* @throws IllegalArgumentException for a null name
*/
public static String fixName(String name) {
if (name == null) {
throw MESSAGES.nullArgument("name");
}
int length = name.length();
if (length <= 1) { return name; }
if (name.charAt(length - 1) == '/') { return name.substring(0, length - 1); }
return name;
}
/**
* Decode the path with UTF-8 encoding..
*
* @param path the path to decode
* @return decoded path
*/
public static String decode(String path) {
return decode(path, DEFAULT_ENCODING);
}
/**
* Decode the path.
*
* @param path the path to decode
* @param encoding the encoding
* @return decoded path
*/
public static String decode(String path, String encoding) {
try {
return URLDecoder.decode(path, encoding);
} catch (UnsupportedEncodingException e) {
throw MESSAGES.cannotDecode(path,encoding,e);
}
}
/**
* Get the name.
*
* @param uri the uri
* @return name from uri's path
*/
public static String getName(URI uri) {
if (uri == null) {
throw MESSAGES.nullArgument("uri");
}
String name = uri.getPath();
if (name != null) {
// TODO: Not correct for certain uris like jar:...!/
int lastSlash = name.lastIndexOf('/');
if (lastSlash > 0) { name = name.substring(lastSlash + 1); }
}
return name;
}
/**
* Deal with urls that may include spaces.
*
* @param url the url
* @return uri the uri
* @throws URISyntaxException for any error
*/
public static URI toURI(URL url) throws URISyntaxException {
if (url == null) {
throw MESSAGES.nullArgument("url");
}
try {
return url.toURI();
} catch (URISyntaxException e) {
String urispec = url.toExternalForm();
// Escape percent sign and spaces
urispec = urispec.replaceAll("%", "%25");
urispec = urispec.replaceAll(" ", "%20");
return new URI(urispec);
}
}
/**
* Ensure the url is convertible to URI by encoding spaces and percent characters if necessary
*
* @param url to be sanitized
* @return sanitized URL
* @throws URISyntaxException if URI conversion can't be fixed
* @throws MalformedURLException if an error occurs
*/
public static URL sanitizeURL(URL url) throws URISyntaxException, MalformedURLException {
return toURI(url).toURL();
}
/**
* Copy all the children from the original {@link VirtualFile} the target recursively.
*
* @param original the file to copy children from
* @param target the file to copy the children to
* @throws IOException if any problems occur copying the files
*/
public static void copyChildrenRecursive(VirtualFile original, VirtualFile target) throws IOException {
if (original == null) {
throw MESSAGES.nullArgument("Original VirtualFile");
}
if (target == null) {
throw MESSAGES.nullArgument("Target VirtualFile");
}
List<VirtualFile> children = original.getChildren();
for (VirtualFile child : children) {
VirtualFile targetChild = target.getChild(child.getName());
File childFile = child.getPhysicalFile();
if (childFile.isDirectory()) {
if (!targetChild.getPhysicalFile().mkdir()) {
throw MESSAGES.problemCreatingNewDirectory(targetChild);
}
copyChildrenRecursive(child, targetChild);
} else {
FileInputStream is = new FileInputStream(childFile);
writeFile(targetChild, is);
}
}
}
/**
* Copy input stream to output stream and close them both
*
* @param is input stream
* @param os output stream
* @throws IOException for any error
*/
public static void copyStreamAndClose(InputStream is, OutputStream os) throws IOException {
copyStreamAndClose(is, os, DEFAULT_BUFFER_SIZE);
}
/**
* Copy input stream to output stream and close them both
*
* @param is input stream
* @param os output stream
* @param bufferSize the buffer size to use
* @throws IOException for any error
*/
public static void copyStreamAndClose(InputStream is, OutputStream os, int bufferSize)
throws IOException {
try {
copyStream(is, os, bufferSize);
// throw an exception if the close fails since some data might be lost
is.close();
os.close();
} finally {
// ...but still guarantee that they're both closed
safeClose(is);
safeClose(os);
}
}
/**
* Copy input stream to output stream without closing streams. Flushes output stream when done.
*
* @param is input stream
* @param os output stream
* @throws IOException for any error
*/
public static void copyStream(InputStream is, OutputStream os) throws IOException {
copyStream(is, os, DEFAULT_BUFFER_SIZE);
}
/**
* Copy input stream to output stream without closing streams. Flushes output stream when done.
*
* @param is input stream
* @param os output stream
* @param bufferSize the buffer size to use
* @throws IOException for any error
*/
public static void copyStream(InputStream is, OutputStream os, int bufferSize)
throws IOException {
if (is == null) {
throw MESSAGES.nullArgument("input stream");
}
if (os == null) {
throw MESSAGES.nullArgument("output stream");
}
byte[] buff = new byte[bufferSize];
int rc;
while ((rc = is.read(buff)) != -1) { os.write(buff, 0, rc); }
os.flush();
}
/**
* Write the given bytes to the given virtual file, replacing its current contents (if any) or creating a new file if
* one does not exist.
*
* @param virtualFile the virtual file to write
* @param bytes the bytes
* @throws IOException if an error occurs
*/
public static void writeFile(VirtualFile virtualFile, byte[] bytes) throws IOException {
final File file = virtualFile.getPhysicalFile();
file.getParentFile().mkdirs();
final FileOutputStream fos = new FileOutputStream(file);
try {
fos.write(bytes);
fos.close();
} finally {
safeClose(fos);
}
}
/**
* Write the content from the given {@link InputStream} to the given virtual file, replacing its current contents (if any) or creating a new file if
* one does not exist.
*
* @param virtualFile the virtual file to write
* @param is the input stream
* @throws IOException if an error occurs
*/
public static void writeFile(VirtualFile virtualFile, InputStream is) throws IOException {
final File file = virtualFile.getPhysicalFile();
file.getParentFile().mkdirs();
final FileOutputStream fos = new FileOutputStream(file);
copyStreamAndClose(is, fos);
}
/**
* Get the virtual URL for a virtual file. This URL can be used to access the virtual file; however, taking the file
* part of the URL and attempting to use it with the {@link java.io.File} class may fail if the file is not present
* on the physical filesystem, and in general should not be attempted.
* <b>Note:</b> if the given VirtualFile refers to a directory <b>at the time of this
* method invocation</b>, a trailing slash will be appended to the URL; this means that invoking
* this method may require a filesystem access, and in addition, may not produce consistent results
* over time.
*
* @param file the virtual file
* @return the URL
* @throws MalformedURLException if the file cannot be coerced into a URL for some reason
* @see VirtualFile#asDirectoryURL()
* @see VirtualFile#asFileURL()
*/
public static URL getVirtualURL(VirtualFile file) throws MalformedURLException {
try {
final URI uri = getVirtualURI(file);
final String scheme = uri.getScheme();
return AccessController.doPrivileged(new PrivilegedExceptionAction<URL>() {
@Override
public URL run() throws MalformedURLException{
if (VFS_PROTOCOL.equals(scheme)) {
return new URL(null, uri.toString(), VFS_URL_HANDLER);
} else if ("file".equals(scheme)) {
return new URL(null, uri.toString(), FILE_URL_HANDLER);
} else {
return uri.toURL();
}
}
});
} catch (URISyntaxException e) {
throw new MalformedURLException(e.getMessage());
} catch (PrivilegedActionException e) {
throw (MalformedURLException) e.getException();
}
}
/**
* Get the virtual URI for a virtual file.
* <b>Note:</b> if the given VirtualFile refers to a directory <b>at the time of this
* method invocation</b>, a trailing slash will be appended to the URI; this means that invoking
* this method may require a filesystem access, and in addition, may not produce consistent results
* over time.
*
* @param file the virtual file
* @return the URI
* @throws URISyntaxException if the file cannot be coerced into a URI for some reason
* @see VirtualFile#asDirectoryURI()
* @see VirtualFile#asFileURI()
*/
public static URI getVirtualURI(VirtualFile file) throws URISyntaxException {
return new URI(VFS_PROTOCOL, "", file.getPathName(true), null);
}
/**
* Get a physical URL for a virtual file. See the warnings on the {@link VirtualFile#getPhysicalFile()} method
* before using this method.
*
* @param file the virtual file
* @return the physical file URL
* @throws IOException if an I/O error occurs getting the physical file
*/
public static URL getPhysicalURL(VirtualFile file) throws IOException {
return getPhysicalURI(file).toURL();
}
/**
* Get a physical URI for a virtual file. See the warnings on the {@link VirtualFile#getPhysicalFile()} method
* before using this method.
*
* @param file the virtual file
* @return the physical file URL
* @throws IOException if an I/O error occurs getting the physical file
*/
public static URI getPhysicalURI(VirtualFile file) throws IOException {
return file.getPhysicalFile().toURI();
}
/**
* Get the physical root URL of the filesystem of a virtual file. This URL is suitable for use as a class loader's
* code source or in similar situations where only standard URL types ({@code jar} and {@code file}) are supported.
*
* @param file the virtual file
* @return the root URL
* @throws MalformedURLException if the URL is not valid
*/
public static URL getRootURL(VirtualFile file) throws MalformedURLException {
final URI uri;
try {
uri = getRootURI(file);
} catch (URISyntaxException e) {
throw new MalformedURLException(e.getMessage());
}
return uri.toURL();
}
/**
* Get the physical root URL of the filesystem of a virtual file. This URI is suitable for conversion to a class loader's
* code source URL or in similar situations where only standard URL types ({@code jar} and {@code file}) are supported.
*
* @param file the virtual file
* @return the root URI
* @throws URISyntaxException if the URI is not valid
*/
public static URI getRootURI(final VirtualFile file) throws URISyntaxException {
return VFS.getMount(file).getFileSystem().getRootURI();
}
/**
* Safely close some resource without throwing an exception. Any exception will be logged at TRACE level.
*
* @param c the resource
*/
public static void safeClose(final Closeable c) {
if (c != null) {
try {
c.close();
} catch (Exception e) {
VFSLogger.ROOT_LOGGER.trace("Failed to close resource", e);
}
}
}
/**
* Safely close some resource without throwing an exception. Any exception will be logged at TRACE level.
*
* @param closeables the resources
*/
public static void safeClose(final Closeable... closeables) {
safeClose(Arrays.asList(closeables));
}
/**
* Safely close some resources without throwing an exception. Any exception will be logged at TRACE level.
*
* @param ci the resources
*/
public static void safeClose(final Iterable<? extends Closeable> ci) {
if (ci != null) {
for (Closeable closeable : ci) {
safeClose(closeable);
}
}
}
/**
* Safely close some resource without throwing an exception. Any exception will be logged at TRACE level.
*
* @param zipFile the resource
*/
public static void safeClose(final ZipFile zipFile) {
if (zipFile != null) {
try {
zipFile.close();
} catch (Exception e) {
VFSLogger.ROOT_LOGGER.trace("Failed to close resource", e);
}
}
}
public static boolean isForceCaseSensitive() {
return forceCaseSensitive;
}
/**
* In case the file system is not case sensitive we compare the canonical path with
* the absolute path of the file after normalized.
* @param file
* @return
*/
public static boolean exists(File file) {
try {
boolean fileExists = file.exists();
if(!forceCaseSensitive || !fileExists) {
return fileExists;
}
String absPath = canonicalize(file.getAbsolutePath());
String canPath = canonicalize(file.getCanonicalPath());
return fileExists && absPath.equals(canPath);
} catch(IOException io) {
return false;
}
}
/**
* Attempt to recursively delete a real file.
*
* @param root the real file to delete
* @return {@code true} if the file was deleted
*/
public static boolean recursiveDelete(File root) {
boolean ok = true;
if (root.isDirectory()) {
final File[] files = root.listFiles();
if (files != null) {
for (File file : files) {
ok &= recursiveDelete(file);
}
}
return ok && (root.delete() || !root.exists());
} else {
ok &= root.delete() || !root.exists();
}
return ok;
}
/**
* Attempt to recursively delete a virtual file.
*
* @param root the virtual file to delete
* @return {@code true} if the file was deleted
*/
public static boolean recursiveDelete(VirtualFile root) {
boolean ok = true;
if (root.isDirectory()) {
final List<VirtualFile> files = root.getChildren();
for (VirtualFile file : files) {
ok &= recursiveDelete(file);
}
return ok && (root.delete() || !root.exists());
} else {
ok &= root.delete() || !root.exists();
}
return ok;
}
/**
* Recursively copy a file or directory from one location to another.
*
* @param original the original file or directory
* @param destDir the destination directory
* @throws IOException if an I/O error occurs before the copy is complete
*/
public static void recursiveCopy(File original, File destDir) throws IOException {
final String name = original.getName();
final File destFile = new File(destDir, name);
if (original.isDirectory()) {
destFile.mkdir();
for (File file : original.listFiles()) {
recursiveCopy(file, destFile);
}
} else {
final OutputStream os = new FileOutputStream(destFile);
try {
final InputStream is = new FileInputStream(original);
copyStreamAndClose(is, os);
} finally {
// in case the input stream open fails
safeClose(os);
}
}
}
/**
* Recursively copy a file or directory from one location to another.
*
* @param original the original file or directory
* @param destDir the destination directory
* @throws IOException if an I/O error occurs before the copy is complete
*/
public static void recursiveCopy(File original, VirtualFile destDir) throws IOException {
final String name = original.getName();
final File destFile = destDir.getChild(name).getPhysicalFile();
if (original.isDirectory()) {
destFile.mkdir();
for (File file : original.listFiles()) {
recursiveCopy(file, destFile);
}
} else {
final OutputStream os = new FileOutputStream(destFile);
try {
final InputStream is = new FileInputStream(original);
copyStreamAndClose(is, os);
} finally {
// in case the input stream open fails
safeClose(os);
}
}
}
/**
* Recursively copy a file or directory from one location to another.
*
* @param original the original virtual file or directory
* @param destDir the destination directory
* @throws IOException if an I/O error occurs before the copy is complete
*/
public static void recursiveCopy(VirtualFile original, File destDir) throws IOException {
final String name = original.getName();
final File destFile = new File(destDir, name);
if (original.isDirectory()) {
destFile.mkdir();
for (VirtualFile file : original.getChildren()) {
recursiveCopy(file, destFile);
}
} else {
final OutputStream os = new FileOutputStream(destFile);
try {
final InputStream is = original.openStream();
copyStreamAndClose(is, os);
} finally {
// in case the input stream open fails
safeClose(os);
}
}
}
/**
* Recursively copy a file or directory from one location to another.
*
* @param original the original virtual file or directory
* @param destDir the destination virtual directory
* @throws IOException if an I/O error occurs before the copy is complete
*/
public static void recursiveCopy(VirtualFile original, VirtualFile destDir) throws IOException {
final String name = original.getName();
final File destFile = destDir.getChild(name).getPhysicalFile();
if (original.isDirectory()) {
destFile.mkdir();
for (VirtualFile file : original.getChildren()) {
recursiveCopy(file, destFile);
}
} else {
final OutputStream os = new FileOutputStream(destFile);
try {
final InputStream is = original.openStream();
copyStreamAndClose(is, os);
} finally {
// in case the input stream open fails
safeClose(os);
}
}
}
private static final InputStream EMPTY_STREAM = new InputStream() {
public int read() throws IOException {
return -1;
}
};
/**
* Get the empty input stream. This stream always reports an immediate EOF.
*
* @return the empty input stream
*/
public static InputStream emptyStream() {
return EMPTY_STREAM;
}
/**
* Get an input stream that will always be consumable as a Zip/Jar file. The input stream will not be an instance
* of a JarInputStream, but will stream bytes according to the Zip specification. Using this method, a VFS file
* or directory can be written to disk as a normal jar/zip file.
*
* @param virtualFile The virtual to get a jar file input stream for
* @return An input stream returning bytes according to the zip spec
* @throws IOException if any problems occur
*/
public static InputStream createJarFileInputStream(final VirtualFile virtualFile) throws IOException {
if (virtualFile.isDirectory()) {
final VirtualJarInputStream jarInputStream = new VirtualJarInputStream(virtualFile);
return new VirtualJarFileInputStream(jarInputStream);
}
InputStream inputStream = null;
try {
final byte[] expectedHeader = new byte[4];
expectedHeader[0] = (byte) (JarEntry.LOCSIG & 0xff);
expectedHeader[1] = (byte) ((JarEntry.LOCSIG >>> 8) & 0xff);
expectedHeader[2] = (byte) ((JarEntry.LOCSIG >>> 16) & 0xff);
expectedHeader[3] = (byte) ((JarEntry.LOCSIG >>> 24) & 0xff);
inputStream = virtualFile.openStream();
final byte[] bytes = new byte[4];
final int read = inputStream.read(bytes, 0, 4);
if (read < 4 || !Arrays.equals(expectedHeader, bytes)) {
throw MESSAGES.invalidJarSignature(Arrays.toString(bytes), Arrays.toString(expectedHeader));
}
} finally {
safeClose(inputStream);
}
return virtualFile.openStream();
}
/**
* Expand a zip file to a destination directory. The directory must exist. If an error occurs, the destination
* directory may contain a partially-extracted archive, so cleanup is up to the caller.
*
* @param zipFile the zip file
* @param destDir the destination directory
* @throws IOException if an error occurs
*/
public static void unzip(File zipFile, File destDir) throws IOException {
final ZipFile zip = new ZipFile(zipFile);
try {
final Set<File> createdDirs = new HashSet<File>();
final Enumeration<? extends ZipEntry> entries = zip.entries();
FILES_LOOP:
while (entries.hasMoreElements()) {
final ZipEntry zipEntry = entries.nextElement();
final String name = zipEntry.getName();
final List<String> tokens = PathTokenizer.getTokens(name);
final Iterator<String> it = tokens.iterator();
File current = destDir;
while (it.hasNext()) {
String token = it.next();
if (PathTokenizer.isCurrentToken(token) || PathTokenizer.isReverseToken(token)) {
// invalid file; skip it!
continue FILES_LOOP;
}
current = new File(current, token);
if ((it.hasNext() || zipEntry.isDirectory()) && createdDirs.add(current)) {
current.mkdir();
}
}
if (!zipEntry.isDirectory()) {
final InputStream is = zip.getInputStream(zipEntry);
try {
final FileOutputStream os = new FileOutputStream(current);
try {
VFSUtils.copyStream(is, os);
// allow an error on close to terminate the unzip
is.close();
os.close();
} finally {
VFSUtils.safeClose(os);
}
} finally {
VFSUtils.safeClose(is);
}
// exclude jsp files last modified time change. jasper jsp compiler Compiler.java depends on last modified time-stamp to re-compile jsp files
if (!current.getName().endsWith(".jsp"))
current.setLastModified(zipEntry.getTime());
}
}
} finally {
VFSUtils.safeClose(zip);
}
}
/**
* Return the mount source File for a given mount handle.
*
* @param handle The handle to get the source for
* @return The mount source file or null if the handle does not have a source, or is not a MountHandle
*/
public static File getMountSource(Closeable handle) {
if (handle instanceof MountHandle) { return MountHandle.class.cast(handle).getMountSource(); }
return null;
}
private static final Pattern GLOB_PATTERN = Pattern.compile("(\\*\\*?)|(\\?)|(\\\\.)|(/+)|([^*?]+)");
/**
* Get a regular expression pattern which matches any path names which match the given glob. The glob patterns
* function similarly to {@code ant} file patterns. Valid meta-characters in the glob pattern include:
* <ul>
* <li><code>"\"</code> - escape the next character (treat it literally, even if it is itself a recognized meta-character)</li>
* <li><code>"?"</code> - match any non-slash character</li>
* <li><code>"*"</code> - match zero or more non-slash characters</li>
* <li><code>"**"</code> - match zero or more characters, including slashes</li>
* <li><code>"/"</code> - match one or more slash characters. Consecutive {@code /} characters are collapsed down into one.</li>
* </ul>
* In addition, like {@code ant}, if the pattern ends with a {@code /}, then an implicit <code>"**"</code> will be appended.
* <p/>
* <b>See also:</b> <a href="http://ant.apache.org/manual/dirtasks.html#patterns">"Patterns" in the Ant Manual</a>
*
* @param glob the glob to match
* @return the pattern
*/
public static Pattern getGlobPattern(final String glob) {
StringBuilder patternBuilder = new StringBuilder();
patternBuilder.append("^");
final Matcher m = GLOB_PATTERN.matcher(glob);
boolean lastWasSlash = false;
while (m.find()) {
lastWasSlash = false;
String grp;
if ((grp = m.group(1)) != null) {
// match a * or **
if (grp.length() == 2) {
// it's a **
patternBuilder.append(".*");
} else {
// it's a *
patternBuilder.append("[^/]*");
}
} else if ((grp = m.group(2)) != null) {
// match a '?' glob pattern; any non-slash character
patternBuilder.append("[^/]");
} else if ((grp = m.group(3)) != null) {
// backslash-escaped value
patternBuilder.append(grp.charAt(1));
} else if ((grp = m.group(4)) != null) {
// match any number of / chars
patternBuilder.append("/+");
lastWasSlash = true;
} else {
// some other string
patternBuilder.append(Pattern.quote(m.group()));
}
}
if (lastWasSlash) {
// ends in /, append **
patternBuilder.append(".*");
}
patternBuilder.append("$");
return Pattern.compile(patternBuilder.toString());
}
/**
* Canonicalize the given path. Removes all {@code .} and {@code ..} segments from the path.
*
* @param path the relative or absolute possibly non-canonical path
* @return the canonical path
*/
@SuppressWarnings("UnusedLabel") // for documentation
public static String canonicalize(final String path) {
final int length = path.length();
// 0 - start
// 1 - got one .
// 2 - got two .
// 3 - got /
int state = 0;
if (length == 0) {
return path;
}
final char[] targetBuf = new char[length];
// string segment end exclusive
int e = length;
// string cursor position
int i = length;
// buffer cursor position
int a = length - 1;
// number of segments to skip
int skip = 0;
loop:
while (--i >= 0) {
char c = path.charAt(i);
outer:
switch (c) {
case '/': {
inner:
switch (state) {
case 0:
state = 3;
e = i;
break outer;
case 1:
state = 3;
e = i;
break outer;
case 2:
state = 3;
e = i;
skip++;
break outer;
case 3:
e = i;
break outer;
default:
throw new IllegalStateException();
}
// not reached!
}
case '.': {
inner:
switch (state) {
case 0:
state = 1;
break outer;
case 1:
state = 2;
break outer;
case 2:
break inner; // emit!
case 3:
state = 1;
break outer;
default:
throw new IllegalStateException();
}
// fall thru
}
default: {
final int newE = e > 0 ? path.lastIndexOf('/', e - 1) : -1;
final int segmentLength = e - newE - 1;
if (skip > 0) {
skip--;
} else {
if (state == 3) {
targetBuf[a--] = '/';
}
path.getChars(newE + 1, e, targetBuf, (a -= segmentLength) + 1);
}
state = 0;
i = newE + 1;
e = newE;
break;
}
}
}
if (state == 3) {
targetBuf[a--] = '/';
}
return new String(targetBuf, a + 1, length - a - 1);
}
}
|
def handle_position(self, pos: int) -> None:
self._handle_position = pos
self.update() |
Cascading and Parallelising Curvilinear Inertial Focusing Systems for High Volume, Wide Size Distribution, Separation and Concentration of Particles Inertial focusing is a microfluidic based separation and concentration technology that has expanded rapidly in the last few years. Throughput is high compared to other microfluidic approaches although sample volumes have typically remained in the millilitre range. Here we present a strategy for achieving rapid high volume processing with stacked and cascaded inertial focusing systems, allowing for separation and concentration of particles with a large size range, demonstrated here from 30m300m. The system is based on curved channels, in a novel toroidal configuration and a stack of 20 devices has been shown to operate at 1L/min. Recirculation allows for efficient removal of large particles whereas a cascading strategy enables sequential removal of particles down to a final stage where the target particle size can be concentrated. The demonstration of curved stacked channels operating in a cascaded manner allows for high throughput applications, potentially replacing filtration in applications such as environmental monitoring, industrial cleaning processes, biomedical and bioprocessing and many more. dewatering for biofuel production 31,32, to clean circulating oil in vehicles and heavy rotating machinery 33 and bioprocessing/biotechnology 34. As implied above parallelization is oft quoted as the solution to increase throughput, particularly in microfluidics. However, as highlighted in Table S1, there are much fewer examples of successful parallelization strategies in the literature, particularly for large particles separation using inertial focusing (> 60 m in diameter). Removing pathogenic bacteria from blood samples appears to be the application which has received most attention for parallelization in inertial focusing. Mach et al. 35 reported a parallelized approach based on a "Ferris wheel" arrangement of straight channels with 40 devices fed from one inlet. This system processed 30 mL of blood at a flow rate of 8 mL/min and it was proposed that stacking of the single layer Ferris arrangement could enable further throughput increases. Hansson et al. also parallelized straight channels for a similar application achieving a higher filtration efficiency of 95% with 4 and 16 channel devices that could be operated at 4 mL/min 16. Straight and serpentine channels have been considered easier to parallelize 8,10,18. Spiral channels offer the advantage of particle focusing at one lateral position usually close to the inner wall until a threshold concentration is reached, though the central inlet location makes parallelization challenging. Some designs have proposed a double inlet to the spiral 24,36 with flow entering on the outer edge of the spiral, with the aim of enabling easier parallelization, although this merely transfers the problem to the outlet. As Mach noted stacking could enable higher throughput since in-plane parallelization results in an expanded device footprint which can quickly become impractical and this strategy for inertial focusing was demonstrated in a prototype system developed by Parc (personal communication) and in recent work by Warkiani 21,27. However, inlet pressure variance occurs when stacking and attempting to pump from one or both ends of an access port/ pipe as the distance from the pressure source is not equal through the stack. Given that flow rate is a critical parameter in determining separation efficiency 12, we have developed a new stacking approach using a novel toroidal channel design to enable easy access to the inlet and outlets along with a novel manifold to deliver equalized inlet pressure to the stack. The new designs of the IF channel as well as the novel stacking approach, here incorporating 20 devices, has enabled processing of 1 L/min doubling the current highest throughput rate for IF reported recently by Warkiani at 500 mL/min. Recirculation or multiple passes within IF devices has been proposed previously for increasing purity and yield, having been described by the authors as operating devices in series 7. However, the same sizes of devices were adopted. Cascading as a strategy has been extended in this work to employ a series of different sized devices to allow for an efficient separation of particles from an initial sample with a particle distribution size ranging over several orders of magnitude (2-300 m). In addition to cascading, recirculation is necessary to ensure high recovery rates. We demonstrate here the principle of recirculating and cascading to successfully separate and concentrate for the first time small particles (down to ~4 m) from a mixture with a large range of particle sizes (up to 300 m), providing an alternative to filtration for complex samples. The devices proposed in this work are produced using laser-cutting technologies, which allow rapid design changes and low cost manufacture in comparison to standard photolithography. Finally we propose that a combination of the stacking, recirculation and cascade strategy will enable large volume processing of samples with a large particle size range, opening up inertial focusing systems to a wider range of industrial and biotechnology applications. Results A series of curved devices with different designs (described in Fig. S1 and Table S3) were investigated for creating cascaded and stacked systems with performance characterized via imaging of particles within the device outlet channels and analyzing samples collected from the outlets using a laser diffraction particle size analyzer (Mastersizer 2000, Malvern Instruments). All the designs presented a rectangular cross-section and utilized two outlets; the one closest to the inner wall being denoted the focused outlet since the focused particles, above a certain critical diameter are collected here. The critical diameter is function of the channel geometry and has been empirically estimated by a/D h > 0.07 15, where a is the particle diameter and D h is the hydraulic diameter of the channel (Fig. 1). Performance characterisation with spiral channels. A set of spiral designs with 6 turns and 2 outlets (as illustrated schematically in Fig. 2) were produced using a laser cutter with the dimensions given in Table S3 (first three rows of the table; 500, 300 and 200 m high spiral channels with 1:6 aspect ratio). All spiral designs have the same structure (number of loops, design and number of outlets and aspect ratio) but were scaled to target the focus of a different particle size. The standard spiral designs were tested first to establish a benchmark for performance. A further two scaled device sizes were tested to determine the minimum focusing sizes of particles in 50 m and 30 m high spiral designs. These devices could be applied at the end of a cascading strategy involving the first three spirals to shift from "filtration", and removal of larger particles, to concentrate small particles of interest (~2-6 m) from a mixture containing particle sizes between 2-300 m. It is shown in Fig. 1 that the minimum size for focusing particles of diameter a observed in these scaled designs did not follow the rule commonly used to predict the sizes at which focusing generally occurs (a/D h > 0.07 15 ) with discrepancies of up to 50%. A new relationship between minimum focusing size and channel height has been observed with these scaled devices, which is described by the following equation where H is the channel height (in m). This relationship, though purely empirical, may be useful for precisely targeting specific sizes of particles, provided that the channel design conforms to the ones produced for this work. Precise details for reproducing the spiral designs can be found in the SI. Scientific RepoRts | 6:36386 | DOI: 10.1038/srep36386 Cascading and recirculation set-up. The use of a cascade of sequentially decremented scaled geometries reduces the consequent size of particles which can be focused at each stage. By choosing overlapping focusing size ranges, the efficient removal of particles large enough to clog the smaller geometries is ensured. The net effect is to fractionate and concentrate particle size ranges from a broad spectrum particle size distribution starting with the largest and working down to the smallest particle sizes. Each stage of the cascading strategy ( Fig. 2) has been tested individually, with single bead sizes as well as mixed bead sample inputs. Figure 3 illustrates the results of testing a three stage sequenced cascade (top 3 devices in Table S3) with a mixed bead sample between 1 m and 250 m (Table S5) from a 500 mL sample with ~2 continuous recirculations per device. Further details on the operation of the cascade and on the notion of recirculation are proposed in Fig. S2. Successful particle focusing is shown in Fig. 3-a, where the volume percentage of larger (> 100 m) particles is significantly increased in the focused outlet of the 500 m high spiral compared to the initial sample. Figure 3-b then confirms the removal of these particles in the unfocused outlet of the first cascade stage (500 m high spiral) and similar data is observed for each of the next two stages. Fragmentation of some of the beads introduced to the cascade were observed visually and evidence of this was captured using the high speed camera (Fig. S3). The fragmentation is clear in Fig. 3 where the particle size distribution at the unfocused outlet of the 200 m high spiral shows a broad distribution and low detection count of larger particles. The source of this fragmentation is most Table S4) with the data shown being based on the mean particle size reported by the manufacturer. The location of single particles is imaged using a high speed camera (cf. Fig. S5) or by visual observation for the larger particles (> 75 m) as presented in the video in SI. Particles are "observed to focus" when they align close to the inner wall of the spiral with 100% of particles going into the focused outlet based on 100 recorded images (number of particles detected for each case> 200). Table S5. Each spiral presents a similar design, scaled down to focus different particle sizes (~100 m for the 500 m high spiral, ~50 m for the 300 m high spiral and ~30 m for the 200 m high spiral). The initial sample volume (500 mL) is injected through the 500 m high spiral (blue arrow) and split equally into two outlets. The focused outlet contains focused particles while smaller particles are homogeneously distributed in the two outlets. The focused outlet is continuously re-injected at the inlet of the spiral until the desired volume is reached (~50 mL in this case). A 50 mL sample is collected from the unfocused outlet for measurements, the remainder of which is then injected through the 300 m high spiral and recirculated in a similar manner until the volume at the focused outlet reaches ~50 mL. The same process is repeated with the 200 m high spiral (final volume at the focused outlet ~50 mL). The flow rates were 22, 12 and 7 mL/min respectively. likely high shear forces within the pump and it is recommended to use a progressing cavity pump to mitigate this issue. It can be noted that for smaller inertial focusing channels with similar profile heights (30 and 50 m high), 100% recoveries have been reported in previous works where syringe pumps have been used 29,30,37. However, such pumps cannot be used for recirculating continuously the sample. In order to quantify the focusing performance a plot of the area under the curves shown in Fig. 3 for certain particle size classes were computed (Fig. S4). The data indicates that approximately 95% of the particles above 95 m (i.e. those which focus in this device) are found in the expected focused outlet after ~2 recirculations in the 500 m high spiral indicating a high degree of concentration/removal of the large particles. The 300 m high spiral performed equally well, enriching the larger particles (> 50 m) 19-fold, and achieving 96% collection into the focused outlet. As detailed in Fig. S2, performances could be further improved by increasing the number of recirculations. In the 200 m high spiral device some large beads (> 250 m) were recorded by the laser diffraction particle size analyzer as seen in Fig. S4, although this anomaly, given the fact that these beads are larger than the channel height and would thus clog the device, might well be explained by the bead fragmentation described above, and result from fragmented beads. Cascading in this way thus offers a means of sequential removal of larger particles as an alternative to traditional filtration concentrating the particles above the critical focusing diameter into the focused outlet and enabling high recovery of the smaller particles below this diameter into the unfocused outlet. Concentration, recovery and time required. The concentration factor, C, achieved by a single device layer is given by Equation 2 where n is the number of outlets and r is the number of recirculations as defined in Fig. S2. Therefore, a two outlet design like those presented here would reduce 100 L to 1.56 L in the focused outlet with 6 recirculations (C = 0.0156) although this will be limited by the dead volume of the system. Since small particles remain unfocused the percentage recovered into the unfocused outlet after a certain number of recirculations is 1-C such that we could expect a recovery rate of 0.98 or 98% from 6 recirculations. Higher recoveries can be reached by increasing the number of recirculations r although issues of dead volume, and any particle loss within the system, act to reduce this number. Previous work by Warkiani et al. 24 has reported recoveries of similar magnitude (85%). The time t required for sample processing can be calculated using Equation 3 Table S5. Initial sample particle size distribution and subsequent distributions present at the focused (a) and unfocused (b) outlet from each device profile size. Volume % corresponds to the volume of particles detected for a particular size range divided by the total volume of particles detected (cf. Performance Characterization section for further details). where V is the sample volume, f is the flow rate and R is total number of recirculations applied. Therefore using the stacked system which runs at 1 L/min, detailed in the next section, a sample of 100 L could be reduced to 1.5625 L after 6 recirculations in approximately 3.25 hours (193.75 mins). The concentration effect was studied using 75-90 m orange beads in the 200 m high spiral design. Results, based on image processing of particle trajectories at the outlet as detailed in Fig. S5, are shown in Fig. 4. A 450 mL inlet sample was recirculated over 100 mins down to 125 mL. The expected linear evolution of concentration over a series of 1.848 recirculations is clearly indicated in the figure, though the detected overall concentration factor falls slightly short of what would be expected, with a value of 2.9 (corresponding to 1.536 cycles) versus 3.6 expected. Fragmented beads (Fig. S3), depending on their orientation, were not recognised by the algorithm which is thought to explain this discrepancy. The drop observed after 30 minutes is likely to be due to an accumulation of beads in the outlet tubing before being expelled back into the reservoir. This temporal variation is likely to be attributable to non uniform return to the reservoir impacting the number of particles being detected. Stacked system. Two designs, the semi-circular and toroidal designs (last two rows in Table S3), were developed in order to enable the insertion of a manifold for stacking. These were designed to have the same length, and therefore ideally the same focusing behavior, as the spiral of corresponding channel height. The challenge with stacking spiral channels is that fluid delivery is from either the top or the bottom in a vertical array of devices, and therefore flow rates will vary between layers (see the "Heterogeneities in fluid distribution in stacked spiral micro-channels" section in the SI). Inertial focusing depends upon flow rate and if it is too low a focusing effect is not observed. Therefore, variation in flowrate could negatively impact upon the performance of a stacked set of channels. To overcome these issues a manifold approach to device stacking has been developed. The modular manifold was designed, inspired by a technique for ensuring highly uniform flow across an open linear section 38, and in our case adapted to evenly distribute pressure and flow rate across all channels of the stack. To check the adapted design's expected performance before production, COMSOL modelling was undertaken to predict the flow rate distribution across the 20 manifold outlets/20 device layer inputs (Fig. 5-a). Table S3 shows that a semi-circular approach allowing easy access of the manifold to the inlets (Fig. S1-Semi-circular design) was unsuccessful at focusing in the range of flow rates trialled. It is thought that the increased radius of curvature combined with the upper limit on pumping capacity hindered the formation of the secondary Dean Flows, thereby resulting in no focusing. Therefore, the toroidal design was selected and a stack of 20 of the 500 m high toroidal inertial focusing channels was produced. The stacked system is shown in Fig. 5-b with further details provided in the SI (Fig. S7). The 20 layer stacked toroidal spirals device was tested with ~250 m (blue) and ~45 m (red) beads at a flow rate of 1 L/min. The focusing of particles into the outlet closest to the inner wall was clearly visible but to further quantify the performance of the system particle size distributions were measured using the laser diffraction particle size analyzer to compare the inlet sample with those collected from the outlets. A total of 7.05 L of sample was circulated until 2.51 L was remaining in the inlet reservoir (~1.7 recirculations). Figure 5-c shows the resultant particle distributions at both the focused and unfocused outlets with the initial sample superimposed. The results indicate the level of performance of separation commensurate with expectations (very low concentration in large particles > 100 m in the unfocused outlet; particle size distributions being expressed in volumes, there is an emphasis on large particles), with some fragmentation still evident. According to individual particle counting measurements, ~88% of large particles were concentrated in the focused outlet while the unfocused outlet contained ~73% of the smaller particles after 1.7 recirculations. Fig. S5). The data points shown are an average particle count from 100 images recorded every 10 minutes using orange beads (75-90 m) recirculating in the 200 m high spiral device at a flow rate of 6.5 mL/min. Discussion Here we show how a cascading and recirculating strategy can successfully separate and concentrate small particles from a mixture with a large range of particle sizes (2-300 m) with enrichment factors of above 19, that could be improved by further recirculation steps. By sequentially removing the largest particles into a highly concentrated sample, the particle range is narrowed until the target particle size at which point this size is focussed and concentrated. This technique offers an alternative to filtration with the additional advantage that unlike traditional filtration processes which concentrate all particles above a given cut-off a relatively narrow size band of particles can be extracted from a complex mixture. We demonstrate larger scale inertial focusing than have been previously shown in the literature and observe at larger (> 300 m) channel heights that the critical size at which a particle becomes focussed is higher than predicted from the established empirical formula. A similar deviation is also observed at smaller channel heights, although in this case smaller particles than expected are focused. We propose a new relation between critical focusing particle diameter and channel height for spiral systems similar to those produced in this paper. This will assist in the design of such systems for other applications. Furthermore, we show the potential of stacking to increase the throughput of inertial focusing systems to industrially relevant sample volumes. In particular we have demonstrated a stack of 20 devices operating at 1 L/min, setting a new precedent for microfluidics throughput. This was achieved through the use of a novel toroidal inertial focusing design. The stacking approach presented enables even distribution of pressure and flow rates throughout the layers ensuring maintenance of performance and potentially enabling a larger number of devices to be integrated into a system. We believe this approach could be useful for environmental monitoring as well as industrial filtration applications and bioprocessing markets. Materials and Methods Device Designs and Manufacture. The single spiral devices used in the cascade (Fig. 3) were all manufactured in PMMA using an Epilog Mini 24 CO 2 laser cutter, tuned individually for each material thickness, to pattern device layers. PSA1589F adhesive transfer tape (18 m thickness) was applied to both sides of the device layer material prior to patterning. Assembly was achieved by removing the tape backing and sandwiching (b) A photo of the stacked system. The stack consists of 20 rectangular toroidal channels (500 m high, 1:6 aspect ratio). The manifold described in Fig. 5-a is inserted at the centre of the stack (white block) to ensure an homogenous fluid distribution between the different layers. Two aluminium box sections are sealed at the top of the system to collect the liquid coming out from the focused and unfocused outlets respectively, with gravity equalising the back pressure at the outlets. Two populations of particles (as described in Table S6) are diluted in 7.05 L of tap water and processed through the stack at 1 L/min over 1.7 recirculations. (c) Corresponding particle size distributions at the inlet (purple curve), focused (red curve) and unfocused (green curve) outlets. Scientific RepoRts | 6:36386 | DOI: 10.1038/srep36386 between a ported layer and a substrate layer. Connections for the cascaded devices were achieved with generic 1/8 bspt barbed tubing connectors and 2.4 mm ID tygon tubing. To run the spiral channels a 12-roller Watson-Marlow Peristaltic pump was used. The semi-circular device was also produced using this technique. A height of 200 m was the maximum which could be manufactured due to constraints of the laser cutter workbed relative to the length of channel required to be directly comparable to a spiral of the same height. For the devices with channel height of 30 m manufacture was outsourced to the commercial company Epigem Ltd. From designs produced using AutoCAD Epigem manufactured the systems in Epoxy and PMMA. These devices were run using a WPI AL1000-220 syringe pump and 5 mL BD Lure Lock syringes. 50 m devices were laser micro-machined and bonded using a hybrid solvent/plasticiser low temperature press bonding method. The stack of toroidal 500 m high spirals (Fig. 5-b) was produced by the individual manufacture of each device layer with assembly taking place through a jigged alignment process and finally bonding was achieved using high tack adhesive transfer tape. For the stack 1/8 bspt to 6 mm push fit connectors were used in conjunction with LDPE tubing. Device and substrate layers were patterned using a CNC Laser Cutter exploiting the larger workbed. This method was also used to produce the single layer 500 m high toroidal channel used to confirm the focusing performance of this design. Further details regarding each designs tested in this work are available in the SI (Tables S2 and S3, Figs S1 and S7). Manifold manufacture. The manifold, presented in Fig. 5-a, was manufactured in nylon using a 3D printer from a model created in AutoCAD 2012. Comsol simulation. A velocity field of the mid z-plane section was generated using the laminar flow solver on the geometry of the manifold imported from the AutoCAD 3D model at 1 L/min flow rate with 20 inlet sections of the same geometry as the 500 m high device inlets. Chemicals and Beads. All of the beads above 5 m were sourced from Cospheric LLC, with the exception of the turquoise and red beads which were obtained from Phosphorex. The beads of size 5 m and below were sourced from Magsphere. All bead details are given in Table S4. Tween 20 (Sigma-Aldrich) was added to the sample to reduce aggregation of beads due to static build up on the polystyrene beads. A magnetic stirrer was used in the inlet reservoir to agitate the sample to prevent settling of the beads (Fig. S2). Performance Characterization. Particle size measurements were obtained in triplicate using a laser diffraction particle size analyzer (Mastersizer 2000, Malvern Instruments ) to analyse the inlet samples and the subsequent samples collected from the outlets. Particle size distributions measured by the Mastersizer are expressed in volume percentage. A high speed camera setup (CCD ProgRes, Jenoptik, GmbH), mounted to an inverted microscope (Nikon, x10 or x25 magnification), was used to observe the evolution of concentration over time in a single layer system with a single bead size population. In the focussed outlet a batch of 100 photos was collected at 10 min intervals. Data was analysed in MATLAB and beads were detected based on intensity differences between background and particles using thresholds (cf. Fig. S5). |
<reponame>corets/use-throttle<gh_stars>0
import { useEffect, useRef, useState } from "react"
import throttle from "lodash/throttle"
import { UseThrottle } from "./types"
export const useThrottle: UseThrottle = <TValue>(
value: TValue,
delay,
options
) => {
const [state, setState] = useState<TValue | null>(
typeof value === "function" ? null : value
)
const callback = throttle(
(...args) => {
if (typeof ref.current.value === "function") {
ref.current.value(...args)
} else {
setState(ref.current.value)
}
},
delay,
options
)
const ref = useRef({ value, callback })
useEffect(() => {
ref.current.value = value
if (typeof ref.current.value !== "function") {
ref.current.callback()
}
}, [value])
return typeof ref.current.value === "function"
? (ref.current.callback as any)
: state
}
|
Rear Add-on Device for Drag Reduction of Van Body Truck In this work, to reduce the drag of a van body truck, an aerodynamic device is fixing on the aft-body with different angle of declination and shape of the wing. The effects of reducing drag are studied by the methods of Numerical Simulation. And then the mechanism is discussed. The paper selects four rear add-on devices with different obliquity by 5deg, 10deg, 15deg and 20deg. And the shape of the wing is defined as straight line and curve, respectively. Seen from the results of numerical simulation, the rear add-on device can reduce the drag effectively. When the declination angle is 15deg, the effect is the best and the drag of the truck model is reduced by 8.9%. Furthermore, when the add-on plate is changed from contouring with straight line into Witozinsky curve in the same declination angle, the drag can reduce about another 3%. With the optimum declination angle and wing shape, the drag of the truck model is reduced 11.98%. |
<gh_stars>1-10
package seedu.anilist.ui;
import java.util.Comparator;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import seedu.anilist.model.anime.Anime;
/**
* An UI component that displays information of a {@code Anime}.
*/
public class AnimeCard extends UiPart<Region> {
private static final String FXML = "AnimeListCard.fxml";
/**
* Note: Certain keywords such as "location" and "resources" are reserved keywords in JavaFX.
* As a consequence, UI elements' variable names cannot be set to such keywords
* or an exception will be thrown by JavaFX during runtime.
*
* @see <a href="https://github.com/se-edu/addressbook-level4/issues/336">The issue on AddressBook level 4</a>
*/
public final Anime anime;
@FXML
private HBox cardPane;
@FXML
private Label name;
@FXML
private Label id;
@FXML
private Label episode;
@FXML
private Label status;
@FXML
private FlowPane genres;
/**
* Creates a {@code AnimeCard} with the given {@code Anime} and index to display.
*/
public AnimeCard(Anime anime, int displayedIndex) {
super(FXML);
this.anime = anime;
id.setText(displayedIndex + ". ");
name.setText(anime.getName().fullName);
episode.setText(anime.getEpisode().toString());
status.setText(anime.getStatus().toString());
anime.getGenres().stream()
.sorted(Comparator.comparing(genre -> genre.genreName))
.forEach(genre -> genres.getChildren().add(new Label(genre.genreName)));
}
@Override
public boolean equals(Object other) {
// short circuit if same object
if (other == this) {
return true;
}
// instanceof handles nulls
if (!(other instanceof AnimeCard)) {
return false;
}
// state check
AnimeCard card = (AnimeCard) other;
return id.getText().equals(card.id.getText())
&& anime.equals(card.anime);
}
}
|
Analysis on the Influence of Local Government Behavior on Regional Economic Development under the Current Fiscal System In the process of China's regional economic development, local governments, as the regulating body of regional economy, are the main body of protection. Some measures taken to prove their own interests will lead to unbalanced development of regional economy. This paper tries to analyze the existing problems, and the influence of local government's behavior on regional economic development under the financial system. Development is a common topic faced by the countries in the world in the process of economic development. If this is the excessive imbalance will severely affect a country's economic and social development, even do serious harm for donational unity and political stability. The problem of regional economic development gap in China has existed for a long time. Natural geographical factors, ideological factors, policy factors, layout and structure factors, capital issues, human capital and so on. Under the condition of market economy, the allocation of resources in the whole society should be based on market and regional economic development. Exhibitions should also follow the basic laws of market economy, but the market is not omnipotent. In the development of regional economy, exhibitions should follow the basic laws of market economy. In some areas, the market is ineffective or inefficient. At this time, the local government is the main regulator of the regional economy. We need to give full play to our role and guide the harmonious development of regional economy. 1. The role of local government in the development of regional economy |
/// Permutation method that swaps vowels for other vowels (e.g.
/// `google.com` -> `gougle.com`).
pub fn vowel_swap(&self) -> impl Iterator<Item = String> + '_ {
Domain::filter_domains(
self.fqdn
.chars()
.enumerate()
.filter_map(move |(i, c)| {
if VOWELS.contains(&c) {
Some(VOWELS.iter().filter_map(move |vowel| {
if *vowel == c {
None
} else {
Some(format!(
"{}{}{}",
&self.fqdn[..i],
vowel,
&self.fqdn[i + 1..]
))
}
}))
} else {
None
}
})
.flatten(),
)
} |
A ROS based framework for Multi-floor navigation for unmanned ground robots This paper presents use of a cost graph as a representation of a multi-floor building to enable the multi-floor autonomous navigation capability for a team of robot(s). A method for global path planning on this cost graph have been presented. A navigation stack provides a framework for building autonomous navigation capabilities. A navigation stack which enables use of the proposed approach for navigation in a multi-floor building and enables multi-robot operations has been detailed. The improvements provided by the proposed navigation stack over the existing ROS (Robot Operating System) navigation stack have been explained. A way to integrate multiple local path-execution nodes which can combine together to execute the planned global path has also been explained. The paper also demonstrates the reuse of existing ROS compliant source codes for implementation of the proposed navigation stack, thereby optimizing the use of proven and established technology. Further, the extensions to different components of the existing ROS navigation stack, definition of new ROS messages and action definitions, to enable interaction between the components of the stack has been explained. The paper concludes with a brief study on how the proposed stack can be used for multi-robot operations. |
/**
* Decorator for describing path params in requests. This is used to decorate a parameter object in `@request` decorated methods.
*
* @example
```
@endpoint({
path: "/users/:id",
// ...
})
class GetUserEndpoint {
@request
request(
@pathParams
pathParams: {
id: string;
// ...
}
// ...
) {}
// ...
}
```
*/
export declare function pathParams(target: any, propertyKey: string, parameterIndex: number): void;
|
With Jay Leno set to say goodbye to his 10 p.m. time slot in February, NBC has just announced the lineup of shows that will fill in the huge void left by canceling five hours of evening programming in one fell swoop.
Law & Order will get shuffled around to fill in the 10:00 ET/PT slot on Mondays.
Parenthood fills in the blank on Tuesday nights.
Law & Order: Special Victims Unit will pick up the slack on Wednesdays.
New, Jerry Seinfeld-produced show The Marriage Ref will get the historically popular Thursday night spot.
And good ol’ NBC newser Dateline will end the work week on Fridays.
All of this will begin in early March, after NBC completes its coverage of the Winter Olympics in Vancouver. |
Correlation of temperature and pathophysiological effect during radiofrequency catheter ablation of the AV junction. BACKGROUND Accelerated junctional rhythms have been observed before the development of AV nodal block during radiofrequency (RF) catheter ablation of the AV junction. However, the time course and temperatures required to induce an accelerated junctional rhythm and AV nodal block during this procedure have not yet been characterized. METHODS AND RESULTS Nineteen patients underwent RF ablation of the AV junction with a thermistor ablation catheter. RF energy was initially delivered at 10 W for 9 seconds and then increased by 5-W increments for 9 seconds at each power level up to a maximum power of 50 W. If a junctional rhythm was observed during the power titration, a 30- to 60-second RF application was then delivered at the same power level. The power was then further increased to a maximum of 50 W if AV nodal block was not observed after 20 seconds of RF delivery. The procedure was successful in all 19 patients. A median of one RF application (range, one to eight applications) was required to produce permanent AV nodal block. An accelerated junctional rhythm was observed during 89% of successful attempts versus 70% of unsuccessful deliveries (P = NS). The median time to onset of the junctional rhythm was significantly shorter during successful compared with unsuccessful applications (1.8 versus 7.7 seconds, respectively; P <.001). Similarly, the mean time to appearance of AV nodal block was significantly shorter during successful compared with unsuccessful attempts (19.6 +/- 9.4 versus 36.8 +/- 19.0 seconds, respectively; P <.01). The catheter tip temperatures associated with the development of an accelerated junctional rhythm were significantly lower than those associated with the appearance of AV nodal block (51 +/- 4 degrees C versus 58 +/- 6 degrees C, respectively; P <.001). Mean temperatures in the range of 60 +/- 7 degrees C were required to produce permanent AV nodal block. CONCLUSIONS The development of an accelerated junctional rhythm within 5 seconds and the appearance of AV nodal block within 30 seconds of RF onset were both highly characteristic of successful target sites during RF ablation of the AV junction. The accelerated junctional rhythm and AV nodal block were both highly temperature dependent. The temperatures associated with the onset of AV nodal block were significantly higher than the temperatures resulting in an accelerated junctional rhythm. |
// checkServiceMetadata checks all service metadata and adds the results to GCM.
func checkServiceMetadata(v23ctx *context.T, ctx *tool.Context, s *cloudmonitoring.Service) error {
serviceNames := []string{
monitoring.SNMounttable,
monitoring.SNIdentity,
monitoring.SNRole,
monitoring.SNProxy,
monitoring.SNBenchmark,
monitoring.SNAllocator,
}
hasError := false
mdMetadata, err := gcm.GetMetric("service-metadata", projectFlag)
if err != nil {
return err
}
now := time.Now()
strNow := now.UTC().Format(time.RFC3339)
for _, serviceName := range serviceNames {
ms, err := checkSingleServiceMetadata(v23ctx, ctx, serviceName)
if err != nil {
test.Fail(ctx, "%s\n", serviceName)
fmt.Fprintf(ctx.Stderr(), "%v\n", err)
hasError = true
continue
}
aggBuildTime := newAggregator()
aggBuildAge := newAggregator()
for _, m := range ms {
buildTimeUnix := m.buildTime.Unix()
buildAgeInHours := now.Sub(m.buildTime).Hours()
instance := m.location.Instance
zone := m.location.Zone
aggBuildTime.add(float64(buildTimeUnix))
aggBuildAge.add(buildAgeInHours)
if err := sendDataToGCM(s, mdMetadata, float64(buildTimeUnix), strNow, instance, zone, serviceName, "build time"); err != nil {
return err
}
if err := sendDataToGCM(s, mdMetadata, buildAgeInHours, strNow, instance, zone, serviceName, "build age"); err != nil {
return err
}
label := fmt.Sprintf("%s (%s, %s)", serviceName, instance, zone)
test.Pass(ctx, "%s: build time: %d, build age: %v\n", label, buildTimeUnix, buildAgeInHours)
}
mdMetadataAgg, err := gcm.GetMetric("service-metadata-agg", projectFlag)
if err != nil {
return err
}
if err := sendAggregatedDataToGCM(ctx, s, mdMetadataAgg, aggBuildTime, strNow, serviceName, "build time"); err != nil {
return err
}
if err := sendAggregatedDataToGCM(ctx, s, mdMetadataAgg, aggBuildAge, strNow, serviceName, "build age"); err != nil {
return err
}
}
if hasError {
return fmt.Errorf("failed to check metadata for some services.")
}
return nil
} |
package Seacrest
import (
"bufio"
"encoding/json"
"errors"
"fmt"
uuid "github.com/nu7hatch/gouuid"
"log"
"os"
"time"
)
type EventEnvelope struct {
EventID string
Order uint
AggregateID string
EventType string
Payload []byte
RecordedAt int64
}
type EventStore struct {
orderedEvents []EventEnvelope // <global order> -> EventEnvelope
eventsByID map[string]map[uint]EventEnvelope // <aggregateID> -> <version> -> EventEnvelope
globalOrder uint
}
func NewEventStore() *EventStore {
eventsByID := make(map[string]map[uint]EventEnvelope, 0)
orderedEvents := make([]EventEnvelope, 0)
es := EventStore{orderedEvents, eventsByID, 0}
return &es
}
func (es *EventStore) GetAllEvents() []EventEnvelope {
return es.orderedEvents
}
func (es *EventStore) PersistEvent(aggregateID string, eventType string, payload []byte) error {
UUID, err := uuid.NewV4()
if err != nil {
return err
}
eventEnvelope := EventEnvelope{
EventID: UUID.String(),
Order: es.GlobalOrder() + 1,
AggregateID: aggregateID,
EventType: eventType,
Payload: payload,
RecordedAt: time.Now().UnixNano(),
}
return es.PersistEventEnvelope(eventEnvelope)
}
func (es *EventStore) GetEventsByAggregateID(aggregateID string) map[uint]EventEnvelope {
if aggregateEvents, ok := es.eventsByID[aggregateID]; ok {
return aggregateEvents
}
return nil
}
func closeFileHandle(f *os.File) {
err := f.Close()
if err != nil {
fmt.Printf(err.Error())
}
}
func (es *EventStore) WriteEventsToFile(filename string) error {
f, err := os.Create(filename)
if err != nil {
return err
}
defer closeFileHandle(f)
for _, event := range es.orderedEvents {
eventJson, err := json.Marshal(event)
if err != nil {
return err
}
_, err = f.WriteString(string(eventJson) + "\n")
if err != nil {
return err
}
}
err = f.Sync()
if err != nil {
return err
}
return nil
}
func (es *EventStore) LoadEventsFromFile(filename string) error {
f, err := os.Open(filename)
if err != nil {
log.Fatal(err)
}
defer closeFileHandle(f)
scanner := bufio.NewScanner(f)
for scanner.Scan() {
eventEnvelope := EventEnvelope{}
err := json.Unmarshal(scanner.Bytes(), &eventEnvelope)
if err != nil {
return err
}
err = es.PersistEventEnvelope(eventEnvelope)
if err != nil {
return err
}
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
return nil
}
func (es *EventStore) GlobalOrder() uint {
return es.globalOrder
}
func (es *EventStore) IncrementGlobalOrder() {
es.globalOrder++
}
func (es *EventStore) PersistEventEnvelope(envelope EventEnvelope) error {
version := uint(0)
if _, ok := es.eventsByID[envelope.AggregateID]; ok {
version = uint(len(es.eventsByID[envelope.AggregateID]))
if _, ok := es.eventsByID[envelope.AggregateID][version]; ok {
return errors.New(fmt.Sprintf("event version %d already exists for envelope %+v", version, envelope))
}
es.eventsByID[envelope.AggregateID][version] = envelope
} else {
es.eventsByID[envelope.AggregateID] = map[uint]EventEnvelope{
0: envelope,
}
}
es.orderedEvents = append(es.orderedEvents, envelope)
es.IncrementGlobalOrder()
return nil
}
|
Eraño Manalo
Biography
Eraño G. Manalo was born at Riverside Drive, San Juan, Rizal (now part of Metro Manila) on January 2, 1925. He was the fifth child of Felix Y. Manalo and Honorata de Guzman. His name came from a reversal and elision of the term "New Era", which his father used to describe what he felt was "a new Christian era" as the Iglesia ni Cristo was established. His older siblings were Sisters Pilar and Avelina, and Brothers Dominador and Salvador. His youngest sibling is Brother Bienvenido, who is currently the head of INC's construction and engineering department.
Eraño received his elementary education at St. John's Academy in San Juan, Metro Manila, starting at the age of six.
Manalo initially took up law school, but left his studies to become a minister of the INC. He started attending the church's ministerial classes at the age of 16 and was ordained as a minister on May 10, 1947 in Locale Congregation of Tayuman, Ecclesiastical District of Manila, at the age of 22. He held various positions in the church including being the General Treasurer of the INC and circulation manager of the Pasugo magazine (now known as Pasugo: God's Message). During this time, he wrote a 64-page booklet entitled Christ-God: Investigated-False.
On January 17, 1955, Eraño Manalo married Cristina Villanueva with whom he has six children (Eduardo V. Manalo, Lolita Manalo-Hemedez, Erlinda Manalo-Alcantara, Liberty Manalo-Albert, Felix Nathaniel Manalo II and Marco Eraño Manalo). On February 18, 1953, ten years before his father's death, Eraño G. Manalo was elected successor to his father as Executive Minister. Following Eraño's death, his son Eduardo then assumed the role of INC's Executive Minister.
Administration
With the death of Felix Y. Manalo on April 12, 1963, Iglesia's critics predicted the church's decline and eventual fall. To them, the church's popularity was due mainly to the charisma and leadership of Felix Y. Manalo. Barely a month after assuming his role as spiritual leader of the church, the young Manalo began visiting congregations nationwide. At every location he visited, he officiated worship services and staged massive religious rallies in public plazas. During this period of transition in what critics thought was the most vulnerable period of the church, Manalo further consolidated the gains of the church.
In 1947, Manalo became the General Treasurer of the church. He was later elected as successor to Felix Y. Manalo by provincial ministers as early as 1953. In 1957 he became the District Minister of Manila. Very few people outside of the church gave Manalo's leadership potential enough credit. He would later initiate significant moves that would make the church to what it is today.
Manalo demonstrated the church responsiveness to the needs of the poor. Even before the government initiated agrarian reforms, Manalo established model land reforms. In 1965, the first of the resettlement farms was Maligaya farm in Palayan City, Nueva Ecija, Philippines. Similar projects were established in Cavite, Rizal and other provinces.
As early as 1967, four years after assuming leadership role, Manalo set his vision to overseas mission and global expansion. The first overseas INC mission was sent in 1968 on its 54th anniversary. On July 27, 1968, Executive Minister Eraño G. Manalo, officiated at the first worship service of the church outside the Philippines. This gathering held in Ewa Beach, Honolulu, Hawaii marked the establishment of the Honolulu congregation, the first overseas mission of the church. The following month, the Executive Minister was in California to establish the San Francisco congregation and lead its inaugural worship service. In 1971, the church set foot in Canada. In June 1987, the US Main Office (USMO) was set up in Daly City, California to assist the INC central administration in supervising the then 11 districts of the church in the West. The first local congregation in Latin America was established in Guantanamo Bay, Cuba in 1990. The following year, the church reached Mexico and Aruba. From 2000 and beyond, congregations rose in the Central and South American countries. The first local congregation in Europe was established in England in 1972. The church came to Germany and Switzerland in the mid-70s. By the end of the 1980s, congregations and missions could be found in the Scandinavian countries and their neighbors. The Rome, Italy congregation was established on July 27, 1994; the Jerusalem, Israel congregation in March 31, 1996; and the Athens, Greece congregation in May 10, 1997. The predecessors (prayer groups) of these full-fledged congregations began two decades earlier. Meanwhile, the mission first reached Spain in 1979. The first mission in northern Africa opened in Nigeria in October 1978. After a month, the King William’s Town congregation, in South Africa was established. A congregation was organized in Guam in 1969. In Australia, congregations have been established since mid-1970s. The church first reached China by way of Hong Kong, and Japan through Tokyo also in the 1970s. Missions have also opened in Kazakhstan and Sakhalin Island in Russia. In Southeast Asia, the first congregation in Thailand was established in 1976 and missions have already been conducted in Brunei since 1979. In addition, there are also congregations in Vietnam, Indonesia, Singapore, and Malaysia.
The INC started operating a radio station in 1969. While its first television program aired in 1983. The Ministerial Institute of Development, currently the New Era University College of Evangelical Ministry, was founded in 1974 in Quiapo, Manila. It moved to its current location in Quezon City in 1978. As of 1995, it had 4,500 students and five extension schools in Bulacan, Cavite, Laguna, Pampanga and Rizal. In 1965, INC launched its first resettlement and land reform program in Barrio Maligaya, Laur, Nueva Ecija. In 1971, the INC Central Office building was built in Quezon City. Thirteen years later, the 7,000-seater Central Temple was added in the complex. The Tabernacle, a tent-like multipurpose building which can accommodate up to 4,000 persons, was finished in 1989. The complex also includes the New Era University, a higher-education institution run by the INC.
Recognition
The Quezon City government renamed what was Central Avenue to Eraño G. Manalo Avenue. Ordinance number SP-1961 S-2009 the Quezon City Council stated the renaming was to is recognition of "“his greatness and nobility” in leading the powerful religious group."
On April 13, 2010 The Philippine Postal Corporation announced that it will issue a limited edition postage stamp in his honor. The stamp will be released on April 23 with 100,000 pieces with a denomination of P 7.00. |
/* Copyright (c) 2017-2021, <NAME> */
#pragma once
#include <chrono>
#include <string_view>
#include <type_traits>
#include <vector>
#include "roq/api.h"
#include "roq/fbs/api.h"
namespace roq {
namespace fbs {
template <typename B, typename T>
auto encode(B &b, const T &);
// std::string_view
template <typename B>
auto encode(B &builder, const std::string_view &value) {
return builder.CreateString(value);
}
// std::chrono::duration
template <typename B>
auto encode(B &, const std::chrono::nanoseconds &value) {
return value.count();
}
template <typename B>
auto encode(B &, const std::chrono::milliseconds &value) {
return value.count();
}
template <typename B>
auto encode(B &, const std::chrono::seconds &value) {
return value.count();
}
template <typename B>
auto encode(B &, const roq::chrono::days &value) {
return value.count();
}
// enums
template <typename B>
auto encode([[maybe_unused]] B &builder, const roq::ConnectionStatus &value) {
using result_type = ConnectionStatus;
using value_type = std::underlying_type_t<result_type>;
return static_cast<result_type>(static_cast<value_type>(value));
}
template <typename B>
auto encode([[maybe_unused]] B &builder, const roq::Error &value) {
using result_type = Error;
using value_type = std::underlying_type_t<result_type>;
return static_cast<result_type>(static_cast<value_type>(value));
}
template <typename B>
auto encode([[maybe_unused]] B &builder, const roq::Liquidity &value) {
using result_type = Liquidity;
using value_type = std::underlying_type_t<result_type>;
return static_cast<result_type>(static_cast<value_type>(value));
}
template <typename B>
auto encode([[maybe_unused]] B &builder, const roq::ExecutionInstruction &value) {
using result_type = ExecutionInstruction;
using value_type = std::underlying_type_t<result_type>;
return static_cast<result_type>(static_cast<value_type>(value));
}
template <typename B>
auto encode([[maybe_unused]] B &builder, const roq::OptionType &value) {
using result_type = OptionType;
using value_type = std::underlying_type_t<result_type>;
return static_cast<result_type>(static_cast<value_type>(value));
}
template <typename B>
auto encode([[maybe_unused]] B &builder, const roq::OrderStatus &value) {
using result_type = OrderStatus;
using value_type = std::underlying_type_t<result_type>;
return static_cast<result_type>(static_cast<value_type>(value));
}
template <typename B>
auto encode([[maybe_unused]] B &builder, const roq::OrderType &value) {
using result_type = OrderType;
using value_type = std::underlying_type_t<result_type>;
return static_cast<result_type>(static_cast<value_type>(value));
}
template <typename B>
auto encode([[maybe_unused]] B &builder, const roq::OrderUpdateAction &value) {
using result_type = OrderUpdateAction;
using value_type = std::underlying_type_t<result_type>;
return static_cast<result_type>(static_cast<value_type>(value));
}
template <typename B>
auto encode([[maybe_unused]] B &builder, const roq::Origin &value) {
using result_type = Origin;
using value_type = std::underlying_type_t<result_type>;
return static_cast<result_type>(static_cast<value_type>(value));
}
template <typename B>
auto encode([[maybe_unused]] B &builder, const roq::PositionEffect &value) {
using result_type = PositionEffect;
using value_type = std::underlying_type_t<result_type>;
return static_cast<result_type>(static_cast<value_type>(value));
}
template <typename B>
auto encode([[maybe_unused]] B &builder, const roq::Priority &value) {
using result_type = Priority;
using value_type = std::underlying_type_t<result_type>;
return static_cast<result_type>(static_cast<value_type>(value));
}
template <typename B>
auto encode([[maybe_unused]] B &builder, const roq::RateLimitType &value) {
using result_type = RateLimitType;
using value_type = std::underlying_type_t<result_type>;
return static_cast<result_type>(static_cast<value_type>(value));
}
template <typename B>
auto encode([[maybe_unused]] B &builder, const roq::RequestStatus &value) {
using result_type = RequestStatus;
using value_type = std::underlying_type_t<result_type>;
return static_cast<result_type>(static_cast<value_type>(value));
}
template <typename B>
auto encode([[maybe_unused]] B &builder, const roq::RequestType &value) {
using result_type = RequestType;
using value_type = std::underlying_type_t<result_type>;
return static_cast<result_type>(static_cast<value_type>(value));
}
template <typename B>
auto encode([[maybe_unused]] B &builder, const roq::SecurityType &value) {
using result_type = SecurityType;
using value_type = std::underlying_type_t<result_type>;
return static_cast<result_type>(static_cast<value_type>(value));
}
template <typename B>
auto encode([[maybe_unused]] B &builder, const roq::Side &value) {
using result_type = Side;
using value_type = std::underlying_type_t<result_type>;
return static_cast<result_type>(static_cast<value_type>(value));
}
template <typename B>
auto encode([[maybe_unused]] B &builder, const roq::StreamType &value) {
using result_type = StreamType;
using value_type = std::underlying_type_t<result_type>;
return static_cast<result_type>(static_cast<value_type>(value));
}
// note! not used directly... redundant, really
template <typename B>
auto encode([[maybe_unused]] B &builder, const roq::SupportType &value) {
using result_type = SupportType;
using value_type = std::underlying_type_t<result_type>;
return static_cast<result_type>(static_cast<value_type>(value));
}
template <typename B>
auto encode([[maybe_unused]] B &builder, const roq::TimeInForce &value) {
using result_type = TimeInForce;
using value_type = std::underlying_type_t<result_type>;
return static_cast<result_type>(static_cast<value_type>(value));
}
template <typename B>
auto encode([[maybe_unused]] B &builder, const roq::TradingStatus &value) {
using result_type = TradingStatus;
using value_type = std::underlying_type_t<result_type>;
return static_cast<result_type>(static_cast<value_type>(value));
}
template <typename B>
auto encode([[maybe_unused]] B &builder, const roq::StatisticsType &value) {
using result_type = StatisticsType;
using value_type = std::underlying_type_t<result_type>;
return static_cast<result_type>(static_cast<value_type>(value));
}
// helper
template <typename B>
auto encode(B &builder, const roq::Layer &value) {
return CreateLayer(builder, value.bid_price, value.bid_quantity, value.ask_price, value.ask_quantity);
}
template <typename B>
auto encode(B &builder, const roq::MBPUpdate &value) {
return CreateMBPUpdate(
builder, value.price, value.quantity, value.implied_quantity, value.price_level, value.number_of_orders);
}
template <typename B>
auto encode(B &builder, const roq::MBOUpdate &value) {
return CreateMBOUpdate(
builder,
value.price,
value.remaining_quantity,
encode(builder, value.action),
value.priority,
encode(builder, static_cast<std::string_view>(value.order_id)));
}
template <typename B>
auto encode(B &builder, const roq::Trade &value) {
return CreateTrade(
builder,
encode(builder, value.side),
value.price,
value.quantity,
encode(builder, static_cast<std::string_view>(value.trade_id)));
}
template <typename B>
auto encode(B &builder, const roq::Fill &value) {
return CreateFill(
builder,
encode(builder, static_cast<std::string_view>(value.external_trade_id)),
value.quantity,
value.price,
encode(builder, value.liquidity));
}
template <typename B>
auto encode(B &builder, const roq::Statistics &value) {
return CreateStatistics(
builder,
encode(builder, value.type),
value.value,
encode(builder, value.begin_time_utc),
encode(builder, value.end_time_utc));
}
template <typename B>
auto encode(B &builder, const roq::Measurement &value) {
return CreateMeasurement(builder, encode(builder, static_cast<std::string_view>(value.name)), value.value);
}
// roq::span
template <typename B>
auto encode(B &builder, const roq::span<roq::MBPUpdate> &value) {
std::vector<flatbuffers::Offset<MBPUpdate>> result;
auto size = value.size();
if (size) {
result.reserve(size);
for (const auto &item : value) {
result.emplace_back(encode(builder, item));
}
}
return builder.CreateVector(result);
}
template <typename B>
auto encode(B &builder, const roq::span<roq::MBOUpdate> &value) {
std::vector<flatbuffers::Offset<MBOUpdate>> result;
auto size = value.size();
if (size) {
result.reserve(size);
for (const auto &item : value) {
result.emplace_back(encode(builder, item));
}
}
return builder.CreateVector(result);
}
template <typename B>
auto encode(B &builder, const roq::span<roq::Trade> &value) {
std::vector<flatbuffers::Offset<Trade>> result;
auto size = value.size();
if (size) {
result.reserve(size);
for (const auto &item : value) {
result.emplace_back(encode(builder, item));
}
}
return builder.CreateVector(result);
}
template <typename B>
auto encode(B &builder, const roq::span<roq::Fill> &value) {
std::vector<flatbuffers::Offset<Fill>> result;
auto size = value.size();
if (size) {
result.reserve(size);
for (const auto &item : value) {
result.emplace_back(encode(builder, item));
}
}
return builder.CreateVector(result);
}
template <typename B>
auto encode(B &builder, const roq::span<roq::Statistics> &value) {
std::vector<flatbuffers::Offset<Statistics>> result;
auto size = value.size();
if (size) {
result.reserve(size);
for (const auto &item : value) {
result.emplace_back(encode(builder, item));
}
}
return builder.CreateVector(result);
}
template <typename B>
auto encode(B &builder, const roq::span<roq::Measurement> &value) {
std::vector<flatbuffers::Offset<Measurement>> result;
auto size = value.size();
if (size) {
result.reserve(size);
for (const auto &item : value) {
result.emplace_back(encode(builder, item));
}
}
return builder.CreateVector(result);
}
template <typename B, std::size_t N>
auto encode(B &builder, const roq::span<roq::string_buffer<N> const> &value) {
std::vector<flatbuffers::Offset<flatbuffers::String>> result;
auto size = value.size();
if (size) {
result.reserve(size);
for (const auto &item : value) {
result.emplace_back(encode(builder, static_cast<std::string_view>(item)));
}
}
return builder.CreateVector(result);
}
// structs
template <typename B>
auto encode(B &builder, const roq::MessageInfo &value) {
return CreateSourceInfo(
builder,
value.source_seqno,
encode(builder, value.receive_time_utc),
encode(builder, value.origin_create_time_utc),
encode(builder, value.receive_time),
encode(builder, value.origin_create_time));
}
template <typename B>
auto encode(B &builder, const roq::DownloadBegin &value) {
return CreateDownloadBegin(builder, encode(builder, value.account));
}
template <typename B>
auto encode(B &builder, const roq::DownloadEnd &value) {
return CreateDownloadEnd(builder, encode(builder, value.account), value.max_order_id);
}
template <typename B>
auto encode(B &builder, const roq::GatewaySettings &value) {
return CreateGatewaySettings(
builder,
value.supports, // note! using Mask<SupportType>
value.mbp_max_depth,
value.mbp_allow_price_inversion,
value.mbp_allow_remove_non_existing,
value.oms_download_has_state,
value.oms_download_has_routing_id,
value.mbp_tick_size_multiplier,
value.mbp_min_trade_vol_multiplier);
}
template <typename B>
auto encode(B &builder, const roq::StreamStatus &value) {
return CreateStreamStatus(
builder,
value.stream_id,
encode(builder, value.account),
value.supports, // note! using Mask<SupportType>
encode(builder, value.status),
encode(builder, value.type),
encode(builder, value.priority));
}
template <typename B>
auto encode(B &builder, const roq::ExternalLatency &value) {
return CreateExternalLatency(builder, value.stream_id, encode(builder, value.latency));
}
template <typename B>
auto encode(B &builder, const roq::RateLimitTrigger &value) {
return CreateRateLimitTrigger(
builder,
encode(builder, value.name),
encode(builder, value.origin),
encode(builder, value.type),
encode(builder, value.users),
encode(builder, value.accounts),
encode(builder, value.ban_expires),
encode(builder, value.triggered_by));
}
template <typename B>
auto encode(B &builder, const roq::GatewayStatus &value) {
return CreateGatewayStatus(
builder,
encode(builder, value.account),
value.supported, // note! using Mask<SupportType>
value.available, // note! using Mask<SupportType>
value.unavailable); // note! using Mask<SupportType>
}
template <typename B>
auto encode(B &builder, const roq::ReferenceData &value) {
return CreateReferenceData(
builder,
value.stream_id,
encode(builder, value.exchange),
encode(builder, value.symbol),
encode(builder, value.description),
encode(builder, value.security_type),
encode(builder, value.currency),
encode(builder, value.settlement_currency),
encode(builder, value.commission_currency),
value.tick_size,
value.multiplier,
value.min_trade_vol,
encode(builder, value.option_type),
encode(builder, value.strike_currency),
value.strike_price,
encode(builder, value.underlying),
encode(builder, value.time_zone),
encode(builder, value.issue_date),
encode(builder, value.settlement_date),
encode(builder, value.expiry_datetime),
encode(builder, value.expiry_datetime_utc));
}
template <typename B>
auto encode(B &builder, const roq::MarketStatus &value) {
return CreateMarketStatus(
builder,
value.stream_id,
encode(builder, value.exchange),
encode(builder, value.symbol),
encode(builder, value.trading_status));
}
template <typename B>
auto encode(B &builder, const roq::TopOfBook &value) {
return CreateTopOfBook(
builder,
value.stream_id,
encode(builder, value.exchange),
encode(builder, value.symbol),
encode(builder, value.layer),
value.snapshot,
encode(builder, value.exchange_time_utc));
}
template <typename B>
auto encode(B &builder, const roq::MarketByPriceUpdate &value) {
return CreateMarketByPriceUpdate(
builder,
value.stream_id,
encode(builder, value.exchange),
encode(builder, value.symbol),
encode(builder, value.bids),
encode(builder, value.asks),
value.snapshot,
encode(builder, value.exchange_time_utc));
}
template <typename B>
auto encode(B &builder, const roq::MarketByOrderUpdate &value) {
return CreateMarketByOrderUpdate(
builder,
value.stream_id,
encode(builder, value.exchange),
encode(builder, value.symbol),
encode(builder, value.bids),
encode(builder, value.asks),
value.snapshot,
encode(builder, value.exchange_time_utc));
}
template <typename B>
auto encode(B &builder, const roq::TradeSummary &value) {
return CreateTradeSummary(
builder,
value.stream_id,
encode(builder, value.exchange),
encode(builder, value.symbol),
encode(builder, value.trades),
encode(builder, value.exchange_time_utc));
}
template <typename B>
auto encode(B &builder, const roq::StatisticsUpdate &value) {
return CreateStatisticsUpdate(
builder,
value.stream_id,
encode(builder, value.exchange),
encode(builder, value.symbol),
encode(builder, value.statistics),
value.snapshot,
encode(builder, value.exchange_time_utc));
}
template <typename B>
auto encode(B &builder, const roq::CreateOrder &value) {
return CreateCreateOrder(
builder,
encode(builder, value.account),
value.order_id,
encode(builder, value.exchange),
encode(builder, value.symbol),
encode(builder, value.side),
encode(builder, value.position_effect),
value.max_show_quantity,
encode(builder, value.order_type),
encode(builder, value.time_in_force),
encode(builder, value.execution_instruction),
encode(builder, value.order_template),
value.quantity,
value.price,
value.stop_price,
encode(builder, value.routing_id));
}
template <typename B>
auto encode(B &builder, const roq::ModifyOrder &value) {
return CreateModifyOrder(
builder,
encode(builder, value.account),
value.order_id,
value.quantity,
value.price,
encode(builder, value.routing_id),
value.version,
value.conditional_on_version);
}
template <typename B>
auto encode(B &builder, const roq::CancelOrder &value) {
return CreateCancelOrder(
builder,
encode(builder, value.account),
value.order_id,
encode(builder, value.routing_id),
value.version,
value.conditional_on_version);
}
template <typename B>
auto encode(B &builder, const roq::CancelAllOrders &value) {
return CreateCancelAllOrders(builder, encode(builder, value.account));
}
template <typename B>
auto encode(B &builder, const roq::OrderAck &value) {
return CreateOrderAck(
builder,
value.stream_id,
encode(builder, value.account),
value.order_id,
encode(builder, value.exchange),
encode(builder, value.symbol),
encode(builder, value.type),
encode(builder, value.origin),
encode(builder, value.status),
encode(builder, value.error),
encode(builder, value.text),
encode(builder, value.request_id),
encode(builder, value.external_account),
encode(builder, value.external_order_id),
encode(builder, value.routing_id),
value.version,
encode(builder, value.side));
}
template <typename B>
auto encode(B &builder, const roq::OrderUpdate &value) {
return CreateOrderUpdate(
builder,
value.stream_id,
encode(builder, value.account),
value.order_id,
encode(builder, value.exchange),
encode(builder, value.symbol),
encode(builder, value.side),
encode(builder, value.position_effect),
value.max_show_quantity,
encode(builder, value.order_type),
encode(builder, value.time_in_force),
encode(builder, value.execution_instruction),
encode(builder, value.order_template),
encode(builder, value.create_time_utc),
encode(builder, value.update_time_utc),
encode(builder, value.external_account),
encode(builder, value.external_order_id),
encode(builder, value.status),
value.quantity,
value.price,
value.stop_price,
value.remaining_quantity,
value.traded_quantity,
value.average_traded_price,
value.last_traded_quantity,
value.last_traded_price,
encode(builder, value.last_liquidity),
encode(builder, value.routing_id),
value.max_request_version,
value.max_response_version,
value.max_accepted_version);
}
template <typename B>
auto encode(B &builder, const roq::TradeUpdate &value) {
return CreateTradeUpdate(
builder,
value.stream_id,
encode(builder, value.account),
value.order_id,
encode(builder, value.exchange),
encode(builder, value.symbol),
encode(builder, value.side),
encode(builder, value.position_effect),
encode(builder, value.create_time_utc),
encode(builder, value.update_time_utc),
encode(builder, value.external_account),
encode(builder, value.external_order_id),
encode(builder, value.fills),
encode(builder, value.routing_id));
}
template <typename B>
auto encode(B &builder, const roq::PositionUpdate &value) {
return CreatePositionUpdate(
builder,
value.stream_id,
encode(builder, value.account),
encode(builder, value.exchange),
encode(builder, value.symbol),
encode(builder, value.side),
value.position,
value.last_trade_id,
value.position_cost,
value.position_yesterday,
value.position_cost_yesterday,
encode(builder, value.external_account));
}
template <typename B>
auto encode(B &builder, const roq::FundsUpdate &value) {
return CreateFundsUpdate(
builder,
value.stream_id,
encode(builder, value.account),
encode(builder, value.currency),
value.balance,
value.hold,
encode(builder, value.external_account));
}
template <typename B>
auto encode(B &builder, const roq::CustomMetrics &value) {
return CreateCustomMetrics(
builder,
encode(builder, value.label),
encode(builder, value.account),
encode(builder, value.exchange),
encode(builder, value.symbol),
encode(builder, value.measurements));
}
template <typename B>
auto encode(B &builder, const roq::CustomMetricsUpdate &value) {
return CreateCustomMetricsUpdate(
builder,
encode(builder, value.user),
encode(builder, value.label),
encode(builder, value.account),
encode(builder, value.exchange),
encode(builder, value.symbol),
encode(builder, value.measurements));
}
// events
template <typename B>
flatbuffers::Offset<Event> encode(B &builder, const roq::Event<roq::DownloadBegin> &event) {
return CreateEvent(
builder, encode(builder, event.message_info), Message_DownloadBegin, encode(builder, event.value).Union());
}
template <typename B>
auto encode(B &builder, const roq::Event<roq::DownloadEnd> &event) {
return CreateEvent(
builder, encode(builder, event.message_info), Message_DownloadEnd, encode(builder, event.value).Union());
}
template <typename B>
auto encode(B &builder, const roq::Event<roq::GatewaySettings> &event) {
return CreateEvent(
builder, encode(builder, event.message_info), Message_GatewaySettings, encode(builder, event.value).Union());
}
template <typename B>
auto encode(B &builder, const roq::Event<roq::StreamStatus> &event) {
return CreateEvent(
builder, encode(builder, event.message_info), Message_StreamStatus, encode(builder, event.value).Union());
}
template <typename B>
auto encode(B &builder, const roq::Event<roq::ExternalLatency> &event) {
return CreateEvent(
builder, encode(builder, event.message_info), Message_ExternalLatency, encode(builder, event.value).Union());
}
template <typename B>
auto encode(B &builder, const roq::Event<roq::RateLimitTrigger> &event) {
return CreateEvent(
builder, encode(builder, event.message_info), Message_RateLimitTrigger, encode(builder, event.value).Union());
}
template <typename B>
auto encode(B &builder, const roq::Event<roq::GatewayStatus> &event) {
return CreateEvent(
builder, encode(builder, event.message_info), Message_GatewayStatus, encode(builder, event.value).Union());
}
template <typename B>
auto encode(B &builder, const roq::Event<roq::ReferenceData> &event) {
return CreateEvent(
builder, encode(builder, event.message_info), Message_ReferenceData, encode(builder, event.value).Union());
}
template <typename B>
auto encode(B &builder, const roq::Event<roq::MarketStatus> &event) {
return CreateEvent(
builder, encode(builder, event.message_info), Message_MarketStatus, encode(builder, event.value).Union());
}
template <typename B>
auto encode(B &builder, const roq::Event<roq::TopOfBook> &event) {
return CreateEvent(
builder, encode(builder, event.message_info), Message_TopOfBook, encode(builder, event.value).Union());
}
template <typename B>
auto encode(B &builder, const roq::Event<roq::MarketByPriceUpdate> &event) {
return CreateEvent(
builder, encode(builder, event.message_info), Message_MarketByPriceUpdate, encode(builder, event.value).Union());
}
template <typename B>
auto encode(B &builder, const roq::Event<roq::MarketByOrderUpdate> &event) {
return CreateEvent(
builder, encode(builder, event.message_info), Message_MarketByOrderUpdate, encode(builder, event.value).Union());
}
template <typename B>
auto encode(B &builder, const roq::Event<roq::TradeSummary> &event) {
return CreateEvent(
builder, encode(builder, event.message_info), Message_TradeSummary, encode(builder, event.value).Union());
}
template <typename B>
auto encode(B &builder, const roq::Event<roq::StatisticsUpdate> &event) {
return CreateEvent(
builder, encode(builder, event.message_info), Message_StatisticsUpdate, encode(builder, event.value).Union());
}
template <typename B>
auto encode(B &builder, const roq::Event<roq::CreateOrder> &event) {
return CreateEvent(
builder, encode(builder, event.message_info), Message_CreateOrder, encode(builder, event.value).Union());
}
template <typename B>
auto encode(B &builder, const roq::Event<roq::ModifyOrder> &event) {
return CreateEvent(
builder, encode(builder, event.message_info), Message_ModifyOrder, encode(builder, event.value).Union());
}
template <typename B>
auto encode(B &builder, const roq::Event<roq::CancelOrder> &event) {
return CreateEvent(
builder, encode(builder, event.message_info), Message_CancelOrder, encode(builder, event.value).Union());
}
template <typename B>
auto encode(B &builder, const roq::Event<roq::CancelAllOrders> &event) {
return CreateEvent(
builder, encode(builder, event.message_info), Message_CancelAllOrders, encode(builder, event.value).Union());
}
template <typename B>
auto encode(B &builder, const roq::Event<roq::OrderAck> &event) {
return CreateEvent(
builder, encode(builder, event.message_info), Message_OrderAck, encode(builder, event.value).Union());
}
template <typename B>
auto encode(B &builder, const roq::Event<roq::OrderUpdate> &event) {
return CreateEvent(
builder, encode(builder, event.message_info), Message_OrderUpdate, encode(builder, event.value).Union());
}
template <typename B>
auto encode(B &builder, const roq::Event<roq::TradeUpdate> &event) {
return CreateEvent(
builder, encode(builder, event.message_info), Message_TradeUpdate, encode(builder, event.value).Union());
}
template <typename B>
auto encode(B &builder, const roq::Event<roq::PositionUpdate> &event) {
return CreateEvent(
builder, encode(builder, event.message_info), Message_PositionUpdate, encode(builder, event.value).Union());
}
template <typename B>
auto encode(B &builder, const roq::Event<roq::FundsUpdate> &event) {
return CreateEvent(
builder, encode(builder, event.message_info), Message_FundsUpdate, encode(builder, event.value).Union());
}
template <typename B>
auto encode(B &builder, const roq::Event<roq::CustomMetrics> &event) {
return CreateEvent(
builder, encode(builder, event.message_info), Message_CustomMetrics, encode(builder, event.value).Union());
}
template <typename B>
auto encode(B &builder, const roq::Event<roq::CustomMetricsUpdate> &event) {
return CreateEvent(
builder, encode(builder, event.message_info), Message_CustomMetricsUpdate, encode(builder, event.value).Union());
}
} // namespace fbs
} // namespace roq
|
Differential effects of carvedilol on norepinephrine release in normoxic and ischemic heart. Carvedilol is a beta-adrenoceptor antagonist with multiple actions, which may contribute to superior cardioprotection in heart failure and myocardial infarction. We hypothesized that carvedilol may modulate presynaptic norepinephrine release in the heart. Therefore, we compared the effects of carvedilol (racemate and both enantiomers) and beta1-selective as well as nonselective beta-adrenoceptor blockers on norepinephrine release in isolated perfused rat hearts under normoxic and brief ischemic conditions. Exocytotic release of endogenous norepinephrine was induced by paired electric field stimulations to compare the release before (S1) and after (S2) beta-adrenoceptor blocker application. Metoprolol, bisoprolol, and pindolol (0.1-10 microM) had essentially no effect on exocytotic norepinephrine release under normoxic and ischemic conditions. In contrast, carvedilol exerted a biphasic concentration-response curve (increase followed by suppression) on norepinephrine release. The increase in norepinephrine release was more pronounced with R-carvedilol than with S-carvedilol, indicating an effect independent from beta-receptor antagonism. During ischemia, the facilitatory effect of carvedilol on norepinephrine release was lost, resulting in a concentration-dependent suppression of the release. These results indicate that carvedilol in contrast to classic beta1-selective and -nonselective beta-adrenoceptor blockers has pronounced effects on cardiac norepinephrine release with a remarkable difference between normoxic and ischemic conditions. Whereas a facilitation of norepinephrine release prevailed in normoxia, we observed a suppression of the release in ischemia. It remains to be established whether this unique action of carvedilol on cardiac sympathetic neurotransmission is of clinical relevance. |
package com.yt.seckill.controller;
import com.alibaba.fastjson.JSONObject;
import com.yt.seckill.entity.SysUser;
import com.yt.seckill.entity.TGoods;
import com.yt.seckill.service.impl.SysUserServiceImpl;
import com.yt.seckill.service.impl.TGoodsServiceImpl;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* <p>
* 前端控制器
* </p>
*
* @author yt
* @since 2022-01-12
*/
@RestController
@RequestMapping("/goods")
@Tag(name = "t-goods-controller", description = "商品接口")
public class TGoodsController {
@Autowired
TGoodsServiceImpl tGoodsService;
@PostMapping("/insert")
@Operation(summary = "商品新增")
public Map insert(@RequestBody @Valid TGoods entity, BindingResult bindingResult) {
if (bindingResult.hasErrors())
throw new RuntimeException(bindingResult.getFieldError().getDefaultMessage());
return tGoodsService.insertGoods(entity);
}
@PostMapping("/delete")
@Operation(summary = "商品删除")
public String delete(@RequestBody String dataId) {
return tGoodsService.deleteGoods((String) JSONObject.parseObject(dataId).get("dataId"));
}
@PostMapping("/list")
@Operation(summary = "分页+条件查询商品列表,参数:\"pageNum\":0,\n" +
"\"pageSize\":10,\n" + "\"keyWord\":\"要查的关键字,没有就为空查询全部\"")
public Map list(@RequestBody Map params) {
return tGoodsService.selectlist(params);
}
@PostMapping("/update")
@Operation(summary = "更新操作")
public String update(@RequestBody TGoods entity) {
return tGoodsService.updateOne(entity);
}
@PostMapping("/detail")
@Operation(summary = "根据dataid查询对应商品信息")
public TGoods detail(@RequestBody String dataId) {
return tGoodsService.detail((String)JSONObject.parseObject(dataId).get("dataId"));
}
}
|
<gh_stars>1-10
package main
import (
"context"
"fmt"
"os"
"os/signal"
"syscall"
)
func main() {
defer fmt.Println("done")
// define signals to handle
trapSignals := []os.Signal{
syscall.SIGHUP,
syscall.SIGINT,
syscall.SIGTERM,
syscall.SIGQUIT}
// create channel for receiving signal
sigCh := make(chan os.Signal, 1)
// receive
signal.Notify(sigCh, trapSignals...)
// create cancelable context for passing main processing
ctx, cancel := context.WithCancel(context.Background())
// wait signal another goroutine
go func() {
// block until catch signal
sig := <-sigCh
fmt.Println("Got signal", sig)
cancel()
}()
doMain(ctx)
}
func doMain(ctx context.Context) {
defer fmt.Println("done doMain")
for {
select {
case <-ctx.Done():
return
default:
// do something
}
// do something
}
}
|
<filename>src/components/utils/ControlledAlert/index.tsx<gh_stars>10-100
export { default } from './ControlledAlert';
export type { ControlledAlertProps } from './ControlledAlert';
|
On the Analogy between Scientific Study of Technical Analysis and Ethnopharmacology The paper describes an analogy between two fields of study inspired by 'folk science' in distant scientific disciplines: financial economics and pharmacology. As the methodology of ethnopharmacology is much more developed than the methodology of scientific investigation of technical analysis, the former could serve as a kind of reference point for the latter. Conducting study of technical analysis according to strict scientific standards should contribute to the development of financial economics, especially important from the perspective of the current debate between neoclassical and behavioral paradigm. Thus, the paper tries to apply analogical reasoning with the aims of proposing a systematic research program and formulate hints regarding it. |
Fabrication and Characterization of Integrated Ultrahigh-Density Pt Nanowire Arrays within the AAO Template The parallel Pt nanowires with highly ordered array and the length more than a dozen micrometers were prepared by the direct current electro-deposition in porous anodic aluminum oxide (AAO) templates. The deposition was performed in a aqueous solution of the Pt (NO2)2(NH3)2 composite electrolyte. The images and structure of Pt nanowire arrays were obtained by field emission scanning electron microscope (FESEM) and transmission electron microscope (TEM), respectively. Selected area electron diffraction (SAED) are employed to study the crystalline morphology of Pt nanowire arrays. The relationship between the nanowires length and electro-deposition time was discussed. Their growth speed is about 0.5m/h. The TEM micrographs show that these nanowires have uniform diameter of approximate 55nm. SAED pattern reveals that the Pt nanowire has a polycrystalline structure. |
<filename>lib/badge/index.d.ts<gh_stars>0
declare const Badge: import("../utils").WithInstall<import("vue").DefineComponent<{
dot: BooleanConstructor;
max: (NumberConstructor | StringConstructor)[];
color: StringConstructor;
offset: import("vue").PropType<[string | number, string | number]>;
content: (NumberConstructor | StringConstructor)[];
showZero: {
type: BooleanConstructor;
default: true;
};
tag: {
type: import("vue").PropType<keyof HTMLElementTagNameMap>;
default: string;
};
}, () => JSX.Element | undefined, unknown, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, Record<string, any>, string, import("vue").VNodeProps & import("vue").AllowedComponentProps & import("@vue/runtime-core").ComponentCustomProps, Readonly<{
dot: boolean;
showZero: boolean;
tag: keyof HTMLElementTagNameMap;
} & {
max?: string | number | undefined;
color?: string | undefined;
offset?: [string | number, string | number] | undefined;
content?: string | number | undefined;
}>, {
dot: boolean;
showZero: boolean;
tag: keyof HTMLElementTagNameMap;
}>>;
export default Badge;
export { Badge };
|
n = input()
nums = map(int,raw_input().split())
import math
def taxi(n,nums):
a,b,c,d = map(nums.count, range(1,5))
b1 = int(math.ceil(b/2.0))
a1 = int(math.ceil(a/2.0))
if c-a>=0:
a = 0
b = b1
return b+c+d
elif c-a<0:
a = a-c
f = a%4
a = a/4
e = b%2
b = b/2
if e==0 and f == 0:
return a+b+c+d
elif 2*e+f<=4:
return a+b+c+d+1
else:
return a+b+c+d+2
print taxi(n,nums) |
/**
* Remapper to handle AWS re-packaging of annotations.
*
* @author graemerocher
*/
public class AwsRemapper implements PackageRenameRemapper {
@Override
public String getPackageName() {
return "com.amazonaws.lambda.thirdparty.com.fasterxml.jackson.annotation";
}
@Override
public String getTargetPackage() {
return "com.fasterxml.jackson.annotation";
}
@SuppressWarnings("unchecked")
@Override
public List<AnnotationValue<?>> remap(AnnotationValue<?> annotation, VisitorContext visitorContext) {
final List<AnnotationValue<?>> remapped = PackageRenameRemapper.super.remap(annotation, visitorContext);
return (List<AnnotationValue<?>>) remapped.stream().flatMap(av -> {
final List<AnnotationMapper<?>> annotationMappers =
JacksonAnnotationMapper.JACKSON_ANNOTATION_MAPPERS.get(av.getAnnotationName());
if (CollectionUtils.isNotEmpty(annotationMappers)) {
return annotationMappers
.stream().flatMap(annotationMapper -> ((AnnotationMapper) annotationMapper).map(annotation, visitorContext).stream());
}
return Stream.of(av);
}).collect(Collectors.toList());
}
} |
Mechanism of oxygen reactions at porous oxide electrodes. Part 2--Oxygen evolution at RuO2, IrO2 and Ir(x)Ru(1-x)O2 electrodes in aqueous acid and alkaline solution. The kinetics and mechanism of the oxygen evolution reaction at a series of RuO/IrO mixed oxides in aqueous acid and alkaline solution has been examined using a variety of electrochemical methods. Factors affecting the electrocatalytic activity have been elucidated and novel oxygen evolution mechanisms in terms of reactive oxyruthenium and oxyiridium surface groups are proposed. |
<filename>sudachipy/dictionarylib/doublearraylexicon.py
#import itertool
import struct
from . import lexicon
from .. import dartsclone
from . import wordidtable
from . import wordparameterlist
from . import wordinfolist
class DoubleArrayLexicon(lexicon.Lexicon):
def __init__(self, bytes_, offset):
self.trie = dartsclone.doublearray.DoubleArray()
bytes_.seek(offset)
self.size = int.from_bytes(bytes_.read(4), 'little')
offset += 4
bytes_.seek(offset)
array = struct.unpack_from("<{}I".format(self.size), bytes_, offset)
self.trie.set_array(array, self.size)
offset += self.trie.total_size()
self.word_id_table = wordidtable.WordIdTable(bytes_, offset)
offset += self.word_id_table.storage_size()
self.word_params = wordparameterlist.WordParameterList(bytes_, offset)
offset += self.word_params.storage_size()
self.word_infos = wordinfolist.WordInfoList(bytes_, offset, self.word_params.get_size())
def lookup(self, text, offset):
result = self.trie.common_prefix_search(text, offset)
l = []
for item in result:
word_ids = self.word_id_table.get(item[0])
length = item[1]
for word_id in word_ids:
l.append( (word_id, length) )
return l
def get_left_id(self, word_id):
return self.word_params.get_left_id(word_id)
def get_right_id(self, word_id):
return self.word_params.get_right_id(word_id)
def get_cost(self, word_id):
return self.word_params.get_cost(word_id)
def get_word_info(self, word_id):
return self.word_infos.get_word_info(word_id)
|
// This file is autogenerated. Changes will be overwritten.
#include "JIRO4TO6HL/moc_basicauthmiddleware.cpp"
#include "JIRO4TO6HL/moc_filesystemhandler.cpp"
#include "JIRO4TO6HL/moc_handler.cpp"
#include "JIRO4TO6HL/moc_localauthmiddleware.cpp"
#include "JIRO4TO6HL/moc_localfile.cpp"
#include "JIRO4TO6HL/moc_middleware.cpp"
#include "JIRO4TO6HL/moc_proxyhandler.cpp"
#include "JIRO4TO6HL/moc_qiodevicecopier.cpp"
#include "JIRO4TO6HL/moc_qobjecthandler.cpp"
#include "JIRO4TO6HL/moc_server.cpp"
#include "JIRO4TO6HL/moc_socket.cpp"
#include "UVLADIE3JM/moc_basicauthmiddleware_p.cpp"
#include "UVLADIE3JM/moc_filesystemhandler_p.cpp"
#include "UVLADIE3JM/moc_handler_p.cpp"
#include "UVLADIE3JM/moc_localauthmiddleware_p.cpp"
#include "UVLADIE3JM/moc_localfile_p.cpp"
#include "UVLADIE3JM/moc_proxyhandler_p.cpp"
#include "UVLADIE3JM/moc_proxysocket.cpp"
#include "UVLADIE3JM/moc_qiodevicecopier_p.cpp"
#include "UVLADIE3JM/moc_qobjecthandler_p.cpp"
#include "UVLADIE3JM/moc_server_p.cpp"
#include "UVLADIE3JM/moc_socket_p.cpp"
|
The Virginia House of Delegates has passed a bill requiring state public schools treat Election Day as a school holiday.
Election Day is the Superbowl for the news business. On My Take, Clinton Yates discusses why it’s his favorite work day.
On My Take, Clinton Yates questions the effectiveness of our election process.
If you’re looking to take the edge off at the end of a long Election Day, there are plenty of events to keep you busy in the area. From whiskey to wine, from trivia to puppies, there’s a little something for everyone Tuesday night.
Incumbent D.C. At-Large Councilmember Elissa Silverman and challenger Dionne Reeder are both minimizing the role of Mayor Muriel Bowser in the upcoming election.
Which party has the election edge in Congress?
Republicans and Democrats believe the president is helping to energize their respective bases going into Election Day. Both sides also say the recent fight over Brett Kavanaugh’s confirmation is motivating potential voters. Here’s the latest state of the race for both chambers. |
/**
* Updates customer in database and reloads all customers in memory.
*/
void updateCustomer(Customer customer) {
log.debug("updating customer {}", customer);
customerManager.updateCustomer(customer);
loadCustomersFromDb();
} |
<filename>src/app/budget/budget.component.ts
import { Component, OnInit } from '@angular/core';
import { Operation } from '../shared/Operation';
import { OperationService } from '../shared/operation.service';
import { OperationAjaxService } from '../shared/operation-ajax.service';
@Component({
selector: 'budget-template',
templateUrl: './budget.component.html',
// styleUrls: ['./app.component.css']
})
export class BudgetComponent implements OnInit {
solde = 1000;
sum = 0;
opes;
virements;
virmontant:number;
virdescription:string;
retmontant:number = this.retmontant* -1;
retdescription:string;
constructor(private operationService:OperationService, private operationAjaxService:OperationAjaxService){}
ngOnInit() {
this.operationAjaxService.getAllOpes().then((operations) => this.opes = <Object[]>operations);
}
ngDoCheck(){
this.solde = this.operationService.getSolde(this.solde, this.opes, this.sum);
}
addOpe(montant, description){
this.operationAjaxService.addOpe({
date: new Date,
montant: montant,
description: description
})
.then((operation) => this.opes.push(operation));;
}
removeOpe(index:number){
this.operationAjaxService.removeOpe({
id: index,
date: new Date,
montant: 0,
description: 'null'
})
.then(() => this.opes = this.opes.filter((operation) => operation.id !=index) );
}
getSolde(){
this.solde = this.operationService.getSolde(this.solde, this.opes, this.sum);
}
}
|
// Exchange converts an authorization code into a token or profile
// information. The code will be in the query string of the request sent to the
// RedirectURL, before calling this method ensure you check the state parameter
// matches the value used for AuthCodeURL.
//
// If Scopes is empty, "profile", or "profile email", the response will not
// contain an access token.
func (c *Config) Exchange(endpoints Endpoints, codeVerifier, code string) (*Response, error) {
client := http.DefaultClient
if c.Client != nil {
client = c.Client
}
form := url.Values{
"grant_type": {"authorization_code"},
"code": {code},
"client_id": {c.ClientID},
"redirect_uri": {c.RedirectURL},
"code_verifier": {codeVerifier},
}
endpoint := endpoints.Token
if c.isProfile() {
endpoint = endpoints.Authorization
}
req, err := http.NewRequest("POST", endpoint.String(), strings.NewReader(form.Encode()))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Accept", "application/json")
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
mediatype, _, _ := mime.ParseMediaType(resp.Header.Get("Content-Type"))
if resp.StatusCode != http.StatusOK || mediatype != "application/json" {
data, _ := ioutil.ReadAll(resp.Body)
return nil, &RequestError{
StatusCode: resp.StatusCode,
MediaType: mediatype,
Body: data,
}
}
var data struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
Scope string `json:"scope"`
Me string `json:"me"`
Profile map[string]interface{} `json:"profile"`
}
if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
return nil, err
}
newEndpoints, err := c.FindEndpoints(data.Me)
if err != nil {
return nil, err
}
if newEndpoints.Authorization.String() != endpoints.Authorization.String() {
return nil, ErrCannotClaim
}
return &Response{
AccessToken: data.AccessToken,
TokenType: data.TokenType,
Scopes: strings.Fields(data.Scope),
Me: data.Me,
Profile: data.Profile,
}, nil
} |
Transient gain dynamics in wide bandwidth discrete Raman amplifiers This paper has described measurements of transient gain effects caused by dropping channels in a wide bandwidth backward pumped discrete Raman amplifier. These measurements have shown that in a WDM amplifier the transients include two different features. There is a small but fast component due to signal-to-signal Raman crosstalk which can either increase or decrease the signal power depending on whether the surviving channels are at a longer or shorter wavelength than the dropped channels. There is also a larger, slower component due to pump readjustment which occurs on a time scale determined by the length of the amplifier. After changing the signal power at the input to the amplifier it requires up to three times the transit time of the amplifier for the new steady state to be reached. |
#!/usr/bin/env node
'use strict';
import { Logger, format, transports, createLogger } from 'winston';
import { isNullOrUndefined } from 'util';
import { LyticsClient } from './LyticsClient';
import chokidar = require('chokidar');
import program = require('commander');
const jsome = require('jsome');
const logger: Logger = createLogger({
format: format.combine(
format.colorize({ all: true }),
format.timestamp({
format: 'YYYY-MM-DD hh:mm:ss.SSS'
}),
format.printf(info => {
return `${info.timestamp}\t${info.level}\t${info.message}`;
})
),
transports: [new transports.Console()]
});
program
.description('Invokes the function, using the specified parameters.')
.name('function')
.usage('[options] <name> [param1 param2]')
.option('-k, --key <key>', 'Lytics API key (if not specified, environment variable LIOKEY is used)')
.parse(process.argv);
main();
async function main() {
//
//validate and initialize
if (program.args.length == 0) {
logger.error('Function name must be specified');
logger.error('Fatal error, aborting');
return;
}
const name = program.args[0];
const params = program.args.length > 1 ? program.args.slice(1) : [];
var apikey = program.key;
if (isNullOrUndefined(apikey)) {
apikey = process.env.LIOKEY;
if (isNullOrUndefined(apikey)) {
logger.error('API key must be specified as an option or in the environment variable LIOKEY');
logger.error('Fatal error, aborting');
return;
}
logger.info(`API key from environment variable LIOKEY: ${apikey}`);
}
else {
logger.info(`API key from options: ${apikey}`);
}
//
//
const client = new LyticsClient(apikey);
logger.info(`Calling ${name}(${params.join(', ')})`);
try {
var result = await client.testFunction(name, params);
logger.info(`Result: ${result}`);
}
catch(err) {
logger.error(err.message);
}
}
|
It is well known in the art that cracks and crevices occur in many fields of endeavor, whether intentionally or unintentionally. For example, cracks may appear in concrete surface construction such as sidewalks, driveways, and the like. Often times it is desired to fill in these cracks with a sealant, but many times there is debris which must be removed from the cracks before this can be done. The prior art devices for doing these are various sizes of crevice cleaning tools which are connected to a vacuum source, and held over the crack as best they can be. However, there are no means to guide the crack and crevice cleaning tools while they are doing the job, and many times it is not held in the optimum position.
The same problem can be found for example, in the laying of ceramic tile or other floor tiles. These are installed on mastic or cement and may have spaces in between if ceramic tile is involved. The grout is then put between the cracks. However, it is desired to clean out any foreign material before the grout is applied. The same problem occurs as described above. |
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector <int> vi;
int n, m;
class MyUnionFind{
public:
vi p, rank;
int n, counter;
MyUnionFind(int _n){
n = _n;
p.resize(n);
rank.assign(n, 1);
counter = n;
for(int i=0; i<n; i++)
p[i] = i;
}
int findSet(int i){
while(i != p[i]) p[i] = p[p[i]], i = p[i];
return i;
}
bool isSameSet(int i, int j){
return findSet(i) == findSet(j);
}
void unionSet(int i, int j){
if(!isSameSet(i, j)){
counter--;
int left = findSet(i);
int right = findSet(j);
if(rank[left] < rank[right]) {
p[left] = right;
}else {
p[right] = left;
if(rank[right] == rank[left]) rank[left]++;
}
}
}
};
int main(){
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
int cas = 1;
while(cin >> n >> m, n){
int u, v;
MyUnionFind satvik(n);
for(int i=0; i<m; i++){
cin >> u >> v; u--; v--;
satvik.unionSet(u, v);
}
cout << "Case " << cas++ << ": " << satvik.counter << endl;
}
return 0;
} |
MEMPHIS, Tenn. -- Memphis police are investigating two shootings that occurred Sunday morning, one of which left a person dead.
The first happened just before 2 a.m. Police say officers responded to a shooting call in the 400 block of E.H. Crump. The victims told police that they were leaving a parking lot when shots were fired at their car.
Police learned that there were four people involved in the shooting. While two of the victims were not hit at all, the other two were taken to the Regional Medical Center for treatment.
When the police arrived at the hospital, they learned that one of the victims had died from their injuries.
The second shooting happened just after 8:30 a.m. in the 2200 block of Eldridge. Police arrived on the scene and discovered a man who had been shot.
The victim told police someone shot him as he was going into Springdale Grocery. He said he then ran down the block and collapsed.
The man was taken to the Regional Medical Center in critical condition.
Police said the suspect approached officers on the scene and told them the victim tried to rob him, so he shot him in self defense.
Police are investigating, and no charged have been filed at this point.
WREG is working to find out more details about both shootings. |
<gh_stars>1-10
package tw_08_27;
/**
* @author: afuya
* @program: BiShiLianXi
* @date: 2021/8/27 3:54 下午
*/
class P {
void f(int i) {
System.out.println(i);
}
}
class Q extends P {
@Override
void f(int i) {
System.out.println(2 * i);
}
}
public class T_03 {
public static void main(String[] args) {
P x = new Q();
Q y = new Q();
P z = new Q();
x.f(1);
((P) y).f(1);
z.f(1);
}
}
|
package com.sachin.algos.puzzles.prefixsums;
public class PassingCars {
public int solution(int[] A) {
return singleTraversalSolution(A);
}
/**
* Simplest solution would be to count the number of pair of (0, 1) starting from the index where 0 is found.
* @param A input array
* @return passing cars
*/
private int simplestSolution(int[] A) {
int passingCars = 0;
for (int i=0;i<A.length;i++) {
if (A[i] == 0) {
passingCars += countPassingCars(A, i + 1);
}
}
return passingCars;
}
private int countPassingCars(int[] A, int startIndex) {
int localPassingCars = 0;
for (int i=startIndex;i<A.length;i++) {
if (A[i] == 1) {
localPassingCars++;
}
}
return localPassingCars;
}
// O(n) solution
public int singleTraversalSolution(int[] A) {
int oneCount = 0;
int passingCars = 0;
for (int i=A.length-1;i>=0;i--) {
if (A[i] == 1) {
oneCount++;
} else {
passingCars += oneCount;
if (passingCars > 1000000000) {
return -1;
}
}
}
return passingCars;
}
}
|
North Battleford
History
For thousands of years prior to European settlement, succeeding cultures of indigenous peoples lived in the area. The Battlefords area (including the present city of North Battleford and town of Battleford) was home to several historic indigenous groups, including the Algonquian-speaking Cree and Blackfeet as well as Siouan Assiniboine First Nation band governments, who contested for control of local resources.
Early European settlement began as a result of fur trading by French colonists in the late 18th century. The Canadians founded Fort Montaigne d'Aigle (Eagle Hills Fort) nine miles below the confluence of the Saskatchewan and Battle Rivers in 1778. A year later the fort was abandoned following conflict between traders and natives.
Permanent European settlement in the area centred around the town of Battleford, founded 1875 and located on the south side of the North Saskatchewan River. Battleford served as capital of the North-West Territories between 1876 and 1883.
In 1905 the construction of the Canadian Northern Railway main line to Edmonton placed the line on the north side of the North Saskatchewan River. North Battleford, built along the railway line, was incorporated as village in 1906, a town in 1907 and a city (with population 5000) in 1913.
The Assyrians were one of the first settlers of the area in and around North Battleford. The immigrant colony comprised 36 men and a few women from the town of Urmia in northwestern Persia. It was established in 1903 by Dr. Isaac Adams, an Assyrian Presbyterian missionary. In 1907, 40 more settlers arrived. Eventually, due to economic hardships, Dr. Isaac Adams and a few close relatives emigrated to Turlock, California. The descendants of the families who remained in North Battleford have names that are Assyrian in origin. Examples of Assyrian family names include Bakus, Essau, and Odishaw.
Population growth stagnated until the 1940s and then grew to approximately 10,000 by the 1960s.
The city has grown into an administrative centre and service hub for the economic, education, health and social needs of the region.
The Latter Rain Revival, a Christian movement, started here in 1946–48.
Historic sites
A number of heritage buildings are located within the city. The North Battleford Public Library was built in 1916 with a $15,000 grant from the Carnegie Foundation of New York. and the Canadian National Railways Station was built in 1956.
Crime rate
In 2018, Macleans ranked North Battleford as Canada's most dangerous place for overall crime. The prior year, Macleans published an article about this, Canada’s most dangerous place, North Battleford, is fighting for its future, discussing the safety initiatives planned by the community.
After the article was published, Mayor Ryan Bater said:
The reality is we require the provincial and federal levels of government to take notice of this and align their efforts with ours. This needs to be a partnership. This can’t be something the governments do in silos and we need to be working together. If we can do that, then sometime in the future we can see some great results.
City Manager Jim Puffalt added that the per person index may not be accurate because the population data does not consider the numerous transients, estimated at just over 14,000. In his view, the city has roughly 30,000 people at any time. "If you put our rates over 30,000 people we wouldn’t be number one [in the Macleans study]," he said.
Attractions
North Battleford is the home of one of four branches of the Saskatchewan Western Development Museum. This branch focuses on the agricultural history of Saskatchewan, including a pioneer village. A prominent feature is the former Saskatchewan Wheat Pool grain elevator No. 889 from Keatley, Saskatchewan. The grain elevator was moved to the museum grounds in 1983.
The city also has the Allen Sapp Gallery, featuring a noted Cree painter.
Sports and recreation
The North Battleford Civic Centre, a 2,500-seat multi-purpose arena, is home to the Battlefords North Stars ice hockey team of the Saskatchewan Junior Hockey League.
It is also home to the North Battleford Kinsmen Indoor Rodeo, held annually in April.
The North Battleford CUplex (Credit Union CUplex), which opened in 2013, includes the Dekker Centre for the Performing Arts, the Northland Power Curling Centre, the NationsWest Field House, and the Battlefords CO-OP Aquatic Centre.
Infrastructure
In 2001 a problem with the city's water system led to the infection of approximately 6280 people with cryptosporidiosis; a lawsuit for several million dollars in damages was filed in 2003. Between 5800 and 7100 people suffered from diarrheal illness, and 1907 cases of cryptosporidiosis were confirmed. Equipment failures at the city's antiquated water filtration plant following maintenance were found to have caused the outbreak. The provincial and municipal government offered compensation to victims after the lawsuit was approved in 2017.
The North Battleford Energy Centre, a natural gas-fired power station owned by Northland Power, has been operational since 2013.
Transportation
North Battleford is served by the North Battleford Airport, while the North Battleford/Hamlin Airport is no longer in use. The city also recently added a public transit system, in addition to the book-as-needed "Handi-bus" for people with disabilities.
Newspaper
BattlefordsNOW.com is an online local news site focusing on what's happening "right NOW" in the Battlefords and surrounding area.
The local newspaper is the Battlefords' News-Optimist. It is published weekly on Tuesdays and Thursdays, and has circulation in the surrounding area.
The Battlefords' Daily News is a widely read online publication of news and local events which is updated regularly.
Feed The Artist Magazine is a local non-profit periodical print and online publication that features the work of primarily local artists, photographers, and writers.
Radio
Three local radio stations serve the area; CJNB, CJCQ-FM ("Q98"), and CJHD-FM ("93.3 The Rock"). Some Saskatoon radio stations can also be received.
Television
The Battlefords are served by CFQC-TV-2 channel 6, an analogue repeater of CTV station CFQC-DT Saskatoon. |
package devliving.online.cvscanner;
import com.google.android.gms.vision.MultiProcessor;
import com.google.android.gms.vision.Tracker;
import online.devliving.mobilevisionpipeline.GraphicOverlay;
/**
* Created by user on 10/15/16.
*/
public class DocumentTrackerFactory implements MultiProcessor.Factory<Document> {
GraphicOverlay<DocumentGraphic> mOverlay;
DocumentTracker.DocumentDetectionListener mListener;
public DocumentTrackerFactory(GraphicOverlay<DocumentGraphic> mOverlay, DocumentTracker.DocumentDetectionListener mListener) {
this.mOverlay = mOverlay;
this.mListener = mListener;
}
@Override
public Tracker<Document> create(Document document) {
DocumentGraphic graphic = new DocumentGraphic(mOverlay, document);
return new DocumentTracker(mOverlay, graphic, mListener);
}
}
|
import { Component, OnInit } from '@angular/core';
import { DocumentService } from 'src/app/services/acquisition/document/document.service';
import { DocumentModel } from 'src/app/models/document/document';
@Component({
selector: 'app-document',
templateUrl: './document.component.html',
})
export class DocumentComponent implements OnInit {
cols: any[];
docs: DocumentModel[] = [];
constructor(
private docService: DocumentService,
) { }
ngOnInit() {
this.cols = [
{ field: 'docuCateName', header: 'Document Name', width: '23%' },
{ field: 'description', header: 'Description', width: '28%' },
{ field: 'isActive', header: 'Active', width: '12%' }
];
this.docService.refreshNeeded$.subscribe(() => {
this.getDocList();
});
this.getDocList();
}
private getDocList() {
this.docService.getDocList().subscribe((data) => {
this.docs = data['documentCategory'];
});
}
} |
On Wednesday, April 8, First Lady Michelle Obama said Americans need to do more to ensure Native Americans overcome the ravages of the trauma they have received in the past few centuries.
While acknowledging that many of the social ills present on today’s reservations, she asserts that the country as a whole participated in creating those ills and they must participate in the solution.
“Folks in Indian Country didn’t just wake up one day with addiction problems. Poverty and violence didn’t just randomly happen to this community. These issues are the result of a long history of systematic discrimination and abuse,” she told the audience.
In the speech, Michelle also described meeting with a group of young people from the Standing Rock Sioux Nation. Each of the Native youth faced their own set of obstacles: watching loved ones fall into drug abuse, struggling to balance school with homelessness, and even experiencing the loss of classmates to suicide.
Still, Michelle said, the kids stood persevered , working to create better lives for themselves, their loved ones, and their tribe.
Ms. Obama presented a picture of Native history often neglected by mainstream discourse–from forced relocation and abuse within Native boarding school programs to laws stripping Indians of their right to celebrate culture, heritage, and religion.
“Given this history, we shouldn’t be surprised at the challenges that kids in Indian Country are facing today. And we should never forget that we played a role in this. Make no mistake about it–we own this,” stated Ms. Obama.
Michelle’s call to action comes as yet another display of the Obama administration’s dedication to uplifting Indian Country and restoring what has been taken from them along the United States’ bloody warpath of oppression.
The Lakota People’s Law Project’s mission follows the same thread of preservation, touched on by the First Lady.
We are dedicated to conducting research and outreach in order to connect with Natives and facilitate the changes to build sovereignty and tribal capacity.
In particular, we are working towards autonomous, tribal-run family services that will prevent Native children from being removed from their families and tribes to be put in non-Native foster care as a form of revenue for the state of South Dakota.
We are deeply inspired by Michelle Obama’s words and motivated to continue our efforts in Native Country parallel to hers and the Obama Administration’s As Michelle so eloquently stated, “We all need to work together to invest deeply–and for the long-term–in these young people…These kids have so much promise–and we need to ensure that they have every tool, every opportunity they need to fulfill that promise.”
Advertisements |
Danette Olsen, a records officer with the Lane County Sheriff�s Office, says concealed handgun license applicants offer her a variety of reasons for wanting a permit allowing them to legally carry a hidden pistol in public.
�People will talk about getting one because of what�s happening in the world or in the nation, or what�s happening politically,� Olsen said. �For other people, it�s a rite of passage. And we see increases any time there�s a (gun-related) tragedy� such as a mass shooting.
Olsen and her colleagues were especially busy in 2016, when a record number of Lane County applicants � 3,670 � sought the licenses. That�s a 44 percent increase from 2015, when 2,550 people submitted new license applications.
The previous yearly high, according to statistics from the sheriff�s office, came in 2014, when 3,491 people applied.
More than 20,000 adults in the county now have permission to legally carry concealed weapons. The county has a total population of about 363,000.
Sheriff�s Sgt. Carrie Carver said that while Olsen and other workers in the office aren�t allowed to ask applicants about their interest in obtaining a license, historical records show that numbers tend to spike in presidential election years.
For example, 1,801 Lane County residents applied for concealed handgun licenses in 2011. That number jumped to 2,688 in 2012, the year in which President Obama won re-election.
Most applications are approved. Licenses are good for four years, after which they must be renewed.
Oregon issues concealed-carry permits to most anyone age 21 or older who completes a gun safety class, pays a $65 fee and passes a background check. You can�t get a license if you have a felony or some misdemeanor convictions, or have outstanding warrants against you. Former members of the military who were dishonorably discharged also are prohibited from obtaining a license.
Permit holders seeking renewals pay a $50 fee but are not required to retake safety courses.
In response to the increased demand for licenses, the sheriff�s office in 2013 launched a new, online appointment system that allows people to chose a date and time to submit their applications. Before that, it was common for people to have to wait hours at the office to apply for or renew permits.
The office still maintains drop-in hours on Wednesdays. This week, a middle-age man braved Eugene�s snow-coated streets to renew his license for a third time. The man, who declined to be identified for this article, said he keeps the permit �to ensure (his) Second Amendment rights are not infringed.�
In addition to new applications, sheriff�s officials processed 2,754 renewals in 2016 � another all-time high in Lane County.
Approximately one in 15 adults in the county now have a license to carry a concealed handgun, a rate in line with overall statewide numbers. Only Multnomah, Clackamas and Washington counties have more residents with licenses than does Lane County, where 20,467 people had permits as of Dec. 1, according to statistics kept by Oregon State Police.
The statistics show that generally, Oregon�s more rural counties tend to have a higher rate of concealed-carry license holders.
Time should tell if President-elect Donald Trump�s move to the White House will have any effect on concealed handgun licenses.
Unlike Obama, Trump � who has said he carries a concealed weapon of his own � opposes gun control measures and has discussed support for concealed-carry permit reciprocity among all 50 states. Oregon does not recognize permits issued in other states, meaning that out-of-state residents cannot legally carry concealed weapons here.
Kevin Starrett, executive director of gun rights group Oregon Firearms Federation, questions whether national elections are a major reason people seek concealed-carry licenses. He does, however, believe that mass shootings likely make some people feel they need to protect themselves.
�What it depends on are current events,� Starrett said, mentioning a December 2015 shooting that killed 14 people at a party in San Bernardino, Calif., and an incident in which 49 people were shot and killed last June at an Orlando, Fla., nightclub, as two incidents that raised the general public�s awareness of dangers.
Concealed-carry applications in San Bernardino County and Florida skyrocketed in the weeks after the mass shootings referenced by Starrett, according to media reports.
Follow Jack on Twitter @JackMoranRG . Email jack.moran@registerguard.com . |
/*
* Copyright (C) 2013 Team XBMC
* http://xbmc.org
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include "NetworkInfo.h"
#include "jutils/jutils-details.hpp"
using namespace jni;
int CJNINetworkInfo::getType() const
{
return call_method<jint>(m_object,
"getType", "()I");
}
int CJNINetworkInfo::getSubtype() const
{
return call_method<jint>(m_object,
"getSubtype", "()I");
}
std::string CJNINetworkInfo::getTypeName() const
{
return jcast<std::string>(call_method<jhstring>(m_object,
"getTypeName", "()Ljava/lang/String;"));
}
std::string CJNINetworkInfo::getSubtypeName() const
{
return jcast<std::string>(call_method<jhstring>(m_object,
"getTypeName", "()Ljava/lang/String;"));
}
bool CJNINetworkInfo::isConnectedOrConnecting() const
{
return call_method<jboolean>(m_object,
"isConnectedOrConnecting", "()Z");
}
bool CJNINetworkInfo::isConnected() const
{
return call_method<jboolean>(m_object,
"isConnected", "()Z");
}
bool CJNINetworkInfo::isAvailable() const
{
return call_method<jboolean>(m_object,
"isAvailable", "()Z");
}
bool CJNINetworkInfo::isFailover() const
{
return call_method<jboolean>(m_object,
"isFailover", "()Z");
}
bool CJNINetworkInfo::isRoaming() const
{
return call_method<jboolean>(m_object,
"isRoaming", "()Z");
}
CJNINetworkInfoState CJNINetworkInfo::getState() const
{
return call_method<jhobject>(m_object,
"getState", "()Landroid/net/NetworkInfo$State;");
}
CJNINetworkInfoDetailedState CJNINetworkInfo::getDetailedState() const
{
return call_method<jhobject>(m_object,
"getDetailedState", "()Landroid/net/NetworkInfo$DetailedState;");
}
std::string CJNINetworkInfo::getReason() const
{
return jcast<std::string>(call_method<jhstring>(m_object,
"getReason", "()Ljava/lang/String;"));
}
std::string CJNINetworkInfo::getExtraInfo() const
{
return jcast<std::string>(call_method<jhstring>(m_object,
"getExtraInfo", "()Ljava/lang/String;"));
}
std::string CJNINetworkInfo::toString() const
{
return jcast<std::string>(call_method<jhstring>(m_object,
"toString", "()Ljava/lang/String;"));
}
int CJNINetworkInfo::describeContents() const
{
return call_method<jint>(m_object,
"describeContents", "()I");
}
|
Development of deep learning models for predicting in-hospital mortality using an administrative claims database (Preprint) BACKGROUND Administrative claims databases have been used widely in studies because they have large sample sizes and are easily available. However, studies using administrative databases lack the severity of the disease, so a risk adjustment method needs to be developed. OBJECTIVE To develop and validate deep learningbased prediction models for in-hospital mortality of acute-care patients. METHODS The main model was developed using only administrative claims data (age, sex, diagnoses, and procedures on the day of admission). We also constructed disease-specific models for acute myocardial infarction, heart failure, stroke, or pneumonia using common severity indices for these diseases. Using the Japanese Diagnosis Procedure Combination data from July 2010 to March 2017, we identified 46,665,933 inpatients and divided them into derivation and validation cohorts in a ratio of 95:5. The main model was developed using a 9-layer deep neural network with four hidden dense layers that had 1000 nodes and were fully connected to adjacent layers. We evaluated model discrimination ability by an area under the receiver operating characteristics curve and calibration ability by calibration plot. RESULTS Among the eligible patients, 2,005,035 (4.3%) died. Discrimination and calibration of the models were satisfactory. The AUC of the main model in the validation cohort was 0.954 (95% confidential interval 0.95370.9547). The main model had higher discrimination ability than the disease-specific models. CONCLUSIONS Our deep learning-based model using diagnoses and procedures produced valid predictions of in-hospital mortality. CLINICALTRIAL |
Light Confinement in Resonators Based on Bloch Surface Waves Recently, it has been shown that ring resonators can be obtained by etching multilayers supporting Bloch Surface Waves. The design of this and other types of optical resonators based on Bloch surface waves is particularly challenging due to the hybrid light confinement mechanism that characterizes these structures. Yet, these systems are promising in all those situations that require light to be confined near the surface of a device, e.g. optical surface sensors and quantum dots. Here we investigate the design of a nanobeam cavity on a multilayer supporting a Bloch surface wave and discuss the problems related to light confinement in this BSW-based optical resonator. |
#ifndef NULLINPUTLISTENER_H_
#define NULLINPUTLISTENER_H_
#include "IInputListener.h"
class NullInputListener:public InputListener{
public:
virtual ~NullInputListener(){};
virtual Instruction getInput(){
return InputListener::EXIST;
};
};
#endif /* NULLINPUTLISTENER_H_ */
|
def pop_checkpoint(self, checkpoint_id):
idx = self.checkpoints.index(checkpoint_id)
checkpoint_ids = self.checkpoints[idx:]
self.checkpoints = self.checkpoints[:idx]
revert_data = merge(*(
self.journal_data.pop(c_id)
for c_id
in reversed(checkpoint_ids)
))
return dict(revert_data.items()) |
. Serum and tissue copper, zinc and selenium levels were measured in patients with gastric carcinoma. The mean level of serum copper in patients with gastric carcinoma (42 cases) was 950 +/- 130 ug/L, which was higher than 800 +/- 70 ug/L of the control (30 cases, P less than 0.05). The serum selenium level in patients with gastric carcinoma was lower than that in the control (63 +/- 15 ug/L vs 85 +/- 8 ug/L, P less than 0.05). No significant difference in serum zinc level was found between the patient and control groups. In cancer tissues, the mean concentration of copper was 13.5 +/- 2.6 micrograms/g dry weight, which was much higher than 7.1 +/- 1.6 micrograms/g dry weight in the intact gastric mucosa (P less than 0.01). The activity of superoxide dismutase (SOD) in cancer tissue was 95 +/- 10 u/mg-protein, which was lower than 124 +/- 12 u/mg-protein in the intact gastric mucosa (P less than 0.05). The above changes may facilitate production of free radicals, tissue damage and carcinogenesis. |
<gh_stars>1-10
/**
* This file is part of Aion-Lightning <aion-lightning.org>.
*
* Aion-Lightning is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Aion-Lightning is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License
* along with Aion-Lightning.
* If not, see <http://www.gnu.org/licenses/>.
*/
package com.aionemu.gameserver.network.aion;
import com.aionemu.commons.network.packet.BaseServerPacket;
import com.aionemu.gameserver.configs.administration.DeveloperConfig;
import com.aionemu.gameserver.model.gameobjects.player.Player;
import com.aionemu.gameserver.network.Crypt;
import com.aionemu.gameserver.network.aion.AionConnection.State;
import com.aionemu.gameserver.utils.PacketSendUtility;
import com.aionemu.gameserver.utils.Util;
import java.nio.ByteBuffer;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
/**
* Base class for every GS -> Aion Server Packet.
*
* @author -Nemesiss-
* @author GiGatR00n
*/
public abstract class AionServerPacket extends BaseServerPacket {
//private static final Logger log = LoggerFactory.getLogger(AionServerPacket.class);
/**
* Constructs new server packet
*/
protected AionServerPacket() {
super();
setOpcode(ServerPacketsOpcodes.getOpcode(getClass()));
}
/**
* Write packet opcodec and two additional bytes
*
* @param buf
* @param value
*/
private final void writeOP(int value) {
/**
* obfuscate packet id
*/
int op = Crypt.encodeOpcodec(value);
buf.putShort((short) (op));
/**
* put static server packet code
*/
buf.put(Crypt.staticServerPacketCode);
/**
* for checksum?
*/
buf.putShort((short) (~op));
}
public final void write(AionConnection con) {
write(con, buf);
}
/**
* Write data that this packet represents to given byte buffer.
*
* @param con
* @param buf
*/
protected void writeImpl(AionConnection con) {
}
public final ByteBuffer getBuf() {
return this.buf;
}
private boolean isPacketFilterd(String filterlist, String PacketName) {
//If FilterList was empty, all packets will be shown.
if (filterlist == null || filterlist.equalsIgnoreCase("*")) return true;
String[] Parts = null;
Parts = filterlist.trim().split(",");
for (String p: Parts) {
if (p.trim().equalsIgnoreCase(PacketName)) {
return true;
}
}
return false;
}
private ByteBuffer getByteBuffer(ByteBuffer buf, int count) {
count = (count <= buf.capacity()) ? count : buf.capacity();
ByteBuffer tmpBuffer = buf.asReadOnlyBuffer();
tmpBuffer.position(5+2);
tmpBuffer.limit(count);
// Create an empty ByteBuffer with a Requested Capacity.
ByteBuffer PckBuffer = ByteBuffer.allocate(count);
try {
do
{
PckBuffer.put(tmpBuffer.get());
}
while (tmpBuffer.remaining() > 0);
} catch (Exception e) {
//e.printStackTrace();
}
PckBuffer.position(0);
return PckBuffer;
}
/**
* Write and encrypt this packet data for given connection, to given buffer.
*
* @param con
* @param buf
*/
public final void write(AionConnection con, ByteBuffer buffer) {
if (con.getState().equals(AionConnection.State.IN_GAME) && con.getActivePlayer().getPlayerAccount().getMembership() == 10) {
if (!this.getPacketName().equals("SM_MESSAGE")) {
PacketSendUtility.sendMessage(con.getActivePlayer(), "0x" + Integer.toHexString(this.getOpcode()).toUpperCase() + " : " + this.getPacketName());
}
}
this.setBuf(buffer);
buf.putShort((short) 0);
writeOP(getOpcode());
writeImpl(con);
buf.flip();
/**
* Display Packets Name + Hex-Bytes in Chat Window
*/
int BufCurrentPos = buf.position();
buf.position(5+2);
Player player = con.getActivePlayer();
if (con.getState().equals(State.IN_GAME) && player != null && this.getOpcode() != 24 && player.getAccessLevel() >= DeveloperConfig.SHOW_PACKETS_INCHAT_ACCESSLEVEL) {
if (isPacketFilterd(DeveloperConfig.FILTERED_PACKETS_INCHAT, this.getPacketName())) {
if (DeveloperConfig.SHOW_PACKET_BYTES_INCHAT) {
String PckName = String.format("0x%04X : %s", this.getOpcode(), this.getPacketName());
PacketSendUtility.sendMessage(player, "********************************************");
PacketSendUtility.sendMessage(player, PckName);
PacketSendUtility.sendMessage(player, Util.toHexStream(getByteBuffer(buf, DeveloperConfig.TOTAL_PACKET_BYTES_INCHAT)));
} else if (DeveloperConfig.SHOW_PACKET_NAMES_INCHAT) {
String PckName = String.format("0x%04X : %s", this.getOpcode(), this.getPacketName());
PacketSendUtility.sendMessage(player, PckName);
}
}
}
buf.position(BufCurrentPos);
buf.putShort((short) buf.limit());
ByteBuffer b = buf.slice();
buf.position(0);
con.encrypt(b);
}
/**
* Write String to buffer
*
* @param text
* @param size
*/
protected final void writeS(String text, int size) {
if (text == null) {
buf.put(new byte[size]);
} else {
final int len = text.length();
for (int i = 0; i < len; i++) {
buf.putChar(text.charAt(i));
}
buf.put(new byte[size - (len * 2)]);
}
}
protected void writeNameId(int nameId) {
writeH(0x24);
writeD(nameId);
writeH(0x00);
}
}
|
<filename>springboot-cassandra-autoconfiguration/src/main/java/com/springboot/controller/Consumer.java<gh_stars>0
package com.springboot.controller;
import org.springframework.lang.NonNull;
public class Consumer {
@NonNull
private String customerGuid;
@NonNull
private String consumerGuid;
private String firstName;
private String lastName;
private String emailId;
public String getConsumerGuid() {
return consumerGuid;
}
public void setConsumerGuid(String consumerGuid) {
this.consumerGuid = consumerGuid;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getCustomerGuid() {
return customerGuid;
}
public void setCustomerGuid(String customerGuid) {
this.customerGuid = customerGuid;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
}
|
Criteria and guidelines for reforming the U.S. health care system. It would be tempting to suggest that the U.S. health care system is now in disarray were it not for the fact that it has never really been otherwise. There is increasing anger and frustration among employers, consumers, uninsured people, payers, and providers, all of whom are struggling with what are perceived to be competing demands to contain costs while trying to improve productivity, increase quality, and expand access to services. Clearly, our health care system needs more comprehensive strategies to address the multiple needs of different groups. We do not lack for new ideas or alternative models. In the... |
Charles wore the red and white suit, which didn't fit his thin frame. The old man had told him that it would, with time, but Charles had always been as skinny as a stick. Still, if he grew fat in the coming weeks, it would be far down the list of miraculous things that needed solving.
"I'm an industrial engineer," he'd said, when the old man had come to him. "I don't even have children."
"Neither do I, Charles," said the old man with a touch of sadness in his voice. "But I have seen how you look at them, and you appreciate children all the same."
There were a thousand objections that he should have given instead, when the old man had told him that the mantle of Santa Claus was being passed on. He should have asked how the man had gotten into his studio apartment, which had three locks on the door, or asked how the man had known his name, and he certainly should have objected to the notion that Santa Claus existed at all. Something stayed his tongue though, and it wasn't just surprise.
Now the old man was gone, and Charles had been declared the new Santa Claus before all of the elves and reindeer of the north pole. He'd been given no instructions from the old man, nothing other than an offer, which he'd accepted without hesitation. Charles had grown up in tenement housing, and his mother had been largely absent from his life. He'd nearly drowned himself in escapist books, where poor, unhappy boys got special powers or discovered secret worlds, and the expectation that something like that would happen had never really left him. Still, he had never expected this.
"Come this way," said Kelvin, a head elf who wore special golden epaulettes atop his red and green frippery. He seemed, more or less, the person in charge. Charles couldn't pretend to understand the first thing about fashion among the elves, but they dressed almost exclusively in red, green, white, gold, and silver. Even after half an hour it was starting to grate on his nerves. Kelvin had pointed ears and stood a bit taller than the others, coming up to just above Charles' navel. He had a serious and somewhat dour expression.
"This," he declared as he opened one of the many doors of the North Pole, "Is the List Room."
Before them was more of a stadium than a proper room, with tens of thousands of wooden desks arrayed in concentric circles with steps leading down. Two long pieces of paper hung down from the high ceiling in the center of the room, and when Charles looked up he could see that they were even longer than they appeared, rolling around metal bars until they were nearly a meter thick. From time to time, elves jogged down the steps to write at the very bottom of these papers.
"This is where we determine who is naughty and who is nice," said Kelvin. He stepped forward to the closest desk and placed his hand on the shoulder of the elf who was sitting there. "Paeter, please take a break while I show Santa the ropes." The elf looked between the two of them with shock, and simply nodded once before scurrying away.
"Now then," said Kelvin, "This is the viewing console, through which we watch the children and determine whether they are naughty or nice." The desk was angled, like an architect's desk, and the viewer took up the majority of it. The picture was clearer than any television that Charles had ever seen, and when he moved his head he realized that it produced a three-dimensional effect. It was a perfect window into the world that it was displaying, an autumn evening in New York City. A child of about seven walked down the sidewalk with a backpack on.
"Of course," said Kelvin, "You won't actually be doing any of the monitoring - that might have been feasible in the old days, but now it's more or less left to us. We have three people reviewing every child, and if there's no consensus -"
"I'm sorry, excuse me," said Charles, "But are you telling me that the elves have the ability to monitor every child in the world in real-time?"
Kelvin gave a merry laugh that sounded like tinkling bells, quite at odds with his normal demeanor. "Oh, my no. No, there are, at this time, roughly one and a quarter billion children in the world. To make the list in real-time with the proper oversights would require four billion elves, and that's assuming that we only slept when the children did. Of course, different children sleep at different times, so we'd have to segregate the elves into different populations to take different shifts, and of course that's just considering the elves that are working on making the list and checking it twice. It's under your authority to switch the systems that we use, but I have to say that I'm not terribly enthused about that idea, and I don't imagine that the others are either. But as I say, it's up to you." His sourness returned to him as he considered the logistics.
Charles frowned. "So then how do you make the list?"
"Simple," said Kelvin. "We check the children asynchronously." He pressed a mechanical lever just under the viewer, and the image of the child sped up considerably, until he was home in the space of a breath, playing videogames, eating supper, playing more videogames, and finally tossing and turning in his sleep. Kelvin moved a small orb under the viewer to control the angle that was shown on the screen, and after some quick, wordless demonstration of its abilities, he pushed another lever to pause the viewer entirely.
"So," said Charles, "We don't have real-time viewing of a child's actions, we have a full record of everything that they'd done?" He figured that it would be better to take all of the impossible things in stride and then freak out about them all at once later in the day to save time.
"Not just that," said Kelvin. He pressed another lever, and the viewer stopped focusing on the child and began to fly through walls, briefly showing insulation and structural supports. Eventually Kelvin seemed to find what he was looking for, and settled in on a woman putting on her makeup. "The viewer can look at adults to get some context about the child's life. This, for example, is … ah, Ms. Kerrimore, who teaches second grade to Luke Johnson, the boy we were just watching. Sometimes there are questions that arise which require more information."
Charles stared at the viewer with a frown. A giddy excitement was growing in his chest, and he worried that he would stand there with his jaw on the floor for hours if he dared to let it out. "So you have panopticon surveillance of both the past and the present anywhere on planet Earth," he said carefully.
"And the future," said Kelvin with a nod. "Everything from 00:01 UTC on December 25 of last year to 23:59 UTC on December 24th of this year. And I know what you're going to ask, but we still haven't been able to eliminate the one minute gap."
"That was not at even remotely where my concerns lie," said Charles. "We could see anything? Even things not directly related to whether children are naughty or nice?"
Kelvin turned to look him in the eye and furrowed his brow. "I suppose that's technically possible, but we're really not set up for it. The viewer can, they were built like that, but all the elves are trained to watch children. If you'd like, I can have a viewer set up in your rooms."
"But I mean - wait, I just thought of something, how does doing it this way really reduce your workload? You still have a billion kids to watch," said Charles. "You'd still need at least a significant fraction of that many elves to look through all of this footage, and if you're checking twice you'd need quite a bit more."
"Why would we?" asked Kelvin. "Oh, I think I see the misunderstanding here, the List Room and much of the North Pole itself is outside of time. We can take as many subjective years as we need to complete the list."
"And … how many years do you take every year?" asked Charles.
"It depends on the year," said Kelvin. "Going by current projections, this year it will take roughly fifty thousand years."
Charles dropped his hands to his side and stepped back. He looked out at the row upon row of desks, tens of thousands of elves looking at the lives of children. That alone boggled the mind, but to think that they'd be at it for longer than recorded history was nearly unfathomable.
"How long do elves even live?" asked Charles.
"As long as people, more or less; sixty years," replied Kelvin.
"So these elves won't ever see the fruits of their labors?" asked Charles. "They won't see the Christmas that they're preparing for?"
"Such is the life of an elf," replied Kelvin with a nod. "We do our work knowing that we're making Christmas morning special for the young children, and if we never get to see the Christmas we prepare for, we accept that." He stood up from the viewer. "Now, come along, there are two more stops on the tour before we show you to your rooms."
They walked together down the hallways of the North Pole, and Charles began to truly notice things for the first time. The doors were all sized for a normal person, though he was the only one in sight. Each door had two knobs, a large one and a small one. The fact that the entire place was sized for both of them seemed vaguely absurd.
"Sorry to bring this up so early," said Kelvin, "But the last Santa allowed us a small celebration when the last child had been checked twice. Some of the other elves were wondering if that tradition might be extended?"
"You're … you want a party?" asked Charles.
"If it's not too much trouble," said Kelvin. "We toil at the list for a great while you see, and -"
"Consider it done," said Charles.
"Thank you, Santa," said Kelvin.
They turned left down a festively decorated corridor, and Kelvin opened a wide set of double doors, which led out onto an immense workshop. Kelvin had halfway expected a factory, but instead it was simply row after row of wooden benches, and elves working with a handful of simple tools. It reminded him of nothing more than a sweatshop. Kelvin was used to factory floors; factories were what he did for a living. He'd been part of the team that had worked out the logistics for the most recent production run of Malibu Barbie.
"I have some questions," said Charles.
"Oh?" asked Kelvin. "Didn't you want to see the process a bit first."
"Before that," said Charles firmly. "What process is in place to decide what children get?"
"The Mail Room comes later in the tour," said Kelvin with a trace of irritation. "But we get letters from the children, the elves figure out what's reasonable and within our capacity to produce, and then we build them. Those who don't send us letters - which is the majority of children - have a gift selected for them by the elves which is both age, gender, and culture appropriate."
"All this is made by hand?" asked Charles.
Kelvin nodded. "We take dough from the extruder and shape it." He walked over to a close workbench, and again asked an elf to leave his station. "Here we're making a gift for Li Xiu Yang." As he said the name, his voice dipped into a flawless Chinese pronunciation. "She didn't send us a letter, and so she will be getting a small plastic frog."
The workbench was solid, with a skirt that dropped all the way to the floor. As Charles moved around to look, he could see a thick glass pipe running up the inside of it, which descended into the floor. Where it touched the top of the workbench, there was a metal aperture with an iris opening. On the workbench itself were a variety of tools, hammers, pliers, and a wide variety of others. Kelvin pressed down on one of the pedals near his stool, and the pipe extruded out a grey substance through the metal opening, which had dilated out to let it through. Kelvin took the ball of this stuff began to shape it with his hands, until it resembled a quite detailed frog. It looked something like a computer rendering before the lighting, bump-mapping, and textures had been applied. Then, with a snap of his fingers it took on its proper form and color. Kelvin handed it to Charles, who took it delicately between his thin fingers. It felt and looked exactly like plastic. As Charles turned it around, he could even see a line of flash from where an injection machine would have left extra plastic.
"How?" asked Charles.
"Magic," said Kelvin with a shrug. When it became clear this wouldn't be enough of an answer, he added, "The dough can be shaped into anything, and once we have completed the assembly of the thing, we merely have to snap our fingers to change the materials into the proper form."
"Then … then why in the world does this small plastic frog have flash from injection moulding?"
"Authenticity," replied Kelvin. "If we were to make our plastics perfectly, people might get suspicious. We're well familiar with the processes that the factories use, and we copy them as exactly as possible." He took the plastic frog back, and with a flourish pulled a wrapping paper and ribbon from a compartment in the workshop table. The frog was wrapped in less than three seconds, and the elf wrote out a long list of identifying information on a label, which he tied to the present. He pressed another lever beneath the table, and the metal iris opened back up. Kelvin dropped the present down it, and it disappeared with a pneumatic woosh. "That's one done," he said with satisfaction. He stood from the desk and looked at Charles expectantly.
"I'm sorry," said Charles, "But I'm just starting to catch up to things, this was all thrust on me quite suddenly."
"Yes," said Kelvin, "I understand."
"So on Christmas Day, this Li Xiu will find a present under her Christmas tree?" he asked.
"According to her dossier, she doesn't actually believe in Christmas, more's the shame," said Kelvin. "We'll instead arrange for her to find it under her pillow or in with her other toys. The wrapping will have to come off, of course, and we'll strip the present of its label since she doesn't read English anyway, but she'll get her gift all the same. Delivered by you, of course."
"I see," said Charles, though he didn't really see at all.
"Come along then, there's much more of the North Pole to visit," said the elf.
They walked down the hallways, and a thought occurred to Charles. "Why do you need me at all?" he asked. "You obviously have all these fantastic powers, why don't the elves deliver the gifts without me needing to get in a sleigh?"
"There was an incident," replied Kelvin. "We did spread Christmas cheer without a Santa, for almost five hundred years. And then … then were a series of failures. A child was put on the nice list, even though he was very naughty. We were tasked with making a present for him, and made something that we shouldn't have, due to a failure in the workshop. And we delivered it, because the elves in charge of delivery didn't have any knowledge of what the present actually was. We unanimously decided afterwards that we needed to have a Santa again, to keep us in check."
"What was the gift that you gave the boy?" asked Charles. "What could have been so bad?"
"We gave him a rat," said Kelvin. "A diseased rat."
A chill ran through Charles' veins. "When?" he asked.
"1348," replied Kelvin. "Of course, we realized the mistake slowly over the course of the year, but there wasn't anything that we could do about it. We simply resolved to do better in the future, and having a Santa is part of that."
"So I'm … a figurehead?" asked Charles. "A moral compass?"
"If that's how you'd prefer to think of things," said Kelvin. "You have authority over us, because we cannot trust ourselves to do things properly."
The rest of the tour consisted of the Mail Room, the stables that held the reindeer and the sled, and a variety of other things - none of which came close to their production and surveillance abilities. The elves had a control of space and time itself, and they wanted to show him beasts of burden; there was something very wrong with the place.
"These are your rooms," said Kelvin at the end of the tour. "There's a bedroom, bathroom, living room, dining room, access to cable television and the internet, and a small kitchen, though we will be more than happy to cook you whatever you would like if only you say the word. Ring this bell, and an elf will come to assist you in any way you might desire. We've added another room onto your suite which contains a viewer, as you'd mentioned you'd like to have one - I've included not only the recording for this year, but the archives of years past as well." He bowed slightly and left Charles alone, to look around his room. The furnishings were opulent, if slightly gaudy, and the suite was three times the size his apartment had been. As he looked around, he could see that many of his belongings had been transferred over - the guitar he'd told himself that he would learn to play some day, a painting his ex-girlfriend had made him that he'd never had the heart to throw away, and a dozen other reminders of the real world - a world that had made sense. |
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
type Employee struct {
Name string `json:"name" binding:"required"`
Value string `json:"value" binding:"required"`
Salary float64 `json:"salary,omitempty" binding:"required"`
}
type Role string
const RoleAdmin Role = "ROLE_ADMIN"
const RoleHR Role = "ROLE_HR"
const RoleUser Role = "ROLE_EMPLOYEE"
type User struct {
Name string
Role Role
}
var db map[string]Employee
var userDb map[string]User
func setupRouter() *gin.Engine {
r := gin.Default()
db = map[string]Employee{}
userDb = map[string]User{
"admin": {
Name: "Admin",
Role: RoleAdmin,
},
"hr": {
Name: "<NAME>",
Role: RoleHR,
},
"user": {
Name: "<NAME>",
Role: RoleUser,
},
}
authorized := r.Group("/", gin.BasicAuth(gin.Accounts{
"admin": "admin",
"hr": "hr",
"user": "user",
}))
// Get employee
authorized.GET("/employee/:name", func(c *gin.Context) {
user := c.MustGet(gin.AuthUserKey).(string)
userFromDb, ok := userDb[user]
employee := c.Params.ByName("name")
value, ok := db[employee]
if ok {
if userFromDb.Role != RoleAdmin && userFromDb.Role != RoleHR {
value.Salary = -1
}
c.JSON(http.StatusOK, value)
} else {
c.JSON(http.StatusNotFound, gin.H{"status": "not found"})
}
})
authorized.POST("admin", func(c *gin.Context) {
user := c.MustGet(gin.AuthUserKey).(string)
userFromDb := userDb[user]
json := Employee{}
if userFromDb.Role != RoleAdmin {
c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
}
if c.Bind(&json) == nil {
db[json.Name] = json
c.JSON(http.StatusOK, gin.H{"status": "ok"})
}
})
return r
}
func main() {
r := setupRouter()
r.Run(":8080")
} |
Scintillation reduction using multiple transmitters Uplink scintillation is a serious issue for laser communication between a satellite and the ground. Fluctuations on the uplinked beacon and communications laser can be minimized by transmitting multiple independent lasers from separate apertures which then sum incoherently at the satellite. The objective of the experiment described here was to determine the number and spacing required for separate transmitters to reduce fluctuations in the received power due to atmospheric scintillation to acceptable levels. Received power vs. time data were collected for horizontal laser links established between a laser transmitting platform and a receive telescope assembly separated by distances of 1.2 and 10.4 km to mimic the expected atmospheric effects of an uplink slant path to a satellite. Reduction in signal fluctuations was observed as the number of laser transmitters was increased from 1 to 16. A ground terminal design with 16 lasers on an 18 inch diameter circle with a 7 dB fade margin should be adequate to compensate form sot scintillation fades, while the remaining deep fades may be corrected by using forward error correction techniques. |
// Size - calculated size of box
func (b *Dec3Box) Size() uint64 {
size := boxHeaderSize + 2
for _, es := range b.EC3Subs {
size += 3
if es.NumDepSub > 0 {
size += 1
}
}
size += len(b.Reserved)
return uint64(size)
} |
# --- imports
# pygame imports
import pygame
import pygame.sprite
# local imports
from ..borders import ColoredBorder, Border
from ..designs import getDefaultDesign, getFallbackDesign
# set defaults
getFallbackDesign().border = ColoredBorder(2, 2, (50, 50, 50))
"""Border to be used by default."""
getFallbackDesign().foreground = (255, 255, 255)
"""Color to be used by default for the foreground of a widget."""
getFallbackDesign().background = (100, 100, 100)
"""Color to be used by default for the background of a widget."""
getFallbackDesign().disabeled_overlay = (200, 200, 200, 200)
"""Color used by default to overlay when a widget is disabled."""
getFallbackDesign().scaling_function = pygame.transform.smoothscale
"""Function used to scale background images to widget-size."""
def _getScalingFunctionForSmoothness(self, smooth):
"""
Return an appropiate scaling-function for the smoothness given.
This is an internal function.
Args:
smooth: A boolean indicating whether the returned function should scale smoothly or not.
Returns:
A corresponding scaling-function which transforms a given surface (see pygame.transform.scale).
"""
if smooth:
return pygame.transform.smoothscale
return pygame.transform.scale
class Widget(pygame.sprite.DirtySprite):
"""
Underlying class for interactive GUI-objects with pygame;
intended for use together with pygame.sprite.LayeredDirty.
Note: If you change any widget's visual characteristics (e.g. its background-color)
via its methods or properties (e.g. setBackground()),
its appearance will not change until it is redrawn.
You can force this by calling widget.update() after you modified its characteristics.
"""
def __init__(self, x, y, width, height):
"""
Initialisation of a basic Widget.
The units for the following lengths are pixel.
Args:
x: An integer specifing the x-coordinate of the widget.
This is the horizontal distance from the left reference point.
y: An integer specifing the y-coordinate of the widget.
This is the vertical distance from the top reference point.
width: An integer specifing the width of the widget.
height: An integer specifing the height of the widget.
"""
super(Widget, self).__init__()
self._focused = False
self._active = True
self.image = pygame.Surface((width, height), pygame.SRCALPHA, 32)
self.bounds = self.image.get_rect().move(x, y)
self.border = getDefaultDesign().border
self.foreground = getDefaultDesign().foreground
self.background = getDefaultDesign().background
self.background_image = None
self.disabeled_overlay = getDefaultDesign().disabeled_overlay
self.scaling_function = getDefaultDesign().scaling_function
self._updateRect()
def markDirty(self, overwriteDirtyForever=False):
"""
Mark the widget as dirty and therefore to be redrawn in the next draw-cycle.
Args:
overwriteDirtyForever: A boolean indicating whether this should overwrite the dirty-forever state.
The default is False meaning that a widget which is marked as dirty-forever
will not be clean after the next cycle when this method was called on it.
"""
if not self.isDirtyForever() or overwriteDirtyForever:
self.dirty = 1
def markDirtyForever(self):
"""
Mark the widget as constantly dirty and therefore to be redrawn periodically with every draw-cycle.
"""
self.dirty = 2
def markClean(self):
"""
Mark the widget as clean and therefore not to be redrawn in the next draw-cycle.
"""
self.dirty = 0
def isDirty(self):
"""
Return if the widget is dirty and will be redrawn in the next draw-cycle.
"""
return self.dirty >= 1
def isDirtyForever(self):
"""
Return if the widget is constantly dirty and will be redrawn periodically with every draw-cycle.
"""
return self.dirty >= 2
def setVisible(self, visible):
"""
Set the widget's visibility.
Invisible widgets will not be drawn and are inactive.
Args:
visible: A boolean indicating whether the widget should be visible.
Returns:
Itsself (the widget) for convenience.
"""
visible = bool(visible)
if self.visible != visible:
self.visible = visible
self.setActive(visible)
return self
def isVisible(self):
"""
Return whether the widget is visible.
Invisible widgets will not be drawn and are inactive.
Returns:
A boolean indicating whether the widget is declared visible.
"""
return self.visible
def setFocused(self, focused):
"""
Set whether the widget is focused.
A widget will be focused automatically if it is clicked on.
Although the default implementation does not process this information,
subclasses may use this information to determine if the user-interaction
was meant to be processed by them or not.
Args:
visible: A boolean indicating whether the widget should be focused.
Returns:
Itsself (the widget) for convenience.
"""
focused = bool(focused)
if self.focused != focused:
self._focused = focused
self.markDirty()
return self
def isFocused(self):
"""
Return whether the widget is focused.
A widget will be focused automatically if it is clicked on.
Returns:
A boolean indicating whether the widget is declared focused.
"""
return self._focused
def setActive(self, active):
"""
Set the widget as active and therefore as interactive.
An inactive widget should not be interactable and will have an overlay painted on.
Args:
active: A boolean indicating whether the widget should be active
Returns:
Itsself (the widget) for convenience.
"""
active = bool(active)
if self.active != active:
self._active = active
self.markDirty()
self.update()
return self
def isActive(self):
"""
Return whether the widget is active.
An inactive widget should not be interactable and will have an overlay painted on.
Returns:
A boolean indicating whether the widget is active.
"""
return self._active
def setBounds(self, rect):
"""
Set the widget's base bounds according to a pygame.Rect.
This can be used to change the position of the widget or its size.
Args:
rect: A pygame.Rect with the according position and size.
Returns:
Itsself (the widget) for convenience.
"""
self._bounds = rect
self.markDirty()
return self
def getBounds(self):
"""
Return the widget's base bounds (position and size).
Returns:
A pygame.Rect with the bounds of the widget.
"""
return self._bounds
def getActualBounds(self):
"""
Return the widget's actual bounds (position and size).
Returns:
A pygame.Rect with the bounds of the widget.
"""
return self._rect
def setBorder(self, border):
"""
Set the widget's border.
Args:
border: A PyGVisuals-border to be set.
If this is a falsy value a empty border will be used.
Returns:
Itsself (the widget) for convenience.
"""
if not border:
border = Border(0, 0)
if isinstance(border, Border):
self._border = border
self.markDirty()
return self
def getBorder(self):
"""
Return the widget's border.
Returns:
A PyGVisuals-border belonging to the widget.
"""
return self._border
def setForeground(self, color):
"""
Set the widget's foreground-color (not used by basic implementation).
Args:
color: A color-like object that can be interpreted as a color by pygame (such as a tuple with RGB values).
Returns:
Itsself (the widget) for convenience.
"""
self._foreground = color
self.markDirty()
return self
def setBackground(self, color):
"""
Set the widget's background-color.
Args:
color: A color-like object that can be interpreted as a color by pygame (such as a tuple with RGB values).
Returns:
Itsself (the widget) for convenience.
"""
self._background = color
self.markDirty()
return self
def getForeground(self):
"""
Return the widget's foreground-color (not used by basic implementation).
Returns:
A color-like object that represents the widget's foreground color.
"""
return self._foreground
def getBackground(self):
"""
Return the widget's background-color.
Returns:
A color-like object that represents the widget's background color.
"""
return self._background
def setBackgroundImage(self, image, smooth=None, scale_immediately=False):
"""
Set the widget's background-image.
Args:
image: A surface-like object (e.g. pygame.Surface) that should be rendered as the background.
If this is a falsy value (e.g. None), there will be no background-image.
smooth: A boolean indicating whether the image should be scaled smoothly or not.
If this is None, the previous value will not be overwritten.
The default value is None, so the previous configuration will be kept.
scale_immediately: A boolean indicating whether the image should be scaled during this assignment.
Usually the image is rescaled every time the widget is drawn.
This is especially useful when the scaling-function is set to None
since the image will only be resized once during this assignment therefore increasing performance.
The default value is False, so the image will not be rescaled in this assignment which preserves image quality.
Returns:
Itsself (the widget) for convenience.
"""
if image:
self._background_image = image.convert_alpha(self._getAppearance())
if smooth is None:
smooth = self.smooth_scaling
self.smooth_scaling = smooth
if scale_immediately:
scaling_function = self.scaling_function
if not scaling_function:
scaling_function = _getScalingFunctionForSmoothness(smooth)
self._background_image = scaling_function(self._background_image, self.bounds.size)
else:
self._background_image = image
self.markDirty()
return self
def getBackgroundImage(self):
"""
Return the widget's background-image.
A falsy value (e.g. None) indicates that there is no background-image to be drawn.
Returns:
A surface-like object that is rendered in the background of the widget
or a falsy value indicating that there is no such surface.
"""
return self._background_image
def setDisabeledOverlay(self, color):
"""
Set the widget's color to overlay when it is disabled.
Args:
color: A color-like object that can be interpreted as a color by pygame (such as a tuple with RGB values).
Returns:
Itsself (the widget) for convenience.
"""
self._disabeled_overlay = color
self.markDirty()
return self
def getDisabeledOverlay(self):
"""
Return the widget's color which is overlayed when it is disabled.
Returns:
A color-like object that represents the widget's disabeled color.
"""
return self._disabeled_overlay
def setSmoothScaling(self, smooth):
"""
Set whether the widget's background-image will be scaled smoothly (with pygame.transform.smoothscale) or not.
For more control see the widget's 'scaling_function' property.
Args:
smooth: A boolean indicating whether the image should be scaled smoothly or not.
Returns:
Itsself (the widget) for convenience.
"""
smooth = bool(smooth)
if smooth != self.smooth_scaling:
self.scaling_function = _getScalingFunctionForSmoothness(smooth)
self.markDirty()
return self
def hasSmoothScaling(self):
"""
Return whether the background-image is known to be scaled smoothly or not.
Returns:
A boolean indicating whether the scaling-function is pygame.transform.smoothscale
and the background-image is therefore scaled smoothly.
"""
return self._scaling_function is pygame.transform.smoothscale
def setScalingFunction(self, scaling_function):
"""
Set the scaling-function used for scaling the background-image (to the widgets bounds).
Args:
scaling_function: A function that scales a given surface-like object
to a given size. See for example pygame.transform.scale.
If this is a falsy value (e.g. None), the image will not be rescaled when drawn.
Returns:
Itsself (the widget) for convenience.
"""
self._scaling_function = scaling_function
self.markDirty()
return self
def getScalingFunction(self):
"""
Return the scaling-function used for scaling the background-image (to the widgets bounds).
Returns:
A function that scales a given surface-like object to a given size (like pygame.transform.scale)
or a falsy value (e.g. None) if the background-image is not rescaled when drawn.
"""
return self._scaling_function
def update(self, *args):
"""
Perform any updates on the widget if needed.
This is a basic implementation of focus, active-state and border-rendering;
used for interaction in more advanced widget-classes.
Args:
*args: Any arguments provided for the update. This can include an optional pygame.event.Event to process.
"""
if self.isActive() and len(args) > 0:
event = args[0]
if event.type == pygame.MOUSEBUTTONDOWN and event.button in (1, 2, 3):
self.setFocused(self.rect.collidepoint(event.pos))
if self.isDirty():
self._updateRect(*args)
self.image = self._getAppearance(*args)
if not self.isActive():
inactive = pygame.Surface(self.image.get_rect().size, 0, self.image)
inactive.fill(self.disabeled_overlay)
self.image.blit(inactive, (0, 0))
self.image = self.border.getBorderedImage(self.image, *args)
def _updateRect(self, *args):
"""
Update the actual position and size of the widget.
This is an internal function.
Args:
*args: Any arguments provided for the update. This can include an optional pygame.event.Event to process.
"""
self._rect = self.border.getBounds(self.bounds)
def _getAppearance(self, *args):
"""
Return the underlying widget's appearance.
This is an internal function.
This includes a basic implementation of background-coloring and display of background-image.
Args:
*args: Any arguments provided for the update. This can include an optional pygame.event.Event to process.
Returns:
The underlying widget's appearance as a pygame.Surface.
"""
surface = pygame.Surface(self.bounds.size, pygame.SRCALPHA)
surface.fill(self.background)
if self.background_image:
background_image = self.background_image
if self._scaling_function:
background_image = self._scaling_function(self.background_image, self.bounds.size)
surface.blit(background_image, (0, 0))
return surface
foreground = property(lambda obj: obj.getForeground(), lambda obj, arg: obj.setForeground(arg), doc="The widget's foreground color.")
background = property(lambda obj: obj.getBackground(), lambda obj, arg: obj.setBackground(arg), doc="The widget's background color.")
background_image = property(lambda obj: obj.getBackgroundImage(), lambda obj, arg: obj.setBackgroundImage(arg), doc="""The widget's background-image.
If this is a falsy value (e.g. None), no image will be drawn.""")
disabeled_overlay = property(lambda obj: obj.getDisabeledOverlay(), lambda obj, arg: obj.setDisabeledOverlay(arg), doc="The widget's color to overlay when it is disabled.")
smooth_scaling = property(lambda obj: obj.hasSmoothScaling(), lambda obj, arg: obj.setSmoothScaling(arg), doc="The widget' status as a boolean "
"""regarding whether the background-image will be scaled smoothly (with pygame.transform.smoothscale).
Exact control of the scaling-function is given via the 'scaling_function' property.""")
scaling_function = property(lambda obj: obj.getScalingFunction(), lambda obj, arg: obj.setScalingFunction(arg), doc="The widget's function used "
"""for scaling the background-image (to the widgets bounds).
If this is a falsy value (e.g. None), the image will not be rescaled when drawn.""")
border = property(lambda obj: obj.getBorder(), lambda obj, arg: obj.setBorder(arg), doc="The widget's border (a PyGVisuals' border).")
bounds = property(lambda obj: obj.getBounds(), lambda obj, arg: obj.setBounds(arg), doc="The widget's base position and size as a pygame.Rect.")
rect = property(lambda obj: obj.getActualBounds(), doc="The widget's actual position and size as a pygame.Rect.")
active = property(lambda obj: obj.isActive(), lambda obj, arg: obj.setActive(arg),doc="""The widget's active status as a boolean.
An inactive widget will should not respond to user-input and will have a grey overlay.""")
focused = property(lambda obj: obj.isFocused(), lambda obj, arg: obj.setFocused(arg), doc="""The widget's focus status as a boolean.
A widget will be focused automatically if it is clicked on.""")
|
1. Field of the Invention
The present invention relates to ammunition, and more particularly to low vulnerability gun propellants and novel polymers for use therein.
2. Description of the Prior Art
A continuing objective in the design of gun propellants is to provide a gun propellant which is energetic when deliberately ignited, but which exhibits high resistance to accidental ignition from heat, flame, impact, friction, and chemical action. Propellants possessing such resistance to accidental ignition are known as "low vulnerability" (often abbreviated as LOVA) gun propellants.
LOVA gun propellants are well-known in the prior art. One approach for producing low vulnerability gun propellants has been the use of polyurethane binders. For example, U.S. Pat. No. 4,091,729, to Bell et al, describes a main propellant charge which includes 25% by weight of 1,3,5,7-tetramethylenetetranitramine (HMX) or 1,3,5-trimethylenetrinitramine (RDX), in combination with 75% by weight of polyurethane binder. The polyurethane binder comprises 11.867% by weight of a hydroxyl-terminated block copolymer of propylene oxide and ethylene oxide, 3.167% by weight of trimethylol propane, 9.967% by weight of lysine diisocyanate methyl ester, and 0.025% by weight of titanyl acetyl acetonate. After mixing, the propellant is extruded and placed in a curing oven in the form of small diameter tubes.
However, the propellants of the prior art suffer from the disadvantages that they are not readily extruded with multiple perforations, and their mass impetus is only about 336,000 ft-lbf/lbm. While the mass impetus of such a prior art propellant is acceptable, a higher mass impetus is desirable. In addition, when extruded, a polyurethane such as that described in U.S. Pat. No. 4,091,729 can slump prior to cooling resulting in the partial closure of any perforations. "Slumping" is the tendency of an extruded material to flatten out rather than retaining its shape when placed on a flat surface while cooling and solidifying. Thus if the propellant as extruded is round in cross section, the material will tend to flatten out against the supporting surface.
Accordingly, a need exists for a polymer useful in making a low vulnerability gun propellant which exhibits a desirably high mass impetus value and lends itself to the extrusion of multi-perforated propellant grains which will retain their extruded shape without slumping. |
Mutations in Alternative Carbon Utilization Pathways in Candida albicans Attenuate Virulence and Confer Pleiotropic Phenotypes ABSTRACT The interaction between Candida albicans and cells of the innate immune system is a key determinant of disease progression. Transcriptional profiling has revealed that C. albicans has a complex response to phagocytosis, much of which is similar to carbon starvation. This suggests that nutrient limitation is a significant stress in vivo, and we have shown that glyoxylate cycle mutants are less virulent in mice. To examine whether other aspects of carbon metabolism are important in vivo during an infection, we have constructed strains lacking FOX2 and FBP1, which encode key components of fatty acid -oxidation and gluconeogenesis, respectively. As expected, fox2 mutants failed to utilize several fatty acids as carbon sources. Surprisingly, however, these mutants also failed to grow in the presence of several other carbon sources, whose assimilation is independent of -oxidation, including ethanol and citric acid. Mutants lacking the glyoxylate enzyme ICL1 also had more severe carbon utilization phenotypes than were expected. These results suggest that the regulation of alternative carbon metabolism in C. albicans is significantly different from that in other fungi. In vivo, fox2 mutants show a moderate but significant reduction in virulence in a mouse model of disseminated candidiasis, while disruption of the glyoxylate cycle or gluconeogenesis confers a severe attenuation in this model. These data indicate that C. albicans often encounters carbon-poor conditions during growth in the host and that the ability to efficiently utilize multiple nonfermentable carbon sources is a virulence determinant. Consistent with this in vivo requirement, C. albicans uniquely regulates carbon metabolism in a more integrated manner than in Saccharomyces cerevisiae, such that defects in one part of the machinery have wider impacts than expected. These aspects of alternative carbon metabolism may then be useful as targets for therapeutic intervention. Candida albicans is the most important fungal pathogen of humans, particularly affecting individuals with compromised immune systems or implanted medical devices. Disseminated hematogenous candididasis, the most severe manifestation, is the fourth most common hospital-acquired infection and has a mortality rate of about 40%. Oropharyngeal thrush and vaginitis, nonlethal infections of mucosal surfaces, are the most frequent forms of the disease, but C. albicans can infect essentially any body site. More often, however, C. albicans is a benign component of the mammalian microbiota, living in the gut, mouth, vagina, and on the skin as its primary ecological niche. Despite increasing interest, relatively little is known about the basic biology of C. albicans in either the commensal or pathogenic states. Developing such insight is instrumental in devising novel strategies for reducing the incidence and severity of these infections. The status of the host's innate immune system is the primary determinant of infection. In vitro, the interaction of C. albicans with phagocytes is very dynamic-phagocytosis by macrophages, for instance, induces hyphal growth within the immune cell as a means of escape. The complexity of this interaction has been confirmed through genomic expression profiling of C. albicans cells phagocytosed by macrophages or neutrophils. Over 500 genes are differentially regulated following macrophage phagocytosis, and a similarly massive response accompanies neutrophil phagocytosis ; surprisingly, there are substantial differences between the two programs, suggesting that this fungal pathogen is able to distinguish the two cell types. The macrophage program is similar to that seen after nutrient starvation, including repression of translation and glycolysis and, concurrently, activation of metabolic pathways required to use less favored carbon sources, including the glyoxylate cycle, -oxidation, and gluconeogenesis. Differential display technology has revealed a similar pattern of gene expression in phagocytosed cells. These three interconnected pathways ultimately convert lipids to acetate to glucose. The relevance of these findings has been confirmed by demonstration that the glyoxylate cycle is necessary for full virulence in C. albicans. The primary role of this microbespecific pathway is to assimilate two-carbon compounds (reviewed in reference 20). A similar role for the glyoxylate cycle has been shown in Mycobacterium tuberculosis as well as several fungal and bacterial pathogens of plants, including Magnaporthe grisea, Leptosphaeria maculans, Stagonospora nodorum, and Rhodococcus equi. The key glyoxylate enzyme isocitrate lyase is induced in vivo in C. albicans and Cryptococcus neoformans, though it is not required for virulence in the latter species. These results indicate that diverse pathogens metabolize or are exposed to nonsugar carbon sources in vivo. However, beyond the glyoxylate cycle, little is known about the role of metabolic pathways required to utilize such nutrients during infections. Gluconeogenesis and the glyoxylate cycle have been reported in conflicting reports to be either required or dispensable for virulence in Salmonella. Gluconeogenesisdefective mutants of the plant pathogen Xanthomonas campestris are avirulent, as are peroxisome biogenesis and fatty acid degradation mutants in the plant fungal pathogen Colletotrichum lagenarum. It was recently reported that peroxosome function was not required for pathogenicity in C. albicans. Deletion of the C. albicans gluconeogenic gene PCK1 confers a moderate reduction in virulence. Curiously, disabling both gluconeogenesis and glycolysis via disruption of fructose-1,6-bisaldolase (FBA1) has only a modest impact on infectivity in C. albicans. Some aspects of carbon metabolism present intriguing candidates for drug discovery. The glyoxylate cycle does not exist in mammals, and -oxidation of fatty acids is highly divergent between mammals and fungi. To better understand the importance of these pathways, we have examined the physiology and virulence of C. albicans strains deficient in -oxidation, the glyoxylate cycle, and gluconeogenesis, through deletions of genes encoding key enzymes in each pathway, the -oxidation multifunctional protein (FOX2), isocitrate lyase (ICL1), and fructose-1,6-bisphosphatase (FBP1). Each of these mutants is attenuated to some degree in a mouse model of disseminated candidiasis, confirming that alternative carbon sources are relevant nutrients in vivo, and, in fact, C. albicans likely uses multiple carbon sources during infection. Finally, in vitro phenotypes and genomic analysis indicate that the regulatory networks that control alternative carbon metabolism in C. albicans differ significantly from the paradigms developed in Saccharomyces cerevisiae. Our findings confirm the importance of these central metabolic processes in fungal pathogenesis. For transformation, the disruption construct was liberated from the plasmid backbone using PstI (fox2⌬) or HindIII/SacII (fbp1⌬). These were used to transform CAI4-F2 to uridine prototrophy. Correct heterozygotes were confirmed by PCR. Ura recombinants were selected on 5-FOA medium. The second allele was disrupted in the same manner, and homozygous mutants were confirmed by PCR for the presence of the disruption alleles and the absence of the wild-type allele. For fbp1⌬, the first allele was disrupted with pMR8 and the second was disrupted with pMR9. These constructs differ in the orientation of the hisG-URA3-hisG cassette with respect to the FBP1 open reading frame. The icl1⌬/icl1⌬ mutant strain MLC9 has been described previously. This strain expresses URA3 from the ICL1 locus. Uridine auxotrophs of MLC9 were selected on 5-FOA medium to allow complementation using CIp10-based plasmids, as described below. S. cerevisiae icl1⌬ and fox2⌬ mutants were constructed by PCR-mediated disruption, using plasmid pFA6-KanMX2 as a template and oligonucleotide primers with homology to the genes to be disrupted. Linear PCR products were used to transform strains MLY40 for icl1⌬ and MLY41 for fox2⌬ to G418 resistance. Disruptions were confirmed by PCR. pRS316 was used to complement the uracil auxotrophy for the carbon source growth assay. Complementation. Complementation plasmids for FOX2, ICL1, and FBP1 were constructed by PCR by amplifying the open reading frame flanked by 500 to 700 bp of 5 UTR and 300 bp of 3 UTR. PCR products were subsequently cloned into the integrating plasmid CIp10, which targets integration to the RPS10 locus. This methodology has been demonstrated to be phenotypically neutral and to eliminate position effects based on the expression levels of URA3. The complementation plasmids (pMR11, FOX2; pMR12, ICL1; and pMR2, FBP1) were introduced to uridine auxotrophic homozygous mutants by transformation. Empty CIp10 was integrated into the mutant strains. Insertion at RPS10 was verified by PCR. URA3 is integrated at the RPS10 locus in all strains used here, with the exception of the wild-type strain, SC5314. In vitro growth assays. Growth assays used solid YNB media containing 2% glucose, potassium acetate, ethanol, oleate, citrate, or glycerol as the sole carbon source and incubation at room temperature (24°C), 30°C, or 37°C for 3 to 7 days, depending on the carbon source, as indicated in the figure legends. For the spot dilution assays, strains were grown into the mid-log phase in YPD, collected by centrifugation, and washed with water. They were transferred to 96-well plates, at an optical density at 600 nm (OD 600 ) of 0.5, and serially diluted fivefold. Solid media were spotted with these dilutions using a multiprong pin replicator. The toxicity assays used solid YP medium (1% yeast extract, 2% peptone) with 2% glucose, glycerol, potassium acetate, or ethanol. For growth assays in liquid media, strains were grown in YNB-glucose at 30°C or 37°C overnight. The next day, cells were harvested by centrifugation, washed twice with water, and resuspended at an OD 600 of 0.08 in YNB media containing the appropriate carbon source. Growth of the cultures was assessed over a period of 5 to 7 days by measuring OD 600. Northern analysis. SC5314 cells were grown overnight in YNB media with 2% glucose, harvested by centrifugation, and washed twice with water. Cells were resuspended in YNB media containing 2% glucose, acetate, or oleate and grown for 1 h, pelleted by centrifugation, and frozen on dry ice-ethanol. RNA was isolated using the hot acidic phenol method. RNA was also prepared from icl1⌬, fbp1⌬, and fox2⌬ mutants grown in acetate for 1 h. A total of 15 ng of RNA was loaded and run on a 1% MOPS (morpholinepropanesulfonic acid)-agarose gel and then transferred to a nylon membrane. Gene-specific probes were amplified by PCR and were labeled with the RadPrime DNA labeling system from Invitrogen. Probes were purified using Roche Quick Spin columns. Blots were incubated in prehybridization solution containing 5 SSC (1 SSC is 0.15 M NaCl plus 0.015 M sodium citrate), 50% formamide, 5 Denhardt's solution, 0.1% sodium dodecyl sulfate (SDS), and 100 g/ml single-stranded DNA for 2 h at 42°C followed by hybridization overnight. Images were processed using a Storm PhosphorImager and exposed to film for autoradiography. rRNA was used as a loading control. In vivo virulence assays. Mouse virulence assays were performed as described previously. Adult, female, outbred ICR mice were obtained from Harlan. Cultures of C. albicans were grown in YPD to mid-log phase and collected by centrifugation. Cells were washed and resuspended in phosphate-buffered saline, and mice were infected via tail vein injection with 10 6 C. albicans yeast-form cells. The group sizes were 10 to 12 mice per strain. Infected mice were subsequently monitored for signs of infection and euthanized when moribund according to approved protocols. Survival data were analyzed with Prism3 (Graphpad Software) using the log rank test. Statistical significance was defined as a P value of less than 0.05. All animal assays were conducted in accordance with protocols approved by the University of Texas Health Science Center Animal Welfare Committee. RESULTS Our previous work showed that C. albicans responds to phagocytosis by macrophages with a metabolic shift that is highly similar to carbon starvation. We further demonstrated that the glyoxylate cycle was necessary for full virulence. These results indicated that C. albicans likely encounters glucose-poor conditions during infection and that the ability to utilize alternative carbon sources is a virulence attribute in this species. Other than the role of the glyoxylate cycle, little is known about nutrient availability in different host environments or the importance of carbon metabolic pathways in either commensalism or pathogenicity of C. albicans. In fact, while some nutrients are well known to be scarce in vivo-iron is a classic example-there have been relatively few studies addressing carbon acquisition and/or metabolic activity in pathogens of any kind. C. albicans, like most fungi, uses sugars, particularly glucose, as the preferred carbon source. However, a wide variety of nonfermentable carbon sources can also satisfy cellular requirements, including but not limited to ethanol, acetate, amino acids, glycerol, and fatty acids. Collectively, these compounds are sometimes called "alternative" or "nonpreferred" carbon sources because fungi do not use them in the presence of sugars. These alternative sources are metabolized by three main pathways: -oxidation of fatty acids, the glyoxylate cycle, and gluconeogenesis. The main purposes of these pathways are to provide energy, replenish tricarboxylic acid (TCA) cycle intermediates and acetyl-coenzyme A (CoA), and produce glucose. These pathways are shown in schematic form in Fig. 1. Virtually all cellular building blocks are synthesized starting from one of the three intermediates highlighted here: acetyl-CoA, compounds of the TCA cycle, and glucose, which can be produced from various carbon sources through these central pathways. Figure 1 also lists the induction of key genes in each pathway following macrophage phagocytosis. Such a coordinated and rapid response strongly implicates these processes in pathogenesis. To understand the role of alternative carbon metabolism in vivo, the carbon sources encountered by C. albicans during infections, and how these systems may differ from those of other species, we used a gene disruption approach to disable these pathways individually. Construction of alternative carbon metabolism mutants. Genes chosen for analysis were FOX2, FBP1, and ICL1. FOX2 (orf19.1288) encodes the "multifunctional protein" of -oxidation, so named because it has both 3-hydroxyacyl-CoA dehydrogenase and enoyl-CoA hydratase activities, each of which is required for fatty acid degradation. FOX2 was selected because it is essential for -oxidation in S. cerevisiae, is present as a single gene in C. albicans, and is the most highly induced gene of -oxidation following phagocytosis (44.5-fold; see reference 18). The 923-amino-acid CaFOX2 protein is 52% identical to FOX2 from S. cerevisiae. FOX2 was disrupted using the standard Ura-blaster methodology. The disruption construct was made using overlap PCR to precisely remove the open reading frame, from the ATG to the stop codon. FBP1, encoding fructose-1,6-bisphosphatase, was disrupted in a similar manner. FBP1 (orf19.6178; 331 amino acids) is one of two gluconeogenesis-specific proteins (the other is phosphoenolpyruvate carboxykinase; PCK1), catalyzing the penultimate step in the synthesis of glucose. It, too, is a highly conserved enzyme, with 64% identity to S. cerevisiae FBP1 and 45% identity to the Escherichia coli Fbp. An fbp1 mutant in S. cerevisiae does not grow in the absence of glucose or other hexoses. Both mutants were complemented by cloning the PCR-amplified genes into the CIp10 plasmid, which directs integration to the RPS10 locus. This method has been demonstrated to eliminate potential position effects based on altered 282 RAMREZ AND LORENZ EUKARYOT. CELL URA3 expression and to be appropriate for both in vitro and in vivo experiments. In the mutant strains, URA3 was also integrated at RPS10 using an empty CIp10 vector. For both the fox2⌬ and fbp1⌬ mutants, we tested two independently constructed mutants, one of which was complemented with a wildtype copy of the gene. Our earlier work with ICL1 was done prior to the appreciation of URA3 position effects on virulence ; for this reason, we reconstructed a pair of strains (mutant and complemented) with CIp10 to compare with the fox2⌬ and fbp1⌬ strains. In vitro phenotypes. Strains lacking FOX2, ICL1, or FBP1 are viable and grow at wild-type rates on media containing glucose as the carbon source, as expected. Using precedents from S. cerevisiae and numerous other species, we established predictions for the carbon utilization phenotypes of these mutant strains: fox2⌬ mutants should fail to grow on media containing fatty acids, such as oleic acid, a monounsaturated C-18 lipid; icl1⌬ mutants should not grow in the presence of fatty acids, acetate, or ethanol; and fbp1⌬ mutants should not utilize any nonfermentable carbon source. We tested these predictions using a straightforward growth assay on solid media containing different compounds as the carbon source. Included in this panel were glucose, glycerol, potassium acetate, ethanol, citric acid, and oleic acid, each present at 2% in minimal YNB media. As expected, fox2⌬ mutant strains were unable to grow when fatty acids such as oleic, palmitic, linoleic, or myristic acids were the sole carbon source ( Fig. 2A and data not shown). Surprisingly, the growth defects were not limited to media containing lipids ( Fig. 2A). In particular, the fox2⌬ mutant was also unable to utilize ethanol as a carbon source and grew poorly on citrate and glycerol. The icl1⌬ mutant strain also exhibited more extensive defects than predicted and was entirely unable to grow on citrate and glycerol, in addition to the anticipated phenotypes on fatty acids, ethanol, and oleate. Growth was restored in the complemented strains. We also tested a second, independently constructed, mutant for each gene with identical results (data not shown). These observations were surprising for several reasons. FOX2, ICL1, and FBP1 are each structural enzymes in their respective pathways. Their substrate specificity and biochemical function have been thoroughly established, and we did not expect any "cross talk" between the pathways. Mutations in these genes have been studied in a wide variety of systems, and there have been no indications that they have more global regulatory roles. In S. cerevisiae, for instance, the phenotypes of these mutants are clearly confined to growth on their relevant substrate. To test one of these, we constructed S. cerevisiae strains lacking ICL1 or FOX2 and assessed their ability to use ethanol as the sole carbon source (Fig. 2B). The S. cerevisiae fox2⌬ strain grows at wild-type rates on this carbon source, in contrast to the C. albicans results. To more thoroughly test these strains on alternate carbon sources, we used a spot dilution assay. In this assay, logarithmically growing cells in rich YPD medium were washed in water and diluted to an OD 600 of 0.5 in a 96-well plate. They were then serially diluted 1:5 in water five more times and applied as spots to solid media using a pin replicator. Because initial observations had suggested that the carbon utilization phenotypes may be more severe at higher temperatures, we performed this assay at room temperature (24°C), 30°C, and 37°C (Fig. 3). Three observations stand out in these data. First, there are no growth differences in the presence of glucose for any of these mutants (see also Fig. 4A and B). Second, the ability to assimilate nonpreferred carbon sources is impaired at elevated temperatures. C. albicans does not grow as well at 37°C as at 30°C on acetate or glycerol. This defect is most pronounced on media containing citrate, ethanol, and oleate. Citrate utilization, in particular, is very sensitive to temperature, with growth observed only at 30°C. This is somewhat surprising as C. albicans generally grows more rapidly at 37°C, the temperature of its primary niche in the mammalian host, than it does at 30°C. Finally, the temperature effect is even more severe in the mutants. This is particularly visible for the fox2⌬ mutant on acetate, which exhibits the wild-type growth rate at 30°C, but does not grow at 37°C (Fig. 4C and D). Alternative carbon sources are not toxic. We considered whether it was possible that perturbations in carbon metabo- 284 RAMREZ AND LORENZ EUKARYOT. CELL lism may render certain compounds toxic to the cell. For instance, these mutations may lead to the accumulation of usually transient intermediates that are deleterious at high concentrations: acetaldehyde, an intermediate in the conversion of ethanol to acetyl-CoA, inhibits the growth of S. cerevisiae at concentrations above 0.3 g/liter, while ethanol itself is well tolerated even above 100 g/liter. To test this hypothesis, we incubated the C. albicans wild-type and mutant strains on the undefined medium YP supplemented with glucose (standard YPD), glycerol, acetate, or ethanol, each present at 2%. In this medium, there are numerous compounds to satisfy carbon requirements, including amino acids, nucleotides, fatty acids, etc. The fbp1⌬, icl1⌬, and fox2⌬ mutants grew on each of these media, indicating the growth defects shown in Fig. 2 to 4 on minimal media were not due to toxic effects of these carbon sources. These assays were performed at 37°C, the temperature at which the carbon source-dependent growth effects are most pronounced. As a second test, we incubated these strains on media containing both glucose and an alternative carbon source (e.g., YPDE with 2% glucose and 2% ethanol). The presence of ethanol, glycerol, or acetate, in addition to glucose, did not inhibit growth compared to media containing glucose alone (data not shown), again providing evidence against the toxic effects of these compounds. As can be seen in Fig. 5, the fbp1⌬ mutant does grow more slowly in the presence of these alternative carbon sources, presumably because gluconeogenesis is required to use many of the compounds in YP medium. The three mutants were also tested for other phenotypes, including filamentous growth under a variety of inducing conditions and stress sensitivity. In all tests, they behaved identically to the wild type (data not shown). Regulation of alternative carbon genes. Given the unusual phenotypes, we investigated the regulation of these genes in different carbon sources. In wild-type strains, FBP1, ICL1, and FOX2 are expressed at low levels in glucose-grown cells (Fig. 6). Expression increases markedly in cells incubated in potassium acetate for 1 h. FOX2 is further induced in the presence of oleic acid. These results are similar to the expression profiles of the S. cerevisiae homologs. We also assayed expression of these three genes in the mutant strains to determine whether the unexpected growth phenotypes observed, particularly for the icl1⌬ and fox2⌬ mutant strains, could be explained by misregulation of other carbon metabolic genes. However, expression levels of FBP1, ICL1, and FOX2 were very similar in the mutants compared to the wild-type strain (Fig. 6), indicating that transcriptional regula- tion of these genes does not explain the growth phenotypes. Transcripts were not detected in strains lacking the gene used as a probe (e.g., ICL1 message is not seen in the icl1⌬ mutant), confirming the mutant genotypes and probe specificity. Alternative carbon metabolism is required in vivo. Previous work has shown that icl1⌬ mutants are significantly attenuated in a mouse model of hematogenously disseminated candidiasis. To determine the extent to which alternative carbon sources are relevant in vivo, we tested these mutants in the standard mouse tail vein injection model. In this model, 10 6 C. albicans cells (yeast form) are injected into outbred adult female ICR mice. Subsequently, the animals are monitored for signs of clinical infection and euthanized when moribund according to approved protocols. Using this assay, we determined that fox2⌬ mutant strains have a mild reduction in virulence (Fig. 7A). The mean time to death (MTD) for the fox2⌬ mutant was 6.9 days, compared to 4.8 days for the wild-type strain. Complementation of the mutant with the FOX2 gene fully restored virulence. Given this small difference in virulence, the assay was repeated, giving essentially identical results; the data in Fig. 7A are a combi-nation of both assays (a total of 20 to 22 mice per strain). Statistical analysis of these data is presented in Table 2. In addition, we tested a second fox2⌬ mutant, constructed completely independently, which had a similar phenotype (Table 2) (data not shown). We also used a smaller inoculum to determine whether the virulence defect would be more pronounced at the lower level. Mice injected with 10 5 wild-type cells succumbed to the infection with an MTD of 17.4 days, while 60% of the fox2⌬ mutantinjected mice survived to 45 days, when the experiment was terminated (Fig. 7B). To continue our analysis of alternative carbon metabolism during infection, we tested the icl1⌬ and fbp1⌬ mutant strains as well (Fig. 7C and D). We retested the icl1⌬ mutant using strains that control for URA3 position effects that may have complicated our earlier work. The reduction in virulence was similar to what we observed previously and what another group using a properly complemented strain pair reported recently. We also tested two independent fbp1⌬ mutant strains (Fig. 7B). Both strains behaved similarly in this assay, with either 10% or 30% of the animals surviving to day 20, compared to an MTD of 5.2 days for the wild type. The complemented strain partly restored virulence (MTD 9.4 days). The wild-typemutant comparisons were again significant (n 10, P 0.05). Figure 7E shows a composite survival curve to illustrate the overall patterns of virulence seen in mutant strains for these FIG. 5. Alternative carbon sources are not toxic. C. albicans fbp1⌬, icl1⌬, and fox2⌬ strains (see the legend to Fig. 2) were grown on YP media supplemented with 2% glucose, glycerol, acetate, or ethanol and grown for 2 days at 37°C. FIG. 6. Carbon source-dependent expression of FBP1, ICL1, and FOX2. The wild-type (SC5314), icl1⌬ (MRC10), fbp1⌬ (MRC14), and fox2⌬ (MRC6) strains were grown to mid-log phase in minimal YNB medium with glucose, collected by centrifugation, washed with water, and shifted to media containing glucose (G), potassium acetate (A), or oleate (O) for 1 h. RNA was prepared from these cells, and expression of the three genes was determined by Northern analysis. The absence of signal in the mutant strains also confirms the genotype. The numbers visible at the right side of the rRNA images are from the fluorescent sizing ruler that was inadvertently photographed with the gel. 286 RAMREZ AND LORENZ EUKARYOT. CELL three genes. The fox2⌬ mutant is modestly attenuated compared to the wild type. The icl1⌬ and fbp1⌬ mutants are severely attenuated and are very similar to each other. From these studies, we conclude that C. albicans must acquire and utilize less-preferred carbon sources during an infection. DISCUSSION This work demonstrates that several facets of alternative carbon metabolism in C. albicans are important during systemic infection. Deletions of key enzymes in the pathways of Table 2 for details. (B) A lower inoculum (10 5 cells per strain) was injected. Strains are wild type (SC5314) and fox2⌬ (MRC6). (C) A single strain pair was tested (icl1⌬, MRC10; icl1⌬ ICL1, MRC11). These data are similar to those previously reported; unlike those experiments, URA3 is integrated at RPS10 in these strains; see the text and Table 2 -oxidation of fatty acids (FOX2), the glyoxylate cycle (ICL1), and gluconeogenesis (FBP1) confer virulence defects from moderate to severe. These data strongly support a model whereby C. albicans acquires and assimilates nonfermentable (nonsugar) compounds as primary sources of carbon. The potential nature of these compounds will be discussed below. Furthermore, we have shown that these mutations alter the utilization of alternative carbon sources in unexpected ways. We find that fox2⌬ mutants are unable to efficiently assimilate ethanol or acetate as sole carbon sources, the metabolism of which is independent of the enzymatic steps of -oxidation. In S. cerevisiae, the fox2⌬ mutant grows at wild-type rates in the presence of ethanol, marking an important difference in carbon metabolisms in these two species. Similarly surprising, C. albicans icl1⌬ mutants use glycerol and citrate poorly or not at all, in addition to their expected inability to grow on acetate, ethanol, and fatty acids. The growth defects are not caused by accumulation of toxic intermediates resulting from perturbations in the metabolic pathways. Despite these differences, these three key genes are regulated by carbon source in a manner similar to S. cerevisiae; obviously, though, there are many genes whose misregulation in these mutants might cause the observed phenotypes and a more global analysis may be required to find the relevant perturbations in these mutants. Taken together, these data suggest that the pathways controlling alternative carbon metabolism in C. albicans are more integrated than in other fungi. We speculate that C. albicans has evolved this network to meet its specialized needs as a fungal commensal/pathogen. Further work will be required to decipher these pathways. Why do mutations in carbon utilization pathways confer pleiotropic phenotypes? FOX2 is an enzyme of the -oxidation cycle. In several other bacterial and fungal systems, mutation of this "multifunctional protein" confers a single phenotypethe inability to catabolize fatty acids. In C. albicans, uniquely, FOX2 is also required for the efficient utilization of acetate, ethanol, citrate, and lactate, compounds whose assimilation is completely independent of the enzymatic steps of -oxidation (this work and reference 28). The icl1⌬ mutant is similarly pleiotropic. Why might this be? We speculate that these mutations perturb alternative carbon metabolism in one of three ways: by altering cellular physiology, gene regulation, or metabolite balances to disrupt the normal function of these pathways. Much of alternative carbon metabolism is compartmentalized, occurring in the peroxisomes or mitochondria. Thus, disruption of normal organellar function could inhibit assimilation of nonfermentable carbon sources. Recent work from Distel and colleagues, described below, suggests that peroxisomal dysfunction is not responsible for these phenotypes, but does not exclude a role for the mitochondria. In S. cerevisiae, respiration-deficient mitochondrial mutants are unable to grow on nonfermentable carbon sources, but even less dramatic changes can confer carbon source-and temperaturedependent phenotypes. For instance, strains lacking the mitochondrial protein chaperone CPR3 are specifically unable to grow in the presence of lactate at 37°C. Alternatively, fox2⌬ and icl1⌬ strains may misregulate a gene or genes required for alternative carbon utilization. We show here (Fig. 6) that several key genes are properly regulated at the transcriptional level in the mutant strains, but this was not a comprehensive analysis. Transcriptional repression of genes at key intersections of carbon metabolism-such as acetyl-CoA synthases, carnitine acetyltransferases, or mitochondrial metabolite transporters-could explain these phenotypes, but the possibilities are too numerous for a candidate gene approach and a more global survey will be required. Finally, the mutations described here may instead result in a skewed metabolite profile, such as depletion of coenzyme A or distortion of the NADP/NADPH ratio, that inhibits specific enzymatic processes or disrupts cellular energetics. Most likely, the pleiotropic phenotypes are caused by a combination of effects in which altered levels of metabolites lead to changes in cell physiology that prevent growth. Further studies will be necessary to understand these processes. What alternative carbon sources are available in vivo? Our previous work showed that cells lacking the key glyoxylate enzyme isocitrate lyase (ICL1) are significantly impaired during infections. This initial finding has been confirmed, both here and by others, using reengineered strains that control for possible position effects with the URA3 disruption marker used previously. A conclusion from these earlier studies was that C. albicans must use a substrate incorporated via the glyoxylate cycle during infections. However, there are numerous such compounds, including acetate, fatty acids, ethanol, and several amino acids. Because some aspects of alternative carbon metabolism are unique to microorganisms, the identification of relevant carbon sources in vivo may highlight enzymes or pathways as attractive candidates for antifungal drug discovery. Our data begin to address this question. The mild reduction of virulence seen with the fox2⌬ mutant suggests that fatty acids are a relevant carbon compound in vivo. The unexpected carbon source-dependent growth defects of this mutant complicate this analysis, however, and recent work has called into question the importance of -oxidation. Piekarska et al. reported very recently that disruption of peroxisomal function via mutation of the biogenesis factor PEX5 blocks -oxidation without any discernible effect on virulence. They also showed that the fox2⌬ mutant is unable to use ethanol, acetate, and lactate, similar to our findings, and is attenuated in the mouse model. They concluded from these observations that -oxidation is not relevant in vivo. In contrast, it is apparent that some nonfermentable compounds are important during infection. The similarly severe virulence phenotypes of fbp1⌬ and icl1⌬ mutants strongly indicated that substrates of the glyoxylate cycle and gluconeogenesis are found and used in at least some in vivo niches. So what is the spectrum of potential compounds? It includes any compound for which acetyl-CoA is a catabolic intermediate: acetate, ethanol, fatty acids (which we have shown to be a minor component), and 10 of the amino acids. The remaining amino acids are converted to TCA cycle intermediates (which are also potential nutrients). Several amino acid auxotrophs are fully virulent, including those unable to synthesize arginine, histidine, and leucine, implying that these compounds are present at sufficient levels in tissue or blood to support growth of C. albicans. Alternatively, the secreted aspartyl proteases allow C. albicans to grow in the presence of protein as a nutrient source. The secreted aspartyl proteases are widely considered to be virulence factors, and nutrient acquisition may be one of their functions. Degradation of lipids by the host, which occurs partly in the lysosome, may provide a pool of acetate or acetyl-CoA available to a phagocytosed cell. Very recently, Distel and colleagues proposed that lactate is the relevant carbon source. This is certainly a physiologically accessible compound, and the data are consistent with this suggestion, but as discussed above, numerous other compounds also meet these criteria. We believe it is likely that C. albicans finds and uses multiple carbon sources during infection. These would include substrates of the glyoxylate cycle and gluconeogenesis, in addition to glucose. C. albicans could use several compounds simultaneously at the same infection site; this is not generally favored in S. cerevisiae, but our work has illustrated key differences between these species. Alternatively, different body sites could offer diverse nutrients and our virulence data are an amalgamation of these effects. Further work will be required to dissect these responses, perhaps in a manner similar to the green fluorescent protein-promoter fusions used by Brown and colleagues to examine ICL1 expression in vivo. Regulation of alternative carbon metabolism. Northern analysis has shown that FBP1, ICL1, and FOX2 are expressed at low levels in the presence of glucose and are induced markedly after a shift to media containing acetate or oleate. Particularly highly induced is FOX2 when oleate is the sole carbon source. This carbon source regulation is similar to that observed in S. cerevisiae. However, this regulatory similarity belies the intriguing growth phenotypes of the C. albicans mutants. To examine the regulatory networks that govern alternative carbon utilization, we have begun to identify homologs of the transcriptional regulators known in S. cerevisiae. In that model eukaryote, a shift to poor carbon conditions alleviates glucose repression mediated by the MIG1 transcriptional regulator (reviewed in references 8 and 35). Transcriptional profiling indicates that the C. albicans MIG1 homolog serves a similar function. Specific induction of genes based on carbon source is mediated in S. cerevisiae by the regulators CAT8 (gluconeogenesis, glyoxylate cycle), ADR1 (ethanol, acetate, amino acids), and the OAF1/PIP2 heterodimer (fatty acids, peroxisome biogenesis). Other regulators, such as GAL4, are active in the presence of sugars other than glucose. C. albicans has a clearly recognizable CAT8 homolog. There are two marginally conserved homologs of ADR1; in contrast, OAF1 and PIP2 are not readily apparent through sequence analysis (M. Lorenz and M. Ramirez, unpublished observations). This divergence of regulatory proteins is consistent with our suggestion that C. albicans has a more highly integrated network governing carbon metabolism such that defects in discrete aspects of carbon utilization may feed back to globally downregulate the system. Why might C. albicans have this more integrated regulatory network? In S. cerevisiae, cellular metabolism is tuned to run mostly on glucose. When that preferred source is not available, it activates pathways to utilize small subsets of alternative carbon sources: other sugars, ethanol, amino acids, etc. For a saprobic species, the time required to switch from one source to another may be a small cost in terms of the efficiency of expressing only those genes necessary in a given condition. A pathogen like C. albicans, however, may not be able to tolerate periods of metabolic inactivity while new sets of genes are expressed in the face of immunological pressures. This may have driven the evolutionary divergence in this aspect of metabolism between the two species. Nutritional stress during infection. It has long been appreciated that iron limitation is a key stress encountered in the host, and pathogens of all kinds have developed sophisticated means to acquire this scarce nutrient. There has been far less emphasis on limitation for other nutrients, such as carbon and nitrogen, but there is increasing evidence from many systems that carbon starvation, in particular, is a common obstacle in vivo. Many bacterial commensals and pathogens have the ability to utilize compounds such as ethanolamine, fucose, and propanediol, suggesting that these compounds may be routinely encountered in their natural environment. Similarly, the glyoxylate cycle is required for full virulence in C. albicans and Mycobacterium tuberculosis, the most common fungal and bacterial pathogens of humans. It is also important in several plant pathogens, both bacterial and fungal. Each of these, then, apparently experiences carbon starvation during the infection process. Further work will be required to understand the temporal and spatial requirements for alternative carbon metabolism during an infection and to define the exact compounds available to microbial pathogens in the body. |
Bilateral pontine infarction with basilar artery fenestration Abstract Rationale: Basilar artery (BA) fenestration is a congenital anomaly with duplicated BA, which can cause ischemic stroke. However, the stroke mechanism is not clearly verified in patients with BA fenestration. Patient concerns: Here, we report a case of 64-year-old man with well-controlled hypertension admitted with dysarthria, only. Diagnoses: Diffusion weighted image showed a bilateral symmetric pontine infarction sparing the midline. BA fenestration was observed from magnetic resonance angiography. Intervention: High-resolution magnetic resonance image (MRI) and 4D flow MRI was performed to verify the mechanism of stroke associated with BA fenestration. Outcomes: No plaque was observed at the area of BA fenestration from high-resolution MRI. 4D flow MRI showed bifurcated flow with high flow velocity and low shear stress at the area of BA fenestration. Lessons: A turbulent flow with high flow velocity and low shear stress at the BA fenestration area may have influenced the flow through the bilateral perforating arteries resulting in a bilateral symmetric pontine infarction with sparing the midline where the septa of BA is located. 4D flow dynamic studies may be beneficial for verifying the mechanism of stroke. Introduction Fenestration of basilar artery (BA) is a rare but well-described congenital anomaly. BA is duplicated, especially in the lower end, because of the failure of plexiform primitive longitudinal neural artery fusion. Previously, several cases of posterior circulation infarction or cerebral aneurysms due to BA fenestration were reported. However, the mechanism involved in posterior circulation infarction in patients with BA fenestration was not clearly verified. Here we report of case of patient with symmetrical bilateral pontine infarction patient due to BA fenestration, which may help understanding the mechanism of ischemic stroke. Informed written consent was obtained from the patient for publication of this case report and accompanying images. As a case report ethical approval of this study was waived by the local ethics committee. Case report A 64-year-old man suddenly developed severe dysarthria 2 days before admission. Neurological examination revealed no other deficit. There was no risk factor for stroke, except hypertension. The patient was under regular medication of calcium channel blocker and his blood pressure was well-controlled. Diffusionweighted image revealed symmetric high-signal intensity in bilateral paramedian pontine (Fig. 1A). The midline of basis pontis was spared. The magnetic resonance angiography displayed fenestration of the proximal mid-BA ( Fig. 1B). Highresolution magnetic resonance image (HRMRI) showed endothelium-lined partial intraluminal septa within the fenestrated artery at the level of bilateral symmetric pontine infarction (Fig. 1C). No atheroma was observed from HRMRI. Flow dynamic study with GTflow (GyroTools, Winterthur, Switzerland) was performed. Flow was divided at the fenestrated area (Fig. 1D). Flow velocity and wall shear stress was measured at before, after, and at the level of fenestration (Fig. 1E). Among those 3 points, peak flow velocity was highest and the wall shear stress was lowest at the area of fenestration (Fig. 1F). Aspirin and cilostazol were started and 3 months later patient was maintained with cilostazol mono therapy. Calcium channel blocker was reused after the acute period of stroke. Blood pressure was controlled under 130/80 mmHg. Dysarthria improved and no stroke recurrence was observed during the follow-up. Discussion Previously, pediatric stroke patients with BA fenestration, but without vascular risk factors were reported. Therefore, fenestration of BA itself may be the direct cause of ischemic stroke. However, the exact mechanism was not verified. It is well-known that local hemodynamics alters the development of atherosclerosis; at the bifurcated area of carotid artery, the turbulence at the outer wall influences the development of atherosclerosis. Similarly in BA fenestration, HRMRI study revealed that plaques were mostly observe at the lateral walls, which may obliterate the orifice of BA perforators, in the fenestrated BA area. The location of plaques were explained by the turbulence and low shear stress at the area. However, our case did not show a plaque from the HRMRI. Still an area with turbulence may exist and cause low flow through the perforator originating at the area with turbulence. Interestingly, our patients showed a very symmetric lesion sparring the midline where the septa was observed, which implies that hemodynamic factor may have bilaterally influenced the occurrence of symmetric bilateral pontine infarction. The flow parameters measured at the area of BA fenestration was also supportive for the hemodynamic hypothesis showing that the peak systolic velocity was highest and the wall shear stress was lowest at the fenestrated area, where the bilateral symmetric infarction was observed. Area with turbulence is characterized by high flow velocity and low shear stress. Our case helps to explain the mechanism of pontine infarction in patients with BA fenestration without vascular risk factor by a hemodynamic theory. Furthermore, HRMRI and 4D flow studies may be helpful for evaluating the stroke mechanism. |
The present invention relates to an electromagnetically actuated valve. Several electromagnetically actuated valves, in particular fuel injection valves, are known where components subject to wear are provided with wear-resistant coatings.
German Published Patent Application No. 29 42 928 describes the application of wear-resistant diamagnetic material coatings on parts subject to wear, such as armatures and nozzle bodies. These coatings, applied in accurately dimensioned layer thicknesses, are used to limit the stroke of the valve, thereby minimizing the effect of residual magnetism on the movable parts of the fuel injection valve.
European Published Patent Application No. 0 536 773 also describes a fuel injection valve where a hard metal coating is applied by electroplating to the armature of its cylindrical peripheral surface and annular stop surface. This coating, made of chromium or nickel, has a thickness of 15 to 25 .mu.m, for example. As a result of electroplating, a slightly tapered layer thickness distribution is formed with a minimally thicker layer achieved at the outer edges. The layer thickness distribution of coatings formed by electroplating is physically predefined and can barely be influenced. |
<reponame>sauchye/TZImagePickerController
//
// TTTAttributedLabel+LocalizationsPlus.h
// AWELocalizations-iOS
//
// Created by ByteDance on 2018/2/22.
//
#import <UIKit/UIKit.h>
@interface AWERTLTTTAttributedLabel : NSObject
@end
|
/*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/tcr/v20190924/model/RetentionExecution.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Tcr::V20190924::Model;
using namespace std;
RetentionExecution::RetentionExecution() :
m_executionIdHasBeenSet(false),
m_retentionIdHasBeenSet(false),
m_startTimeHasBeenSet(false),
m_endTimeHasBeenSet(false),
m_statusHasBeenSet(false)
{
}
CoreInternalOutcome RetentionExecution::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("ExecutionId") && !value["ExecutionId"].IsNull())
{
if (!value["ExecutionId"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `RetentionExecution.ExecutionId` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_executionId = value["ExecutionId"].GetInt64();
m_executionIdHasBeenSet = true;
}
if (value.HasMember("RetentionId") && !value["RetentionId"].IsNull())
{
if (!value["RetentionId"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `RetentionExecution.RetentionId` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_retentionId = value["RetentionId"].GetInt64();
m_retentionIdHasBeenSet = true;
}
if (value.HasMember("StartTime") && !value["StartTime"].IsNull())
{
if (!value["StartTime"].IsString())
{
return CoreInternalOutcome(Core::Error("response `RetentionExecution.StartTime` IsString=false incorrectly").SetRequestId(requestId));
}
m_startTime = string(value["StartTime"].GetString());
m_startTimeHasBeenSet = true;
}
if (value.HasMember("EndTime") && !value["EndTime"].IsNull())
{
if (!value["EndTime"].IsString())
{
return CoreInternalOutcome(Core::Error("response `RetentionExecution.EndTime` IsString=false incorrectly").SetRequestId(requestId));
}
m_endTime = string(value["EndTime"].GetString());
m_endTimeHasBeenSet = true;
}
if (value.HasMember("Status") && !value["Status"].IsNull())
{
if (!value["Status"].IsString())
{
return CoreInternalOutcome(Core::Error("response `RetentionExecution.Status` IsString=false incorrectly").SetRequestId(requestId));
}
m_status = string(value["Status"].GetString());
m_statusHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void RetentionExecution::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_executionIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ExecutionId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_executionId, allocator);
}
if (m_retentionIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RetentionId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_retentionId, allocator);
}
if (m_startTimeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "StartTime";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_startTime.c_str(), allocator).Move(), allocator);
}
if (m_endTimeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "EndTime";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_endTime.c_str(), allocator).Move(), allocator);
}
if (m_statusHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Status";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_status.c_str(), allocator).Move(), allocator);
}
}
int64_t RetentionExecution::GetExecutionId() const
{
return m_executionId;
}
void RetentionExecution::SetExecutionId(const int64_t& _executionId)
{
m_executionId = _executionId;
m_executionIdHasBeenSet = true;
}
bool RetentionExecution::ExecutionIdHasBeenSet() const
{
return m_executionIdHasBeenSet;
}
int64_t RetentionExecution::GetRetentionId() const
{
return m_retentionId;
}
void RetentionExecution::SetRetentionId(const int64_t& _retentionId)
{
m_retentionId = _retentionId;
m_retentionIdHasBeenSet = true;
}
bool RetentionExecution::RetentionIdHasBeenSet() const
{
return m_retentionIdHasBeenSet;
}
string RetentionExecution::GetStartTime() const
{
return m_startTime;
}
void RetentionExecution::SetStartTime(const string& _startTime)
{
m_startTime = _startTime;
m_startTimeHasBeenSet = true;
}
bool RetentionExecution::StartTimeHasBeenSet() const
{
return m_startTimeHasBeenSet;
}
string RetentionExecution::GetEndTime() const
{
return m_endTime;
}
void RetentionExecution::SetEndTime(const string& _endTime)
{
m_endTime = _endTime;
m_endTimeHasBeenSet = true;
}
bool RetentionExecution::EndTimeHasBeenSet() const
{
return m_endTimeHasBeenSet;
}
string RetentionExecution::GetStatus() const
{
return m_status;
}
void RetentionExecution::SetStatus(const string& _status)
{
m_status = _status;
m_statusHasBeenSet = true;
}
bool RetentionExecution::StatusHasBeenSet() const
{
return m_statusHasBeenSet;
}
|
def _create_vertical_csv(data, fname):
csv_file = open(fname, 'wb')
writer = csv.writer(csv_file)
for key, val in data.iteritems():
writer.writerow([key, val])
csv_file.close() |
Boingo Wireless has been chosen as exclusive Wi-Fi provider for the new Berlin Brandenburg Airport Willy Brandt.
The Boingo Wi-Fi services will be available as soon as the airport opens on March 17th 2013.
Berlin Brandenburg passengers will be able to access basic complimentary Wi-Fi services or upgrade to premium service for higher bandwidth activities.
This tiered service approach allows airports to serve the needs of both casual and power users while enabling ongoing investment in upgrades and expansion to support ever-increasing demand.
“Berlin Brandenburg Airport will offer its guests the most advanced amenities available,” said Ralf Kunkel of Flughafen Berlin Brandenburg GmbH.
Basic complimentary Wi-Fi services will allow passengers to engage in activities including email, posting to social networking sites and streaming audio, for up to 30 minutes per day after authenticating their identity with a valid credit or debit card.
Travellers can also access premium Boingo Wi-Fi, enabling the use of data intensive applications, video streaming and large file uploading, via any of the company’s Wi-Fi plans.
Wi-Fi access plans available to Berlin Brandenburg travellers will include Boingo Europe Plus, providing unlimited access at more than 200,000 hotspots throughout the Europe, Middle East and Africa region for €27.95 per month, and Boingo Global, providing flat rate access anywhere in the world for €49 per month.
Hourly and day passes will also be available for purchase. |
<reponame>joseiba/SysVetSoft
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib import messages
from django.db.models import Q
from django.core.paginator import Paginator
from django.views.decorators.csrf import csrf_exempt
from datetime import datetime, date
import json
from django.http import JsonResponse
from apps.utiles.views import (cargar_productos_vendidos, cargar_productos_comprados, cargar_ganacias_por_mes,
cargar_producto_vendido_mes, cargar_productos_comprado_mes, cargar_servicios_vendidos, cargar_vacunas_aplicadas)
from apps.utiles.models import (ProductoVendido, ProductoComprados,ProductoCompradoMes, ProductoVendidoMes,
GananciaPorMes, ServicioVendido, VacunasAplicadas)
from apps.configuracion.models import ConfiEmpresa
from apps.ventas.producto.models import Producto
from apps.ventas.mascota.models import Mascota, HistoricoFichaMedica
from apps.ventas.cliente.models import Cliente
today = datetime.now()
hoy = date.today()
meses = [{'mes': 'Enero', 'numero': 1}, {'mes': 'Febrero', 'numero': 2}, {'mes': 'Marzo', 'numero': 3},
{'mes': 'Abril', 'numero': 4}, {'mes': 'Mayo', 'numero': 5}, {'mes': 'Junio', 'numero': 6},
{'mes': 'Julio', 'numero': 7}, {'mes': 'Agosto', 'numero': 8}, {'mes': 'Septiembre', 'numero': 9},
{'mes': 'Octubre', 'numero': 10}, {'mes': 'Noviembre', 'numero': 11}, {'mes': 'Diciembre', 'numero': 12}]
# Create your views here.
@login_required()
@permission_required('reporte.view_reporte')
def reporte_producto(request):
cargar_productos_vendidos()
return render(request, 'reporte/producto/reporte_producto.html')
def reporte_prod_vendido(request):
query = request.GET.get('busqueda')
label_producto_ven = []
data_producto_ven = []
mensaje = ""
try:
if query != "":
produc_vendidos = ProductoVendido.objects.filter(Q(id_producto__nombre_producto__icontains=query))
else:
produc_vendidos = ProductoVendido.objects.all()
for pv in produc_vendidos:
label_producto_ven.append(pv.id_producto.nombre_producto)
data_producto_ven.append(pv.cantidad_vendida_total)
mensaje = "OK"
except Exception as e:
pass
response = {'label_producto_ven': label_producto_ven, 'data_producto_ven': data_producto_ven,'mensaje': mensaje}
return JsonResponse(response)
@login_required()
@permission_required('reporte.view_reporte')
def reporte_producto_comprados(request):
cargar_productos_comprados()
return render(request, 'reporte/producto/reporte_producto_comprado.html')
def reporte_prod_comprado(request):
query = request.GET.get('busqueda')
label_producto_con = []
data_producto_con = []
mensaje = ""
try:
if query != "":
produc_compra = ProductoComprados.objects.filter(Q(id_producto__nombre_producto__icontains=query))
else:
produc_compra = ProductoComprados.objects.all()
for pc in produc_compra:
label_producto_con.append(pc.id_producto.nombre_producto)
data_producto_con.append(pc.cantidad_comprada_total)
mensaje = "OK"
except Exception as e:
pass
response = {'label_producto_con': label_producto_con, 'data_producto_con': data_producto_con,'mensaje': mensaje}
return JsonResponse(response)
@login_required()
@permission_required('reporte.view_reporte')
def reporte_productos_vendido_mes(request):
context = {'meses': meses}
cargar_producto_vendido_mes()
return render(request, 'reporte/producto/reporte_producto_vendido_mes.html', context)
def get_producto_vendido_mes(request):
query = request.GET.get('busqueda')
label = []
data = []
mensaje = ""
try:
if query != "":
prod = ProductoVendidoMes.objects.filter(anho__icontains=str(hoy.year))
prod = prod.filter(Q(label_mes__icontains=query))
else:
prod = ProductoVendidoMes.objects.filter(anho=str(hoy.year))
for p in prod:
label.append(p.label_mes)
data.append(p.cantidad_vendida_total)
if len(data) > 0:
mensaje = "OK"
else:
mensaje = "NA"
except Exception as e:
pass
response = {'label': label, 'data': data,'mensaje': mensaje}
return JsonResponse(response)
def get_rango_mes_pro_vendido(request):
anho = request.GET.get('anho')
desde = request.GET.get('desde')
hasta = request.GET.get('hasta')
label = []
data = []
mensaje = ""
try:
pro = ProductoVendidoMes.objects.filter(anho=anho)
if pro.count() > 0:
for p in pro:
if int(desde) <= p.numero_mes and p.numero_mes <= int(hasta):
label.append(p.label_mes)
data.append(p.cantidad_vendida_total)
if len(data) > 0:
mensaje = "OK"
else:
mensaje = "NA"
except Exception as e:
pass
response = {'label': label, 'data': data,'mensaje': mensaje}
return JsonResponse(response)
@login_required()
@permission_required('reporte.view_reporte')
def reporte_productos_comprado_mes(request):
context = {'meses': meses}
cargar_productos_comprado_mes()
return render(request, 'reporte/producto/reporte_producto_comprado_mes.html', context)
def get_producto_comprado_mes(request):
query = request.GET.get('busqueda')
label = []
data = []
mensaje = ""
try:
if query != "":
prod = ProductoCompradoMes.objects.filter(anho=str(hoy.year))
prod = prod.filter(Q(label_mes__icontains=query))
else:
prod = ProductoCompradoMes.objects.filter(anho=str(hoy.year))
for p in prod:
label.append(p.label_mes)
data.append(p.cantidad_comprada_total)
if len(data) > 0:
mensaje = "OK"
else:
mensaje = "NA"
except Exception as e:
pass
response = {'label': label, 'data': data,'mensaje': mensaje}
return JsonResponse(response)
def get_rango_mes_pro_comprado(request):
anho = request.GET.get('anho')
desde = request.GET.get('desde')
hasta = request.GET.get('hasta')
label = []
data = []
mensaje = ""
try:
prod = ProductoCompradoMes.objects.filter(anho=anho)
if prod.count() > 0:
for p in prod:
if int(desde) <= p.numero_mes and p.numero_mes <= int(hasta):
label.append(p.label_mes)
data.append(p.cantidad_comprada_total)
if len(data) > 0:
mensaje = "OK"
else:
mensaje = "NA"
except Exception as e:
pass
response = {'label': label, 'data': data,'mensaje': mensaje}
return JsonResponse(response)
@login_required()
@permission_required('reporte.view_reporte')
def reporte_ganancias_mes(request):
context = {'meses': meses}
cargar_ganacias_por_mes()
return render(request, 'reporte/ganancias/reporte_ganancias_mes.html', context)
def get_ganancias_mes(request):
query = request.GET.get('busqueda')
label = []
data = []
mensaje = ""
try:
if query != "":
ganancias = GananciaPorMes.objects.filter(anho=str(hoy.year))
ganancias = ganancias.filter(Q(label_mes__icontains=query))
else:
ganancias = GananciaPorMes.objects.filter(anho=str(hoy.year))
if ganancias.count() > 0:
for ga in ganancias:
label.append(ga.label_mes)
data.append(ga.total_mes)
if len(data) > 0:
mensaje = "OK"
else:
mensaje = "NA"
except Exception as e:
pass
response = {'label': label, 'data': data,'mensaje': mensaje}
return JsonResponse(response)
def get_rango_mes_recaudacion(request):
anho = request.GET.get('anho')
desde = request.GET.get('desde')
hasta = request.GET.get('hasta')
label = []
data = []
mensaje = ""
try:
ganancias = GananciaPorMes.objects.filter(anho=anho)
if ganancias.count() > 0:
for ga in ganancias:
if int(desde) <= ga.numero_mes and ga.numero_mes <= int(hasta):
label.append(ga.label_mes)
data.append(ga.total_mes)
if len(data) > 0:
mensaje = "OK"
else:
mensaje = "NA"
except Exception as e:
pass
response = {'label': label, 'data': data,'mensaje': mensaje}
return JsonResponse(response)
@login_required()
@permission_required('reporte.view_reporte')
def reporte_stock_minimo(request):
return render(request, 'reporte/producto/reporte_stock_minimo.html')
def get_producto_minimo(request):
query = request.GET.get('busqueda')
prod_minimo = []
if query != "":
productos = Producto.objects.exclude(is_active="N").filter(Q(id__icontains=query) |Q(nombre_producto__icontains=query)).order_by('-last_modified')
productos = productos.exclude(servicio_o_producto="S")
productos = productos.exclude(producto_vencido="S")
else:
productos = Producto.objects.exclude(is_active="N").order_by('-last_modified')
productos = productos.exclude(servicio_o_producto="S")
productos = productos.exclude(producto_vencido="S")
for p in productos:
if p.stock_minimo >= p.stock_total:
prod_minimo.append(p)
total = len(prod_minimo)
_start = request.GET.get('start')
_length = request.GET.get('length')
if _start and _length:
start = int(_start)
length = int(_length)
page = math.ceil(start / length) + 1
per_page = length
prod_minimo = prod_minimo[start:start + length]
data =[{'id': p.id, 'nombre': p.nombre_producto, 'descripcion': p.descripcion, 'stock_minimo': p.stock_minimo ,'stock_total': p.stock_total} for p in prod_minimo]
response = {
'data': data,
'recordsTotal': total,
'recordsFiltered': total,
}
return JsonResponse(response)
@login_required()
@permission_required('reporte.view_reporte')
def reporte_stock_a_vencer(request):
return render(request, 'reporte/producto/reporte_stock_vencimiento.html')
def get_producto_vencimiento(request):
query = request.GET.get('busqueda')
prod_vencimiento = []
try:
confi = ConfiEmpresa.objects.get(id=1)
dias_compare = confi.dias_a_vencer
except Exception as e:
dias_compare = 30
if query != "":
productos = Producto.objects.exclude(is_active="N").filter(Q(id__icontains=query) |Q(nombre_producto__icontains=query)).order_by('-last_modified')
productos = productos.exclude(servicio_o_producto="S")
else:
productos = Producto.objects.exclude(is_active="N").order_by('-last_modified')
productos = productos.exclude(servicio_o_producto="S")
for p in productos:
if p.fecha_vencimiento is not None:
if rest_dates(p.fecha_vencimiento) <= dias_compare:
prod_vencimiento.append(p)
total = len(prod_vencimiento)
_start = request.GET.get('start')
_length = request.GET.get('length')
if _start and _length:
start = int(_start)
length = int(_length)
page = math.ceil(start / length) + 1
per_page = length
prod_vencimiento = prod_vencimiento[start:start + length]
data =[{'id': p.id, 'nombre': p.nombre_producto, 'descripcion': p.descripcion, 'stock_total': p.stock_total,
'fecha_vencimiento': p.fecha_vencimiento, 'dias_vencimiento': rest_dates(p.fecha_vencimiento)} for p in prod_vencimiento]
response = {
'data': data,
'recordsTotal': total,
'recordsFiltered': total,
}
return JsonResponse(response)
@login_required()
@permission_required('reporte.view_reporte')
def reporte_servicio_vendido(request):
cargar_servicios_vendidos()
return render(request, 'reporte/producto/servicio_vendido.html')
def get_servicio_vendido(request):
query = request.GET.get('busqueda')
label = []
data = []
mensaje = ""
try:
if query != "":
produc_vendidos = ServicioVendido.objects.filter(Q(id_producto__nombre_producto__icontains=query))
else:
produc_vendidos = ServicioVendido.objects.all()
for pv in produc_vendidos:
label.append(pv.id_producto.nombre_producto)
data.append(pv.cantidad_vendida_total)
mensaje = "OK"
except Exception as e:
pass
response = {'label': label, 'data': data, 'mensaje': mensaje}
return JsonResponse(response)
@login_required()
@permission_required('reporte.view_reporte')
def list_proximas_vacunas(request):
return render(request, 'reporte/mascota/list_proximas_vacunas.html')
def get_proximas_vacunas(request):
query = request.GET.get('busqueda')
ficha = []
try:
confi = ConfiEmpresa.objects.get(id=1)
dias_compare = confi.dias_alert_vacunas
except Exception as e:
dias_compare = 30
if query != "":
list_historico = HistoricoFichaMedica.objects.filter(Q(id_mascota__nombre_mascota__icontains=query)
|Q(id_mascota__id_cliente__nombre_cliente__icontains=query)
|Q(id_mascota__id_cliente__apellido_cliente__icontains=query))
else:
list_historico = HistoricoFichaMedica.objects.all()
for f in list_historico:
if f.fecha_proxima_aplicacion is not None:
if rest_dates(f.fecha_proxima_aplicacion) <= dias_compare:
ficha.append(f)
total = len(ficha)
_start = request.GET.get('start')
_length = request.GET.get('length')
if _start and _length:
start = int(_start)
length = int(_length)
page = math.ceil(start / length) + 1
per_page = length
ficha = ficha[start:start + length]
data =[{'id': f.id, 'cliente':try_exception_cliente(f.id_mascota.id_cliente), 'mascota': f.id_mascota.nombre_mascota,
'telefono': f.id_mascota.id_cliente.telefono, 'vacuna': f.proxima_vacunacion,
'fecha': f.fecha_proxima_aplicacion} for f in ficha]
response = {
'data': data,
'recordsTotal': total,
'recordsFiltered': total,
}
return JsonResponse(response)
@login_required()
@permission_required('reporte.view_reporte')
def reporte_vacunas_aplicadas(request):
cargar_vacunas_aplicadas()
return render(request, 'reporte/mascota/vacunas_aplicadas.html')
def reporte_get_vacunas_aplicada(request):
query = request.GET.get('busqueda')
label = []
data = []
mensaje = ""
try:
if query != "":
vacunas = VacunasAplicadas.objects.filter(Q(id_producto__nombre_producto__icontains=query))
else:
vacunas = VacunasAplicadas.objects.all()
for va in vacunas:
label.append(va.id_producto.nombre_producto)
data.append(va.cantidad_aplicadas)
mensaje = "OK"
except Exception as e:
pass
response = {'label': label, 'data': data,'mensaje': mensaje}
return JsonResponse(response)
def try_exception_cliente(id):
try:
cli = Cliente.objects.get(id=id.id)
if cli.ruc is None:
ruc_cedula = cli.cedula
else:
ruc_cedula = cli.ruc
return 'Nombre: ' + cli.nombre_cliente + " " + cli.apellido_cliente +'</br> ' + 'Ruc/Cédula: ' + ruc_cedula
except Exception as e:
return '-'
def rest_dates(fecha_vencimiento):
try:
fechaDate = datetime(today.year, today.month, today.day)
fecha_vencimiento_split = fecha_vencimiento.split('/')
fecha_vencimiento_compare = date(int(fecha_vencimiento_split[2]), int(fecha_vencimiento_split[1]), int(fecha_vencimiento_split[0]))
return (fecha_vencimiento_compare - hoy).days if (fecha_vencimiento_compare - hoy).days >= 0 else 0
except Exception as e:
return 0 |
The epigenetic regulators and metabolic changes in ferroptosis-associated cancer progression Ferroptosis, a novel form of regulated cell death, is different from other types of cell death in morphology, genetics and biochemistry. Increasing evidence indicates that ferroptosis has significant implications on cell death linked to cardiomyopathy, tumorigenesis, and cerebral hemorrhage to name a few. Here we summarize current literature on ferroptosis, including organelle dysfunction, signaling transduction pathways, metabolic reprogramming and epigenetic regulators in cancer progression. With regard to organelles, mitochondria-induced cysteine starvation, endoplasmic reticulum-related oxidative stress, lysosome dysfunction and golgi stress-related lipid peroxidation all contribute to induction of ferroptosis. Understanding the underlying mechanism in ferroptosis could provide insight into the treatment of various intractable diseases including cancers. Background Epigenetics, including DNA methylation, histone modifications, chromatin remodeling and noncoding RNAs such as long non-coding RNAs (lncRNAs) are important mechanisms in a cell's adaptability to a number of signals, conditions, and stressors. The reprogramming of gene expression contributes to tumorigenesis and cancer progression. The gene regulatory machinery and its chromatinassociated factors integrate environmental signals to modulate homeostatic responses. Numerous interplays between inter-metabolites and chromatin modification factors have recently been addressed. There is a significant alteration in cellular metabolism, which is believed to associate with chromatin-remodeling events in different cancers. These emerging viewpoints have biological relevance to cell fate such as cell death, disease and cancer. Ferroptosis, a recently defined type of regulated cell death (RCD), is different from other types of cell death in morphology, genetics and biochemistry. A great variety of human diseases including cancer have been linked to the abnormal function of ferroptosis, either in excessive induction or inhibition of it. The relationship between ferroptosis and oncogenic Ras has been identified. Ras contributes to the induction of ferroptosis through the RAS-BRAF (B-Raf proto-oncogene, serine/threonine kinase)-MAP2K/MEK (mitogen-activated protein kinase kinase)-MAPK/ERK (mitogen-activated protein kinase) pathway. Also, the role of tumor suppressor gene, tumor protein p53 (TP53) has been revealed in ferroptosis. TP53 represses the cystine/ glutamate transporter, solute carrier family 7 membrane 11 (SLC7A11), which regulates the expression of glutathione (GSH), therefore promoting ferroptosis. It is interesting to understand the interplay of epigenetic modifications and metabolic pathways in ferroptosis and tumorigenesis. Among various differences between normal cells and cancer cells, one distinct characteristic of cancer cells is the switch to an anaerobic metabolism even in the presence of oxygen, known as the Warburg effect. Observations in various cancers have indicated that there is a change of cellular metabolism with the significant changes of the tricarboxylic acid (TCA) cycle, a critical oxidative circulation in metabolism. Iron, a critical metallic element, is necessary for cell replication, metabolism and growth. The Fenton reaction is an important part of ferroptosis, in which the lipid peroxidation is mediated by carbon and oxygen centred radicals, initiated by free intracellular iron. Ferrous iron donates an electron in a reaction with hydrogen peroxide to produce the hydroxyl radical, a reactive oxygen species (ROS). This reaction not only damages lipids and proteins, but also causes oxidative damage to DNA. The release of free iron catalyzed by heme oxygenase (Hmox1) generates ROS in the mitochondrial membrane and leads to ferroptosis against doxorubicin (DOX)treated cardiomyopathy, indicating that inference of ferroptosis is feasible as a novel strategy for the treatment of diseases. Epigenetic regulators determine the gene transcription, cellular fate, developmental processes, and immune cell development of an organism. A panel of epigenetic regulators have recently been linked to the induction of ferroptosis and oncogenesis. These provide a more comprehensive and more exact mechanism in ferroptosistargeted tumor intervention. And the epigenetic controls in ferroptosis present a new direction for therapeutic intervention, which may help to overcome the current barrier in anti-cancer therapy. Here we discuss various epigenetic regulators and metabolic changes in respect to ferroptosis-mediated cancer cell progression. The discovery of ferroptosis and the location of ferroptosis The discovery of ferroptosis Ferroptosis is a form of RCD driven by iron-dependent lipid peroxidation. It was initially caught when seeking small molecular compounds for targeting RAS mutations, an oncogene. In 2003, a small molecule compound termed 'erastin' was identified, which selectively induced nonapoptotic cell death in both an ST-and RASG12Vdependent manner. In 2007, tests of the genotypeselective antitumor activity of erastin in various RAS mutation cancer cell lines confirmed that the RAS-BRAF-MAP2K/MEK -MAPK/ERK pathway and VDAC (voltage-dependent anion channel), mediating oxidative stress and mitochondria dysfunction, respectively, were required for erastin-induced cell killing. VDAC2 and VDAC3 can also be directly targeted by erastin. In 2012, the erastin-induced cell death was finally defined as an iron-dependent RCD and was named 'ferroptosis'. Erastin can inhibit the cystine/glutamate transporter system x c −, leading to cysteine starvation, GSH depletion, and consequently, oxidative death. The discovery of ferroptotic cell death provides insight into cancer research. Two main components contribute to ferroptotic cell death: increased free iron and accumulated lipid peroxides. Erastin-induced iron accumulation, which can be avoided by iron chelation, antioxidants or the genetic inhibition of cellular iron uptake, is conductive to ROS production, which results in lipid peroxidation and subsequent death. Free iron changes in the labile iron pool (LIP) occurs as a result of increased uptake, decreased storage, breakdown of iron-containing proteins, or malfunction of iron exporters. Almost all intracellular iron can be found in heme-containing and mitochondrial proteins, in the form of iron-sulfur clusters or stored as ferric iron (Fe 3+ ) by ferritin. Ferrous iron can react chemically with hydrogen peroxide to form hydroxyl radicals, which lead to an excessive accumulation of free iron after reacting with polyunsaturated fatty acid (PUFAs) to form lipid peroxides. Degradation of ferritin occurs via ferritinophagy, a form of autophagic degradation of ferritin by nuclear receptor coactivator 4 (NCOA4). Accordingly, genetic knockdown or overexpression of NCOA4 has been shown to prevent or trigger erastin-induced ferroptosis respectively. Taken together, meticulous regulation of heme, the mitochondria, and ferritin are all critical mediators of the LIP, lipid peroxide formation and subsequent ferroptosis. Ferroptosis is evidently different from apoptosis. It is not effective to block ferroptosis with inhibitors of caspase, cathepsin or calpain proteases, RIPK1 (receptorinteracting serine/threonine kinase 1), PPID/cyclophilin D, lysosomal function or autophagy or the genetic inhibition of apoptosis effectors. However, to some extent, ferroptosis is a type of autophagy-dependent cell death (ADCD) in some cancer cells, resulting from tumor heterogeneity or potential drug stability. Further studies argue a crosstalk between ferroptosis and other established cell death modalities including apoptosis and necroptosis. For example, fibroblasts that are MLKL (mixed lineage kinase domain like pseudokinase)-deficient and necroptosis-resistant are more vulnerable to erastin-induced ferroptosis. Erastin can also induce apoptosis in lung (e.g. A549) and colorectal cancer cell lines (e.g., HT-29, DLD-1, and Caco-2) via the activation of TP53 and mitochondrial oxidative injury. More recently, the major pro-ferroptosis activity of erastin has been linked to directly blocking system x c −. These findings raise questions about the theoretical foundations of ferroptosis, and the interplay between ferroptosis and apoptosis. The mitochondrion is a crucial player in ferroptosis induced by cysteine deprivation Mitochondria are vital organelles involved in energy metabolism, cell signaling, and cell death pathway regulation including ferroptosis. Moreover, ferroptosis is morphologically depicted by condensation of mitochondria, reduction of mitochondrial cristae, and decrease in mitochondrial size. It appears reasonable that the mitochondrion is indeed a crucial player in ferroptosis induced by cysteine deprivation. However, it remains highly controversial whether or not mitochondria are an important component in ferroptosis. Ferrostatin-1 is a potent and selective inhibitor of ferroptosis, which accumulates in specific organelles including lysosomes, mitochondria, and endoplasmic reticulum (ER), but not the plasma membrane or nucleus. Nevertheless, mitochondria are not indispensable for ferroptosis or ferroptosis rescue by Ferrostatin-1. Further work is needed to excavate certain statuses of mitochondria in ferroptosis. Mitochondria play a vital role in ferroptosis induced by cysteine deprivation but not by glutathione peroxidase-4 (GPX4) inhibition, the most downstream of the ferroptosis pathway. Cysteine deprivation leads to mitochondrial membrane hyperpolarization and lipid peroxide accumulation. Inhibition of the mitochondrial TCA cycle or electron transport chain (ETC) mitigates mitochondrial membrane hyperpolarization, lipid peroxide accumulation, and ferroptosis. Glutaminolysis (a major source of anaplerosis) is involved in ferroptosis through ferroptotic functioning of the TCA cycle. Importantly, loss of fumarate hydrase function, a TCA cycle component and tumor suppressor, confers resistance to cysteine-deprivation induced ferroptosis. Therefore, both mitochondrial TCA cycle and the ETC action are dispensable to potent ferroptosis. The endoplasmic reticulum (ER) is involved in ferroptosis Containing more than half of all lipid bilayers in any cell, ER is the source of lipids for most membranes in other organelles and may also be critical to ferroptosis initiation. The ER lumen is an oxidative environment and may initiate ferroptosis as a consequence of oxidative stress. System x c − is an antiporter that imports one molecule of cystine in exchange for one molecule of glutamate. Small molecule inhibition of system x c −, such as erastin and its analogs, specifically inhibit cystine uptake via system x c −, which leads to ER stress,triggering ferroptosis in a variety of cellular contexts. Upregulation of ER stress markers such as CHAC1 (ChaC, cation transport regulator homolog 1), ATF4 (activating transcription factor 4) and phosphorylation of eIF2 have been observed in ferroptosis. Ferroptotic agents erastin and artesunate (ART) can induce ER stress and promote p53 upregulated modulator of apoptosis (PUMA) expression via C/EBP-homologous protein (CHOP), whereas ER stress response mediated by the PERK (PKR-like ER kinase)-eIF2 (eukaryotic initiation factor 2)-ATF4 pathway is involved in regulation of the expression of several target genes such as CHOP. ATF4 is also involved in upregulation of the heat shock 70 kDa protein 5 (HSPA5, also termed GRP78 or BIP), a member of the molecular chaperones expressed primarily in the ER, resulting in the inhibition of lipid peroxidation in ferroptosis by directly protecting against GPX4 degradation. These ER-related regulators significantly contribute to ferroptosis. In addition, ER also participates in ferroptosis rescue. The hypothesis that the location in which ferrostatin exerts its antiferroptotic action is the ER, is supported by the increased potency of ferrostatin-1 in postmitophagy cells, which shows greater ER abundance. Relevant regulators and pathways have been discussed, while the link of ferroptosis and the ER requires further identification ( Fig. 1). Ferroptosis is a lysosomal cell death process Lysosomes contain hydrolases (e.g. the cathepsin family) for the degradation and recycling of essential nutrients to maintain homeostasis through various ways, including ferroptosis. Increasing evidence has demonstrated that lysosomal activity is involved in the induction of ferroptosis. Interestingly, ferroptosis as a lysosomal cell death process requires activation of signal transducer and activator of transcription 3 (STAT3)-mediated cathepsin B (mediator in lysosomal cell death) expression. STAT3 promotes erastin-induced ferroptosis through activation of lysosomal cell death in human pancreatic ductal adenocarcinoma (PDAC) cell lines. Meanwhile, in PDAC, erastin promotes, and sorafenib inhibits STAT3 phosphorylation, triggering increased expression of cathepsin B via the MEK-ERK pathway. The process above renders more MDA (malondialdehyde), one of the final products of lipid peroxidation. Taken overall, STAT3-meidated cathepsin B expression is required for ferroptosis with increased oxidative injury in PDAC cells through induction of lysosomal cell death. Another pathway occurring in lysosomes takes part in ferroptosis as well. Chaperone-mediated autophagy (CMA), a cellular lysosome-mediated degradative mechanism, is involved in the execution of ferroptosis. The activation of ferroptosis increases the levels of lysosome-associated membrane protein 2a (Lamp-2a) known to be associated with heat shock cognate 70 (HSC70) to promote CMA and the degradation of GPX4. HSP90 associates with Lamp-2a at the lysosomal membrane and regulates the functional dynamics of the Lamp-2a complexes for CMA activation. Accordingly, 2-amino-5-chloro-N,3-dimethylbenzamide (CDDO), as a potent inhibitor of ferroptosis, can inhibit HSP90 to block GPX4 degradation, lipid peroxidation, ROS accumulation and cell death consequently. Interestingly, only lysosome pathway inhibitors could inhibit degradation of GPX4 induced by glutamate or erastin rather than proteasome inhibitors, suggesting that degradation of GPX4 might be located in the lysosome. Noticeably, HSP90 is important for mediating the activation of RIPK1 kinase in both necroptosis and RIPK1-mediated apoptosis (RDA), which suggests that HSP90 may represent a common regulatory nodal between necroptosis and ferroptosis. Collectively, CMA regulated by HSP90, CDDO, HSC70 and Lamp-2a promotes the degradation of GPX4 and is ultimately involved in ferroptosis (Fig. 1). Golgi stress involved in ferroptosis Golgi stress plays a role in ferroptosis in human cells. Ferroptosis can be triggered by several Golgi-disrupting compounds such as AMF-26, BFA, GCA, and AG1478/ tyrphostin. Accordingly, diverse ferroptosis-modulating compounds have protective effects on Golgi morphology and functionality after treatment with the above Golgi stressors. Inhibitors of ferroptosis protect cells from Golgi dispersal and inhibit protein secretion in response to several Golgi stress agents. Erastin at sublethal concentrations to cells is sufficient to alleviate Golgi stress-induced lipid peroxidation. The transsulfuration pathway may play a compensatory role for cysteine provision following oxidative challenge as a mechanism to limit ferroptosis. When concurrently applied to cells with a pharmacological inhibitor of the transsulfuration pathway, the pro-survival effects of a low dose of erastin in combination with Golgi stressors can be abolished. The Golgi apparatus is involved in cellular redox control and prevents ferroptosis (. Effects of signal transduction pathways on ferroptosis There are two central biochemical events, intracellular iron accumulation and lipid peroxidation, leading to ferroptosis. An integrated signaling network plays a vital role in ferroptosis by mediating intracellular iron accumulation, lipid peroxidation and ROS generated by extracellular or intracellular stimuli. Iron-mediated oxidative stress Iron is a trace mineral essential for the functioning of the human body. There are two types of iron existing in the body: heme iron and non-heme iron. Ferric iron (Fe 3+ ), the main nonheme iron, can be absorbed by intestinal epithelial cells in the duodenum and upper jejunum, which then binds to transferrin (TF). Fe 3+ circulates with TF and is then imported into cells Fig. 1 Known function of organelles in ferroptosis. In the mitochondrion, glutamine is oxidatively phosphorylated, contributing to ROS production. The ER stress response is mediated by the PERK-eIF2-ATF4 pathway involved in GPX4 degradation, ultimately, inhibiting oxidative injury. In the lysosome, STAT3-mediated cathepsin B expression is required for ferroptosis via the MEK-ERK pathway. Meanwhile, chaperone-mediated autophagy (CMA) regulated by HSP90, CDDO, HSC70 and Lamp-2a promotes the degradation of GPX4. In the Golgi apparatus, Golgi-disrupting compounds enable inhibition of ARF1, an inhibitor of GSH and ACSL4, and activator of SLC7A11, leading to increased ROS through the membrane protein transferrin receptor (TFRC), subsequently reduced to Fe 2+ in endosomes. Next, Fe 2+ is released from the endosome into a LIP in the cytoplasm via SLC11A2/DMT1 (solute carrier family 11 member 2/ cytosine-C5 specific DNA methyltransferase). Excess iron can be stored in ferritin or exported into the circulation in the blood stream through the iron efflux pump SLC11A3/ferroportin (solute carrier family 11 member 3). Iron absorption and metabolism have been targeted in the treatment of cancers, while excessive iron can cause tissue injury and increase the risk of developing cancers. The Fenton reaction, catalyzed by iron and responsible for iron biotoxicity, can produce hydroxyl radicals that damage cellular proteins, lipids, and DNA. For example, iron-based nanoparticles can release ferrous and ferric iron in acidic lysosomes, inducing ferroptosis, ultimately suppressing tumor growth. It is evident that iron performs not only physiological but also pathological functions. Iron uptake, export, utilization, and storage are reprogrammed by ferroptosis. The intracellular levels of Fe 3+ are upregulated in response to ferroptosis activators. Moreover, ferroptosis can be inhibited by preventing cellular iron overload by knockdown of TFRC, inhibiting mitochondrial iron accumulation by the upregulation of the mitochondrial iron exporter CISD1 (CDGSH iron sulfur domain 1) and increasing the storage of iron via the upregulation of cytosolic and mitochondrial ferritin [35,. The suppression of IREB2 (iron responsive element binding protein 2), a transcription factor, limits ferroptotic cancer cell death by regulating iron metabolism. In contrast, blockade of iron export by knockdown of SLC11A3 promotes erastin-induced ferroptosis in neuroblastoma cells. Iron metabolism affects ferroptosis by mediating oxidative stress, reflecting the physiological minitrim of the ferroptotic response. Antioxidant events also play a pivotal role in ferroptosis. Antioxidant defenses counteracting ferroptosis may be divided into four categories: 1) the prevention of Fenton reactions, such as through iron storage ; 2) the scavenging or eliminating of free radicals, such as by the production of glutathione (GSH) ; 3) the repair of damage from toxic oxidation products, such as by the activation of GPX4 ; and 4) adaptive responses, such as upregulation of NFE2L2/NRF2 (nuclear factor, erythroid 2 like 2)-dependent antioxidant protein expression and activation of heat shock response. Overall, it is important to understand the definite relationship between lipid peroxidation pathways and antioxidant systems so as to distinguish ferroptosis from other types of RCD. p53-mediated ferroptosis p53 is an essential regulator of cell growth, metabolism, differentiation and death. TP53 (tumor protein p53) is famous for its function as a tumor suppressor. In recent years, a mass of research has provided evidence of its pivotal role in metabolic functions, cell apoptosis, growth arrest, and indicates that p53 plays a bidirectional role in controlling ferroptosis. p53 can promote ferroptosis to selectively deplete cancer cells via several approaches. Spermidine/spermine N1-acetyltransferase 1 (SAT1), a transcription target of p53, leads to lipid peroxidation and ferroptosis upon ROS stress. In this process, ALOX15 plays a critical role but not GPX4 or SLC7A11. Through inhibiting the expression of SLC7A11, an acetylation-resistant TP53 3KR (K117R, K161R, K162R), can indirectly suppress the absorbency of cystine, which plays a key role in GSH biosynthesis. Moreover, depletion of GSH leads to lipid peroxidation, which then triggers ferroptosis. Furthermore, the loss of K98 acetylation on p53 4KR (K98R + K117R + K161R + K162R) compared to p53 3KR results in the loss in ability to induce ferroptosis, which indicates that acetylation is pivotal for p53-mediated ferroptosis. p53 targets gene GLS2 (glutaminases2), relating to glutaminolysis, also involved in ferroptosis. SOCS1 (suppressor of cytokine signaling 1) can sensitize cells to ferroptosis by regulating the expression of some target genes of p53. SOCS1 exerts its function through regulating phosphorylation and stabilization of p53. Interestingly, SLC7A11 and SAT1 are both found as the SOCS1-dependent p53 targets, indicating that the SOCS1-p53 axis is involved in the ferroptosis pathway. On the other hand, p53 also suppresses ferroptosis in other cancer cells (e.g. Colorectal cancer). Loss of p53 prevents accumulation of dipeptidyl-peptidase-4 (DPP4) in the cell nucleus, and contributes to the formation of a complex of DPP4 and NOX1 (NADPH oxidase 1) on the plasma-membrane, thus enhancing lipid peroxidation, which results in ferroptosis. In contrast, by blocking DPP4 activity in a transcription-independent manner, the formation of DPP4-TP53 complex limits erastininduced ferroptosis. In addition, stabilization of wild-type p53 postpones the onset of ferroptosis and CDKN1A (encoding p21CIP1/WAF1) is required in this process. This delay is also related to slower depletion of intracellular GSH and a reduced accumulation of toxic lipid-ROS. Several other molecules such as lncRNAs, and single-nucleotide polymorphisms can also help p53 play a dual role in ferroptosis. For example, the Pro47Ser polymorphism (S47) can restrain erastin-induced GLS2 expression and ferroptosis. However, the exact mechanisms of the dual functions of p53 in ferroptosis have not been clearly uncovered. The effects of p53 and its epigenetic regulators in ferroptosis may contribute to a potential target in ferroptosis related diseases. NFE2L2/ NRF2-mediated ferroptosis Many pathological conditions are linked to imbalances in redox homeostasis. It is becoming increasingly apparent that the accumulation of lipid peroxides has an important role in multiple diseases. The transcription factor nuclear factor erythroid 2-related factor 2 (NRF2/ NFE2L2) is a key regulator of the cellular antioxidant response, controlling the expression of genes that counteract oxidative and electrophilic stresses as well as ferroptosis. In liver cancer cells, ferroptosis activators (e.g., erastin, sorafenib) could enhance the expression of SQSTM1/ p62 (sequestosome 1), a competitive inhibitor of KEAP1 (Kelch-like ECH-associated protein 1). The levels of NRF2 are kept basally low by three different E3ubiquitin ligase complexes: Kelch-like ECH-associated protein 1-Cullin 3-Ring box 1 (KEAP1-CUL3-RBX1), Sphase kinase-associated protein 1-Cullin1-Rbx1/-transducin repeat-containing protein (SCF/-TrCP), and synoviolin/Hrd1. Therefore, ferroptosis activators can induce NFE2L2 protein stabilization and its transcriptional activity. SQSTM1 or p62 is a scaffold protein with multiple functions that can be used as a cargo receptor to eliminate intracellular proteins (e.g., KEAP1) through autophagy. Depending on the clearance of autophagic cargos, SQSTM1 plays a dual role in both promoting cell survival and cell death. It is unclear whether there is an interconnection between SQSTM1-mediated autophagy and SQSTM1-NFE2L2-regulated ferroptosis. In addition, the upregulation of metallothionein MT-1G (metallothionein-1G) is strongly associated with sorafenib resistance in human HCC cells, the molecular mechanisms of which involve the inhibition of ferroptosis. Metallothioneins (MTs) are low molecular weight and cysteine-rich proteins that are highly induced in response to different environmental stressors, including metal ions. MT-1G is identified as a downstream target of NFE2L2 that contributes to ferroptosis resistance in response to sorafenib. NRF2 together with MafG (v-maf avian musculoaponeurotic fibrosarcoma oncogene homolog) can activate transcription of NQO1 (quinone oxidoreductase-1), HO1 (heme oxygenase-1), and FTH1 (ferritin heavy chain-1), which have the ability to inhibit ferroptosis. HO1 plays a dual role in the inhibition or promotion of ferroptosis, depending on the cellular redox status. The downregulation of HO1 in renal proximal tubule cells of mice promotes ferroptosis, and high levels of HO1 promotes Bay-induced ferroptosis through NRF2-SLC7A11-HO1 pathway. It is evident that NRF2 participates and plays an essential role in ferroptosis through the different pathways explained. ECAD-induced hippo signaling pathway to inhibit ferroptosis A group test of human epithelial cancer cells revealed that ferroptosis is dependent on cell density, which increases the interaction between cells. E-cadherin (ECAD) plays an important part in the mediation of intercellular contact in epithelial cells. ECAD expression is positively associated with the level of cell confluence, and promotes intercellular dimerization, therefore, driving the Hippo signaling pathway through mediating NF2. Activation of tumor suppressor NF2 downregulates the expression of an E3 ubiquitin ligase (CRL4-DCAF1), which promotes the oligoubiquitylation of the kinase Warts (LAST1/2) and leads to their degradation. As a result, NF2 reverses the inhibition of kinase activity LAST1/2, which induces the phosphorylation of an oncogenic transcriptional co-activator YAP. This removes YAP from the nucleus, thereby suppressing substrates of YAP, including TFRC1 and acyl-CoA synthetase long chain family member 4 (ACSL4). Collectively, the activation of the cadherin-NF2-Hippo-YAP signaling axis, a pathway dependent on cell density, blocks ferroptosis as a result. Paradoxically, lymphocyte-specific helicase (LSH) inhibits ferroptosis, and downregulates the expression of EMT-related genes including, E-cadherin and ZO-1 to promote cancer progression in IKK-mediated way. In addition, other substrates of YAP also contribute to the induction of ferroptosis, however the co-overexpression of TFRC and ACSL4 did not restore ferroptosis in confluent cells to the level of that in sparse cells. Mutation of the E-cadherin-NF2-Hippo-YAP signaling axis in various cancers could provide new ideas for current treatments in terms of ferroptosis. Regulation of metabolic pathways in ferroptosis VDAC sensitize cells to ferroptosis Erastin exhibits great lethal potential in human tumor cells containing mutations in the oncogenes HRAS, KRAS or BRAF. In response to erastin, the mitochondria changes in morphology, structure, and function. In the mitochondria, erastin acts through VDACs (voltage-dependent anion channels) found in the outer mitochondrial membrane. Depletion of VDAC2 and VDAC3 reduces erastin harm in RASmutated cancer cells, indicating that these mitochondrial membrane proteins are important for ferroptosis. However, whether VDAC2 and VDAC3 are indispensable to ferroptosis requires further investigation. Cells are sensitive to ferroptosis activators despite depletion of mitochondrial DNA. Some other compounds inducing mitochondrial ROS seem not to induce ferroptosis. These facts all fail to support the significance of mitochondria in ferroptosis. Nevertheless, ferroptosis induction is associated with mitochondrial dysfunction. In neuronal cells, erastin-induced ferroptosis was accompanied by BID (BH3 interacting domain death agonist) transactivation of the mitochondria, resulting in the loss of mitochondrial membrane potential, enhanced fragmentation, and reduced ATP levels. The knockout of BID by CRISPR/Cas9 helps the mitochondria retain its morphology and function, and mediates neuroprotective effects against ferroptosis. Additionally, the expression of VDAC1 could be decreased by the bromodomain inhibitor (JQ1), and bromodomain-containing protein 4 (BRD4) is indicated to be a regulator of VDAC1, providing a novel connection between VDAC and epigenetic regulation. In sum, the role of VDACs in ferroptosis and the conditions under which ferroptosis is promoted requires further investigation. − ) plays a key role in ferroptosis as a common target System x c − is an amino acid antiporter, consisting of the functional subunit, SLC7A11 (solute carrier family 7 member 11), and the regulatory subunit,SLC3A2 (solute carrier family 3 member 2), which imports the cystine into cells with a 1:1 counter-transport of glutamate. The synthesis of GSH, a main endogenous antioxidant, depends on the activity of GCL (glutamate-cysteine ligase). The inhibition of system x c − inhibits its activity, thus leading to the depletion of intracellular GSH, contributing to higher levels of lipid peroxide, resulting in ferroptosis. The upregulation of system x c − expression may be involved in chemoresistance and tumor growth. In breast cancer cells, in order to respond to ROS, System x c − is upregulated to biosynthesize more GSH. The light chain subunit of system x c −, xCT, is regulated by NRF2. ARF (ADP-ribosylation factor) can restrain the overexpression of NRF2, whose down targets include SLC7A11. Thus, ARF expression sensitizes cells to ferroptosis. Several studies have revealed the relationship between small molecule and system x c −. Erastin binds to system L (including SLC7A5/SLC3A2 complex) especially SLC7A5 (solute carrier family 7 member 5), a major part to transport neutral amino acids. p53 3KR is an acetylationdefective mutant unable to induce cell-cycle arrest, apoptosis and senescence, however, retaining its ability to inhibit SLC7A11 and indirectly reduce the activity of system x c −. The BECN1 (beclin 1) network, an important protein in the regulation of autophagy, also plays a vital role in ferroptosis. AMP-activated protein kinase (AMPK) mediates the phosphorylation of BECN1 at Ser90/93/96, and then BECN1 combines with SLC7A11, blocking its activation. This indicates a potential link between autophagy and ferroptosis. Activation transcription factor 3 (ATF3), a member of the ATF/CREB family of transcription factors, is highly expressed when cells are under stress, including DNA damage and oxidative stress. ATF3 puts cells to a state where cells are sensitive to erastin-induced ferroptosis. This is done by ATF3 through binding to the SCL7A11 promoter at BS-1/BS-2 sites and repressing the expression of SLC7A11. All abnormal regulations of the molecule above can result in the decrease of cysteine in cells, leading to lipid peroxidation accumulation, resulting in ferroptosis. Various pathways have been found in mediating ferroptosis. Of note, some of the pathways take SCL7A11 as their common target which indicates that SCL7A11 plays a key role in ferroptosis. GPX4 inhibits ferroptosis GPX4 is a member of GSH peroxidase that can reduce lipid peroxides in cells and help cells survive. Loss of activity of GPX4 promotes ferroptosis. RSL3(RAS-selective lethal 3), a ferroptosis inducer, has a critical role in GPX4-regulated ferroptosis. Unlike erastin that promotes ferroptosis either by downregulating GSH or via the VDAC2/VDAC3 mechanism, RSL3 can covalently bind to a nucleophilic active site "selenocysteine" of GPX4 depending on its electrophilic chloroacetamide and subsequently do harm to the activity of GPX4. FINO2 (endoperoxide-containing 1,2-dioxolane) can also initiate ferroptosis through GPX4 inactivation. FINO2 requires both an endoperoxide and a nearby hydrophilic head to induce ferroptosis. However, the exact relationship between GPX4 and FINO2 remains an enigma. Depletion of GPX4 increases phospholipid hydroperoxide and promotes lipoxygenase-mediated lipid peroxidation, which ultimately leads to ferroptosis. The abnormal expression of GPX4 is shown to link with various human diseases including cancer and chronic disease. GPX4 is higher expressed in cancer tissues than normal and is negatively associated with prognosis of patients, through hypomethylation in the upstream of GPX4, and active epigenetic modifications at H3K4me3 (trimethylation of histone H3 at lysine 4) and H3K27ac (acetylation of histone H3 at lysine 27) in the transcription start site of GPX4, indicating that high level of GPX4 in cancer may resulted from epigenetic regulation. In addition, GPX4 may potentially be involved in translation of protein, mitochondrial respiratory chain complex I assembly, electron transport oxidative phosphorylation, nonalcoholic fatty liver disease, and metabolic pathways. It has been found that GPX4 depletion-induced ferroptosis occurs in chronic obstructive pulmonary disease (COPD) pathogenesis under cigarette smoke exposure. In addition, NCOA4 (nuclear receptor coactivator 4) mediates ferritin degradation and contributes to disorder of iron homeostasis in COPD lungs, which indicates NOCA4 may involve in ferroptosis. However, the direct link between GPX4 and NCOA4 in terms of protein expression levels remains unknown. It is worth noting that GPX4 can be a latent therapeutic target in some hard-to-treat cancers such as clear-cell carcinomas (CCCs) that have an intrinsic vulnerability to GPX4 inhibition-induced ferroptosis. In renal CCCs, the HIF-2-HILPDA axis contributes to the sensitivity of CCCs to GPX4 inhibition-induced ferroptosis. HIF-2 (hypoxia inducible factor-2) activates the expression of hypoxia inducible lipid droplet associated protein (HILPDA), which has the ability to selectively enrich PUFA-TAGs/phospholipids over SFA/MUFA (saturated fatty acids/monounsaturated fatty acids)-lipids and repress adipose triglyceride lipase (ATGL) activity, which enriches polyunsaturated lipids in cells, the downstream of GPX4. These findings provide a new perspective into the treatment of diseases including cancer involving ferroptosis. Both glutamine and cysteine are important in ferroptosis Glutamine and cystine are two amino acids required for glutathione (GSH) synthesis, which prevents ferroptosis caused by impaired lipid metabolism including attenuated the accumulation of ROS. Clearly, cysteine deprivation leads to ferroptosis. Many molecules are involved in the regulation of this metabolic pathways. Glutamine (Gln) is an intermediate in the detoxification of ammonia and a well-known nutrient used by tumor cells. SLC38A1 (solute carrier family 38 member 1) and SLC1A5 (solute carrier family 1 member 5) are glutamine transporters that mediate transportation of glutamine through biological membranes. L-Gln is one of the most important amino acids in the body, as it is a nitrogen source in the body and plays an essential role in the TCA cycle. The absorption of Gln mainly depends on SLC38A1 and SLC1A5. MIR137 (microRNA 137) functions as a negative regulator by downregulating SLC1A5, resulting in the dysfunction of glutamine transporter. The decrease of Gln may be closely related to cystine starvation in cells, thus contributing to ferroptosis as mentioned above. Importantly, loss of function of fumarate hydratase, a tumor suppressor and TCA cycle component, confers resistance to cysteine-deprivation-induced ferroptosis. In addition, glutaminases (GLS) turn Gln into glutamate (Glu). Glu generated by GLS2-mediated glutaminolysis contributes to form the production of ketoglutarate, which may induce ferroptosis. Blockage of glutaminolysis had the same inhibitory effect, which was counteracted by supplying downstream TCA cycle intermediates. Glutamine and cystine, two pivotal components which are involved in various metabolic pathways, are also significant to ferroptosis. Many molecules and proteins such as MIR137 and GLS2 can regulate their expression, which indicates that glutamine and cystine may be a latent common pathway for ferroptosis. Peroxidation of polyunsaturated fatty acids are tightly linked to ferroptosis Lipoxygenases including ALOXE3, ALOX5, ALOX12, ALOX12B, ALOX15 and ALOX15B, are a family of non-heme iron enzymes involved in generating leukotrienes from arachidonic acid (AA). ALOX12 has an essential function in p53-dependent ferroptosis. p53 activates ALOX12 function by transcriptionally repressing the expression of SLC7A11, leading to ALOX12-dependent ferroptosis upon ROS stress. In addition, polyunsaturated fatty acids (PUFEs) are found to be involved in ferroptosis. When lipid peroxides accumulate to a lethal level in cells, ferroptosis occurs. A study showed that erastin-induced ferroptosis was rescued by silencing either ALOX15B or ALOXE3 in BJeLR and HT-1080 cells. This indicates that in several conditions such as GSH deficiency, lipoxygenases are required for ferroptosis. ALOX5-derived metabolites are related to ferroptosis because NAC (N-acetylcysteine) can counteract toxic lipids generated by nuclear ALOX5 and prevent ferroptosis in mice. PUFA oxidation by lipoxygenases is also essential in GPX4 inhibition, which results in ferroptosis. Clearly, lipoxygenases are tightly related to ferroptosis, however, the exact mechanism of lipoxygenases and their metabolites involved in ferroptosis needs further investigation. ACSL4 is linked with ferroptosis Human ACSL family, including ACSL1, ACSL3, ACSL4, ACSL5, and ACSL6, expressed on the endoplasmic reticulum and mitochondrial outer membrane, can catalyze fatty acids to form acyl-CoAs. ACSL4 has a preference for long polyunsaturated fatty acids, such as AA and AdA (adenosine deaminase). This proves that only ACSL4 is related to ferroptosis induced by GPX4 inhibitors or erastin. Overexpressing ACSL4 promotes ferroptosis. On the contrary, knocking down ACSL4 prevents ferroptosis and inhibits ferroptosis induced by GPX4 depletion. ACSL4 enriches cellular membranes with long polyunsaturated 6 fatty acids, promoting the production of 5-hydroxyeicosatetraenoic acid (5-HETE), ultimately causing ferroptosis. Interestingly, miRNA-17-92 might protect endothelial cells from ferroptosis through targeting A20(zinc lipoprotein A20, also known as tumor necrosis factor alpha inducible protein 3) that regulates ACSL4 expression directly, indicating that this microRNA protects cells from ferroptosis. In addition, the inhibition of ferroptosis can ameliorate in situ and remote organ injury, in detail, ACSL4 is induced after ischemia and is involved in ischemia/reperfusion injury in the intestine. Transcription factor Sp1 could upregulate ACSL4 expression by directly binding to the ACSL4 regulatory region. To sum up, ACSL4 is another essential way regulating ferroptosis. MicroRNA mediating ACSL4 plays an indispensable role in this pathway, however, the more details in this pathway need more investigation. The participation of NFS1 and ISCs in ferroptosis Iron-sulfur clusters(ISCs)function as protein co-factors in a variety of enzymes which are sensitive to oxidative damage. NFS1 (cysteine desulfurase) is an enzyme that is capable of gaining sulfur from cysteine to synthesize ISCs. ISCs are found in mitochondria and play a key role in electron transfer. Suppression of NFS1 cooperating with inhibition of cysteine transport can trigger ferroptosis. The lack of ISCs leads to the ironstarvation response, and in combination with the inhibition of GSH biosynthesis, induces ferroptosis. These results show the participation of NFS1 and ISCs in ferroptosis. To sum up, numerous molecules and metabolic pathways are involved in the regulation of ferroptosis. Lipid peroxidation is their common pathway. Studies on lipid peroxidation induced by cysteine reduction and GPX4 reduction are the most extensive, which can both inhibit GSH from converting to oxidized glutathione. The depletion of cysteine decreases the synthesis of GSH; however, the depletion of GPX4 prevents the chemical reactions GSH involved. System x c − promotes the synthesis of GSH by increasing the absorption of cysteine, and molecules such as ATF3 and Glu promote ferroptosis by inhibiting this complex. Unlike cysteine regulated by system x c −, GPX4 is mediated by other pathways such as HIF-2-HILPDA axis. In addition, ACSL4 which is involved in A20-ACSL4 axis and can alter the lipid components of cell membranes is another important regulator of ferroptosis. Of note, epigenetic regulation like histone modifications and microRNA-mediated gene silencing also plays a vital role in ferroptosis. All in all, the metabolic regulation of ferroptosis is an intricate network. (Fig. 2). The epigenetic regulators in ferroptosis Epigenetic regulators including DNA methylation, histone modifications, and noncoding RNAs, determine the gene transcription, cellular fate, developmental processes, and immune cell development of an organism. Ferroptosis is a form of non-apoptotic cell death characterized by the iron-dependent overproduction of lipid hydroperoxides. Whether nuclear events participate in the regulation of ferroptosis is largely unknown. Studies in recent years have focused on the epigenetic mechanism of ferroptosis. Here, we list some critical epigenetic effectors in ferroptosis regulation. lncRNA acts as an epigenetic regulator to promote ferroptosis lncRNAs are a group of non-coding RNAs that consist of more than 200 nucleotides but possess low or no proteincoding potential. They can interact directly with DNA, mRNA, or proteins to regulate chromatin modification or structure, transcription, splicing, and translation, resulting in the alteration of a variety of physiological and pathological processes such as cell proliferation, differentiation and RCD. As for RCD, remarkably, it has been found that lncRNAs have a place in the cancer cell progression in ferroptosis. For instance, lncRNAs participate in the development and progression of non-small cell lung cancers (NSCLC) through mediating ferroptosis. RNA sequencing in NSCLC cells showed that SLC7A11, a key gene associated with ferroptosis through its role in controlling iron concentrations, can be downregulated by XAV939 (an inhibitor of NSCLC), as the target genes of lncRNAs, and suppress the development of NSCLC via ferroptosis-mediated pathways. The cytosolic lncRNA P53RRA promotes ferroptosis by activating the p53 pathway and affecting transcription of several metabolic genes. P53RRA increases erastin-induced growth inhibition, the intracellular concentrations of iron and lipid ROS in NSCLC cells consistent with its role in ferroptosis. P53RRA regulates p53 target genes in the cytoplasm by displacing p53 from a G3BP1 complex through its interaction with Ras-GTPase-activating protein-binding protein 1 (G3BP1), a signal transduction modulator stimulated by the oncoprotein Ras, which leads to higher p53 retention in the nucleus so as to stimulate ferroptosis. Delicate balances in chromatin modification are involved in the regulation of P53RRA. To summarize, lncRNA P53RRA regulated by chromatin modification inhibits ferroptosis-regulated genes in a p53-dependent manner by interacting with G3BP1. LINC00336 acts as a crucial inhibitor of ferroptosis in carcinogenesis by decreasing intracellular levels of iron and lipid ROS through interacting with ELAVL1 (ELAV like RNA binding protein 1), which has been recognized as a novel regulator of ferroptosis. Moreover, ELAVL1 increases LINC00336 expression by stabilizing its posttranscriptional modifications. Contrary to P53RRA, LSH promotes the expression of LINC00336 by upregulating ELAVL1 through the p53 signaling pathway in lung cancer. LINC00336 serves as an endogenous sponge of microRNA 6852 (MIR6852), a negative upstream regulator of cystathionine--synthase (CBS)-mediated ferroptosis inhibition. These findings indicate that lncRNA is a critical regulator for ferroptosis and may serve as an effective target of NSCLC therapy. Fig. 2 Metabolic pathways in ferroptosis. In the process of ferroptosis, lipid peroxidation plays a key role in triggering ferroptosis. A great number of molecules participate in ferroptosis by regulating the same protein, resulting in similar downstream pathways. For example, p53, BAP1, ATF3, phosphorylated BECN1,and the combination of erastin and SLC7A5, inhibit expression or activation of SLC7A11, which leads to the depletion of cysteine and GSH in cells. Some other molecules such as FINO2 and RSL3 inhibit GPX4 in cells. The decrease of GSH or GPX4 in cells contributes to lipid peroxidation, ultimately resulting in ferroptosis. MIR137 inhibits SLC1A5 and decreases Gln, Glu, and -KG in cells, also involved in ferroptosis. The cadherin-NF2-Hippo-YAP signaling axis is involved in ferroptosis. miRNA-17-92 prevents ferroptosis in cells through targeting the A20-ACSL4 axis. ACSL4 that is also regulated by Sp1 regulates the expression of 5-HETE and long polyunsaturated 6 fatty acids in cells, thus participating in the regulation of ferroptosis Deubiquitinase acts as an epigenetic regulator to promote ferroptosis BAP1 (BRCA1-associated protein) encodes the deubiquitinase (DUB) in the nucleus, a common inactivated tumor suppressor in different cancer cell lines, including uveal melanoma (UVM), renal cell carcinoma, mesothelioma, and cholangiocarcinoma. Genomic analyses together with robust statistics have revealed that the restoration of BAP1 facilitates the formation of the polycomb repressive deubiquitinase (PR-DUB) complex and inhibits ubiquitinated histone 2A (H2Aub) occupancy on the SLC7A11 promoter. As a result, the downregulation of SLC7A11 blocks ferroptosis as it leads to cystine starvation and depletion of GSH; an important precursor for membrane lipid peroxidation and subsequent ferroptosis-induced cell death. The knockdown of SLC7A11 in UMRC6 cells (a BAP1-deficient renal cancer cell line) marginally affects cancer cell proliferation, suggesting that the BAP1-mediated tumor suppression through regulating SLC7A11. BAP1 is a tumor suppressor, coding for the nuclear deubiquitinating (DUB) enzyme, which reduces histone 2A ubiquitination (H2Aub) on chromatin. By removing ubiquitin from H2Aub on the SLC7A11, BAP1 can repress SLC7A11 expression. In addition, a current study has linked BRCA1-associated tumorigenesis to the stability of Nrf2 (NF-E2-related factor 2), which regulates antioxidant signaling by decreasing the ROS level. The interplay between BAP1 and BRCA1 together with their roles as epigenetic regulators could contribute to the understanding of ferroptosis in terms of oxidative stress. In addition, OTUB1 (OTU deubiquitinase, ubiquitin aldehyde binding 1) is an ovarian tumor (OTU) family member deubiquitinase. It can directly interact with SLC7A11 and regulate SLC7A11 stability, in the process of which, CD44 may play an essential role. Monoubiquitination of histone H2B on lysine 120 (H2Bub1) is an epigenetic mark generally associated with transcriptional activation, and H2Bub1 negatively regulates the Warburg effect and tumorigenesis likely through controlling the expression of multiple mitochondrial respiratory genes, which are essential for OXPHOS (oxidative phosphorylation), through interacting with pyruvate kinase M2 (PKM2), the rate-limiting enzyme of glycolysis. Interestingly, H2Bub1 regulates the expression of SLC7A11 and a group of ionbinding genes that function in multiple metabolismrelated processes, indicating that H2Bub1 is a novel epigenetic regulator of ferroptosis. Moreover, p53 promotes the nuclear translocation of H2Bub1 deubiquitinase USP7 (ubiquitin-specific protease 7) that interacts with, deubiquitinates, and stabilizes p53, functioning as novel regulator of H2Bub1. In addition, the p53-USP7-H2Bub1 axis regulates SLC7A11 expression and activity during ferroptosis induction by erastin treatment. In sum, the effects of deubiquitinases on epigenetic mark links a novel epigenetic mechanism for the regulation of ferroptosis. Selenium acts as an epigenetic regulator to block ferroptosis Selenium (Se) is an important biosis element and the products of it associate with the health and safety of human beings. Selenoprotein, a type of protein with a selenocysteine (Sec, U, Se-Cys) amino acid residue, includes five antioxidant glutathione peroxidases (GPX) and three thioredoxin reductases (TrxR/TXNRD), which both contain only one Sec. As mentioned above, the expression of GPX4 could counter the induction of ferroptosis; however, the function of its upstream transcription molecules remains unclear. A selenium-mediated way of selenome gene augmentation at the epigenetic level could inhibit ferroptosis and protect neuro cell death after brain hemorrhage. Se recruits TFAP2c (transcription factor activating enhancer-binding protein 2C) and Sp1 to the promoter region of GPX4, upregulating GPX4 expression. The high levels of GPX4 expression are critical for an adaptive response and could reduce cell death after intracerebral hemorrhage by inhibiting ferroptosis. Furthermore, Tat-linked SelP Peptide (Tat SelPep), a selenocysteine-containing peptide that was created artificially, has the same function to improve outcomes after stroke in an Sp1 -dependent manner, providing a wider therapeutic window. Collectively, pharmacological selenium provides insights into a novel therapeutic strategy to block ferroptosis and promote cell survival (Fig. 3). The cancer therapeutic application in epigenetic and metabolic regulation of ferroptosis Protein Kinases have appeared as one of the most intensively interested targets in current pharmacological research, especially for cancer, for their critical roles in cellular signaling transduction. Compared to other kinase inhibitors, sorafenib is the only drug that displays ferroptotic efficacy, through enhancing the expression of SQSTM1/p62, or inhibiting STAT3 phosphorylation, or decreasing the expression level of NRF2 target. In addition, ferroptosis might strengthen the anticancer effect of the apoptosis-inducer cisplatin in cancer cells, indicating that ferroptosis inducers could be used to enhance the effect of traditional anticancer drugs. The BRD4 inhibitor (+)-JQ1 (JQ1) has been shown to suppress the proliferation of cancer cells by inducing apoptosis, indicating that JQ1 may be a new therapeutic agent for cancer treatment. (+)-JQ1 could regulate ferroptosis by controlling the expression of ferroptosis-associated genes including GPX4, SLC7A11 and SCL3A2, which regulated by BRD4. (+)-JQ1 regulated ferritinophagy and the expression of ferroptosis-associated genes via epigenetic inhibition of BRD4 by suppressing the expression of the histone methyltransferase G9a or enhancing the expression of the histone deacetylase SIRT1. Clearly, treatment with JQ1 and RSL3, erastin, or sorafenib produced a satisfactory anticancer effect, suggesting that the combination of JQ1 with ferroptosis inducers could become a new therapeutic modality. A challenge in oncology is to rationally and effectively integrate immunotherapy with traditional modalities including radiotherapy, interestingly, immunotherapy sensitizes tumors to radiotherapy by promoting tumor cell ferroptosis, and IFN derived from immunotherapy-activated CD8 + T cells and radiotherapy-activated ATM (ataxia telangiectasia mutated) independently, yet synergistically repress SLC7A11, indicating that ferroptosis may be untapped therapeutic mechanism and focus for the development of effective pharmacologic and immunotherapeutic combinatorial approaches with radiotherapy for the treatment of cancer. Moreover, interferon- produced by tumor-infiltrating T cells downregulates the expression of SLC3A2 and SLC7A11, two subunits of the glutamatecystine antiporter system x c −, impairs the uptake of cystine by tumor cells, and as a consequence, kills cancer cells through the induction of ferroptosis, indicating that targeting ferroptosis-associated metabolism in tumors may improve the efficacy of cancer immunotherapy. Interestingly, FePt nanoparticles, a novel ferroptosis agent, could induce ferroptosis by catalyzing the Fenton reaction to produce the ROS. Meanwhile, the metastatic tumors are abolished effectively with the support of oligodeoxynucleotides containing cytosine-guanine together with systemic checkpoint blockade immunotherapy using an anti-CTLA4 (anti-cytotoxic T lymphocyte associated antigen-4) antibody, providing a multifunctional platform for anticancer therapeutic applications through ferroptosis. Targeting ferroptosis holds novel promise for the treatment of cancer and considerable efforts are being made to generate ferroptosis modulators for clinical use, but additional studies are required to devise the most efficient strategies in epigenetic and metabolic regulation of ferroptosis. Conclusions and perspectives Intracellular iron concentration and lipid peroxidation are two major biochemical characteristics required for autophagy-dependent ferroptosis, a novel type of RCD. Inhibiting iron overload in the mitochondria and/or blocking the process of redox imbalance can serve as a possible anti-ferroptosis approach. Multiple organelles, including the mitochondria, ER, lysosome, and Golgi apparatus, are involved in the regulation of iron metabolism and lipid peroxidation in ferroptosis. The metabolite-mediated ways of ferroptosis include GPX4 as an important core molecule and system x c − in importing cysteine and exporting glutamate. Abundant Fig. 3 The epigenetic regulators in ferroptosis. The BAP1-mediated pathway independent of TP53 executes the suppression of SLC7A11. LSH expression is upregulated by c-Myc, which is enriched at the LSH promoter by the EGLN1-mediated repression of HIF-1. The induced LSH interacts with WDR76, which, in turn, up-regulates the lipid metabolic genes including SCD1 and FADS2. LSH also induces ELAVL1 expression through the inactivation of p53 and ELAVL1, enhancing LINC00336 levels. LINC00336 serves as an endogenous sponge of MIR6852 as a circulating extracellular DNA (ceRNA), which increases the mRNA levels of CBS, inhibiting ferroptosis in lung cancer. P53RRA promotes ferroptosis by retaining p53 in the nucleus discoveries have been made in transcription signaling of ferroptosis as well as the effects of different related factors. Among them, NRF2 has been tested to inhibit ferroptosis by targeting system x c − and mediating GPX4, therefore, decreasing iron concentration and ROS. However, the targeted effectors of ferroptosis remain unclear and are required for interventions which may contribute to a new way to treat diseases through ferroptosisinduced cell death. Therefore, more detailed research on the suppression of ferroptosis is needed to provide a more valuable therapy. The mechanistic relationships between epigenetic controls and ferroptosis in cancer progression were previously unclear. However, epigenetic regulators have been identified to involve in ferroptosis and oncogenesis by mediating metabolic genes and intermediators, therefore, contributing to the change of lipid peroxidation. Interestingly, microbial metabolites could not only mediate modulation of host immunity and metabolism as well as epigenetics, but also input the effects on cancer immunotherapy, therefore, elevating our understanding of how the microbiome and its metabolites affect cell fate including ferroptosis will advance our capacity to provide well-founded microbial-based therapeutics. Though the precise and comprehensive role of these factors are not yet fully discovered, they do provide us with a novel way to regulate ferroptosis by mediating potential targets and intervening the axis. The new direction of therapeutic intervention may help to overcome the current barrier in anti-cancer therapy. Further study is required to discover more epigenetic molecules and related mechanisms of ferroptosis, which may contribute to the discovery of anti-cancer therapies. |
HPBOSE 10th, 12th supplementary results 2018: The Himachal Pradesh Board of School Education (HPBOSE) has declared the results for the class 10 and 12 supplementary exams. Candidates who have appeared in these exams can check their results from the official website, hpbose.org.
The Himachal Pradesh Board of School Education (HPBOSE) has declared the results for the class 10 and 12 supplementary exams.
Candidates who have appeared in these exams can check their results from the official website, hpbose.org. Apart from it, the results are available on some private websites.
The supplementary exams were conducted in the state for candidates who had failed the matriculation or the plus two exams. The plus two, 10th supplementary exams were held in the month of June.
The candidates have to visit the official website, hpbose.org. Then, click on the tab for the results page. Click on the link for the class 10 or class 12 results. Enter your details in the fields provided. Download your results and take a print out of the same for further reference. |
Formation of molecular oxygen in ultracold O + OH reaction We discuss the formation of molecular oxygen in ultracold collisions between hydroxyl radicals and atomic oxygen. A time-independent quantum formalism based on hyperspherical coordinates is employed for the calculations. Elastic, inelastic and reactive cross sections as well as the vibrational and rotational populations of the product O2 molecules are reported. A J-shifting approximation is used to compute the rate coefficients. At temperatures T = 10 - 100 mK for which the OH molecules have been cooled and trapped experimentally, the elastic and reactive rate coefficients are of comparable magnitude, while at colder temperatures, T<1 mK, the formation of molecular oxygen becomes the dominant pathway. The validity of a classical capture model to describe cold collisions of OH and O is also discussed. While very good agreement is found between classical and quantum results at T=0.3 K, at higher temperatures, the quantum calculations predict a larger rate coefficient than the classical model, in agreement with experimental data for the O + OH reaction. The zero-temperature limiting value of the rate coefficient is predicted to be about 6.10^{-12} cm^3 molecule^{-1} s^{-1}, a value comparable to that of barrierless alkali-metal atom - dimer systems and about a factor of five larger than that of the tunneling dominated F + H2 reaction. I. INTRODUCTION Important experimental progress is being made in creating ultracold molecules in tightly bound vibrational levels. Very recently, formation of ground state molecules in the vibrational level v = 0 has been reported by different groups for homonuclear molecules such as Cs 2, Rb 2, as well as for heteronuclear polar molecules such as RbCs, KRb, and LiCs. There has also been much progress in the measurement of rate coefficients of barrierless reactions involving alkali-metal atoms at cold and ultracold temperatures. This includes atom -molecule collisions such as Rb + Rb 2, Cs + Cs 2, Na + Na 2, Rb/Cs + RbCs, and molecule -molecule collisions such as Cs 2 + Cs 2, Na 2 + Na 2, and Rb 2 + Rb 2. The typical rate coefficients of these reactions are on the order of 10 −11 − 10 −10 cm 3 molecule −1 s −1 depending on the collisional system, the temperature and the vibrational levels probed. All these experimental studies indicate that inelastic and reactive processes occur at significant rates at ultracold temperatures, in accordance with theoretical predictions on barrier reactions as well as a number of alkali-metal atom -dimer systems such as Li + Li 2, Na + Na 2 and K + K 2 which proceeds without an energy barrier in the entrance channel. The alkali-metal systems are characterized by triatomic complexes with deep potential wells which make them challenging systems for accurate quantum calculations. For these heavy systems, the density of triatomic states is large and it leads to strong couplings between them, enhancing inelastic quenching or reactive scattering. However, explicit quantum calculations of molecule -molecule systems involving alkali-metal atoms are computationally intractable. In a recent theoretical study of vibrational relaxation in collisions between H 2 molecules, Qumner et al. showed that the relaxation rate coefficients at ultralow temperature can attain large values for some near-resonant processes which involve simultaneous conservation of internal energy and total internal rotational angular momentum of the colliding molecules. While there have been a number of theoretical studies of ultracold reactive collisions of tunneling dominated reactions with chemically distinct reactants and products, there have been no such studies involving barrierless chemical reactions at ultracold temperatures. Here we investigate the exothermic reaction at cold and ultracold temperatures as an example of a barrierless chemical reaction involving non-alkali-metal atom systems. The reaction is of key interest in oxygen chemistry in the interstellar medium, OH chemistry in the upper stratosphere and mesosphere, and combustion chemistry (see Ref. and references therein). The OH radical has also been cooled and trapped using the buffer gas and stark decelerator techniques. High precision measurements of its radiative lifetime and its hyperfine constant have recently been reported. An experimental study of scattering between cold OH molecules and He atoms and D 2 molecules has recently been reported. The cooling and trapping studies have stimulated a number of theoretical investigations involving the OH molecule in the last few years. Gonzlez-Snchez et al. reported rotational relaxation and spin-flipping of OH in He collisions at ultralow energies. They found that rotational relaxation occurs more efficiently than elastic collisions at vanishing collision energies. By carrying out quantum calculations of Rb + OH collisions at ultracold temperatures Lara et al. explored the possibility of sympathetic cooling of OH molecules by collisions with Rb atoms. They argued that efficient sympathetic cooling of OH molecules in the ground vibrational state by collisions with Rb atoms is unlikely to occur due to the large inelastic rate coefficient. External fields can also have important effects on ultracold molecular collisions. Avdeenkov and Bohn investigated the effect of external fields on ultracold collisions between OH or OD molecules. Ticknor and Bohn also studied OH−OH collisions in the presence of a magnetic field. They showed that magnetic fields of several thousand Gauss suppress inelastic collision rates by about two orders of magnitude. In a recent study, we reported quantum dynamics calculations of reaction for T = 10 − 600 K and found no significant decrease of the rate coefficient in the temperature range 39 − 10 K, in accordance with conclusions of a recent experimental study by Carty et al.. Our calculations for reaction probabilities were in excellent agreement with those of Xu et al. for collision energies E c > 0.012 eV. In this paper, we present the quantum dynamics of reaction at low and ultralow collision energies to explore the behavior of complex forming chemical reactions at cold and ultracold temperatures. Since OH molecules have been experimentally cooled and trapped at low temperatures, we believe that collisional properties of the O + OH reaction will be of considerable interest to the cooling and trapping community. The paper is organized as follows: The details of the quantum mechanical formalism along with convergence tests are discussed in Section II. Results of cross sections, rate coefficients, and stateto-state product distributions are given in Section III. We also include in this section a discussion on the usefulness of a classical model in describing cold collisions of O and OH. Conclusions are presented in Section IV. A. Potential energy surfaces We employed a modified version of the electronically adiabatic ground state (1 2 A ) potential energy surface (PES) of HO 2 calculated by Kendrick and Pack using a diatomics-in-molecule (DIM) formalism. This new version includes improvements to the long-range behavior and is referred to as the DIMKP PES. In particular, a switching function was implemented which more smoothly "turns-on" the long-range van der Waals potentials for the electronic ground states of both O 2 and OH. This switching function is given by f switch = 0.5(tanh((r − r 0 )) + 1) where = 1, r 0 = 7.0 a 0 for O 2 ( 3 − g ) and r 0 = 10 a 0 for OH( 2 ). A minor global refitting of the DIM HO 2 PES to the original set of ab initio data was required in order to account for the new switching functions and ensure a smooth transition to the longrange behavior. The same long-range coefficients were used as in the original version of the surface, for OH( 2 ):. The global fit in the interaction region is essentially identical to the original fit with nearly the same rms deviation of 0.099 eV (2.3 kcal/mol). The improvements to the long-range behavior are important for the ultracold collisions studied in this work but should not significantly affect the results of previous scattering calculations at higher (thermal) energies. We present in Fig. 1 the potential energy curves for the 3 lowest 2 A states of HO 2 for the DIMKP PES, for a O-HO linear approach. We also note in the inset of Fig. 1 that the DIMKP PES predicts a shallow conical intersection along the O-HO approach due to the crossing of the OH() and OH() states. For a fixed r OH = 1.83 a 0, this crossing occurs at R O-HO = 10.8235 a 0 and its energy lies 8.30 10 −4 eV (≈ 9.6 K) below the asymptotic energy of the O + OH channel. For comparison purposes, we also employed the ab initio PES computed by Xu, Xie, Zhang, Lin, and Guo, referred to as the XXZLG PES. The XX-ZLG PES has been used in a number of quantum dynamics calculations of the O + OH system at high collision energies. The present DIMKP PES was employed for the first time for this reaction in our previous work and it is preferred at low energies as it includes accurate long-range coefficients. B. Quantum mechanical approach and convergence tests The quantum dynamics calculations have been performed using the adiabatically adjusting principle-axis hyperspherical (APH) approach of Pack and Parker. The method uses the democratic Smith-Whitten hyperspherical coordinates in the inner region ( < 17 a 0 ) that includes the triatomic well of the HO 2 system and the Delves-Fock hyperspherical coordinates in the outer region ( > 17 a 0 ) in the valleys of the H + O 2 and O + OH arrangement channels. For a given value of the total angular momentum quantum number, J, and hyperspherical radius,, the wavefunction is expanded onto a basis set of adiabatic functions, which are eigenfunctions of a triatomic hyperangular Hamiltonian. A hybrid DVR/FBR primitive basis set combined with an Implicity Restarted Lanczos algorithm is used to diagonalize the hyperangular Hamiltonian matrix. The timeindependent Schrdinger equation yields a set of differential close-coupling equations in, which are solved using the log-derivative matrix propagation method of Johnson. The log-derivative matrix is propagated to a matching distance ( m ) where asymptotic boundary conditions are applied to evaluate the reactance matrix K J and the scattering matrix S J. The square elements of the S J matrix provide the state-to-state transition probabilities, P J. The matching distance and all other parameters employed in the calculations were determined by optimization and extensive convergence studies. To secure convergence of the reaction probabilities, the number of hyperspherical channels, n, included in the close coupling equations is 393. This is sufficient to obtain converged results at low and ultralow energies. The cross sections are calculated using the standard formulae: where i, j denote initial and final quantum states. The non-thermal elastic and reactive rate coefficients are given by el and re where = k/ is the incident velocity for relative motion of the O atom and the OH molecule. The convergence of the elastic cross section J=0 el and the non-thermal reactive rate coefficient J=0 re are presented in Tab. I and Tab. II for O + OH(v = 0, j = 0) on the DIMKP PES. At vanishing collision energies, these quantities attain finite values as required by the Bethe-Wigner laws : The tables also show convergence of the results with the matching distances. At low energies the elastic cross section converges less rapidly with the matching distance m than the reactive one. This is because the long-range contribution to the interaction potential is not negligible compared to the kinetic energy in the entrance channel, even for moderately large values of the hyperradius. Thus, elastic cross sections are generally more sensitive to the long-range tail of the interaction potential. For the parameters in Tab. I and Tab. II the reactive rate coefficients are converged to within 1% while the elastic cross sections are converged within 3%. All of the final results presented here are obtained using m = 44.0 a 0, which is especially necessary to get converged results at E c < 10 −4 eV. A. Cross sections and rate coefficients The J = 0 elastic and reactive cross sections are plotted as a function of the collision energy in Fig. 2 for the DIMKP PES. The corresponding non-thermal rate coefficients are presented in Fig. 3 limit of zero energy. The elastic rate coefficient and the reactive cross section behave respectively as the square root and the inverse of the square root of the collision energy. The Bethe-Wigner regime is reached at E c ≈ 10 −4 K, where the reactive rate coefficient is of about one order of magnitude higher than that of the elastic counterpart. At E c = 10 −6 K the reactive rate coefficient is two orders of magnitude larger than the elastic one. This is reminiscent of other exothermic barrierless systems such as alkali-metal atom -diatom collisions. At energies between E c = 0.01 K and 30 K, elastic and reactive rate coefficients are of comparable magnitude. For E c > 30 K, the elastic scattering is more efficient than reactive scattering. The inelastic rotational excitation to the j = 1 level opens up at E c = 52 K and its cross section is comparable to the reactive contribution. The J = 0 contribution to the elastic, inelastic and reactive rate coefficients evaluated using the XXZLG PES are presented in Fig. 4 as functions of the collision energy. For E c > 1 K, all three rate coefficients are of comparable magnitudes with those obtained from the DIMKP PES. For E c < 1 K, the reactive rate coefficient is about two orders of magnitude smaller than that obtained using the DIMKP PES. The differences can be traced to the incomplete description of the long-range interaction potential in the XXZLG PES. It does not properly include the long-range potential in the O + OH channel as it was not designed for quantum dynamics calculations at ultralow energies. Thus, the comparison of the results obtained using the two surfaces highlights the crucial role of the long-range interaction potential in chemical reaction dynamics at low temperatures. The importance of the long-range intermolecular forces in the O-OH system in determining its rate coefficient has been pointed out Fig. 6 for each final vibrational level v f populated by the reaction at an energy of 10 −6 K. The results show that low rotational levels are generally preferred for each of the final vibrational levels. Since the incident channel includes only the s-wave, the final rotational distribution is largely determined by the anisotropy of the interaction potential. Explicit calculations of rate coefficients would require reaction probabilities for all contributing values of the total angular momentum quantum number (J). This is a computationally demanding problem for the O + OH reaction if full quantum dynamics calculations are em-ployed, especially when many J values contribute to the reaction probability. The J-shifting approximation is widely used to compute rate coefficients when full quantum calculations are not practical. This is a good approximation for barrier reactions which involve a transition state but not for complex forming reactions. Nevertheless, the J-shifting approximation has been applied to the O + OH reaction in a number of previous studies and it has been demonstrated that it can predict rate coefficients within about 40% of numerically exact calculations. Here we use the J-shifting approximation to compute the rate coefficients for the O + OH reaction. The rate coefficient is given by the expression: where k B is the Boltzmann constant, P re,J=0 v,j is the J = 0 reaction probability and E J shift is the height of the effective barrier for a given partial wave J in the entrance channel. To determine the barrier height for a given partial wave, we first evaluate the effective potential, V J eff : The elastic, inelastic, and reactive rate coefficients of the O + OH(v = 0, j = 0) reaction evaluated using the J-shifting method for the DIMKP PES are shown in Fig. 8 for T = 10 −6 − 10 3 K. As indicated earlier, the Bethe-Wigner regime is reached for temperatures below T ≈ E c ≈ 10 −4 K. The value of the rate coefficient in the zero-energy limit is 6.2 10 −12 cm 3 molecule −1 s −1. This is a factor of 5 smaller than the rate coefficient reported as J=0 re in Fig. 3. The difference comes from the electronic partition function in the denominator in Eq. 2, which is equal to 5 as T → 0. In experiments using the stark decelerator methods, OH molecules were cooled to T = 10 − 100 mK. In this temperature range, our computed values of the elastic rate coefficients are comparable to the reactive ones and will not favor sympathetic cooling of OH by collisions with O atoms. Similar conclusions have been found by Lara et al. for collisions between OH molecules with Rb atoms. The relatively large rate coefficient for the reaction in the zero-temperature limit indicates that barrierless exothermic reactions occur at significant rates at ultracold temperatures, in agreement with similar results for alkali-metal atom -diatom reactions. Fig. 8 shows that the minimum value of the rate coefficient for the O + OH reaction is about 4.9 10 −12 cm 3 molecule −1 s −1 at T = 5 10 −3 K. This provides a lower limit for O 2 formation by reaction. We note that the inelastic process becomes more probable than the reactive process for T > 330 K. B. Classical capture model We shall now compare our quantum dynamics results with a classical capture model also known as the Langevin model. This model has been shown to work quite well for a certain range of collision energy, for atomexchange reactions such as K + K 2, Li + Li 2, and also for non-reactive Rb + OH collisions. We have shown that the Langevin model predicts rate coefficients in close agreement with experimental values for Rb + Rb 2, Cs + Cs 2, and Rb/Cs + RbCs collisions reported recently. For the O + OH reaction, Clary and Werner used an adiabatic capture theory, while Davidsson and Nyman used a generalized Langevin model. Both studies showed good agreement between theoretical and experimental rate coefficients. Here we test the validity of the Langevin model against a TIQM and J-shifting method for the O + OH reaction. For a non-rotating diatomic molecule (j = 0) at large atom -molecule separations R O-OH, for a given value of J, the interaction potential can be approximated by an effective potential, V J Lang, composed of a repulsive centrifugal term and an attractive van der Waals term: At an atom -diatom distance of, the height of the effective potential is given by: The quantities E J Lang and R J Lang are reported in Tab coefficient is due to the presence of significant diatomic mixing in the OH diatomic states for r OH = 1.83 a 0 (see for example Eqs. 34 − 37 in Ref. ). This mixing gives rise to an effective C 6 coefficient of the O-HO approach of 0 where the multiplicative constants 1 and 2 depend on the level of diatomic mixing. As r OH increases, the diatomic mixing decreases and 1 → 1 and 2 → 1. The dependence of the long-range coefficients for atom -diatom interactions on the diatomic separation has also been noted and investigated in recent work on the Li + Li 2 and Na + Na 2 systems. For the atommolecule reduced mass we used = 15023.74 au. In the Langevin model, the rate coefficient as a function of the temperature is given by the expression: The rate coefficient predicted by the Langevin model is plotted in Fig. 8 (black dashed curve). Except in the Bethe-Wigner regime for T < 10 −4 K, where the classical model is not valid, the Langevin model predicts rate coefficients in semi-quantitative agreement with those obtained from the quantum calculations. Overall, the reactive rate coefficients oscillate slightly around the Langevin line, as in other barrierless systems such as K + K 2 and Li + Li 2. However, the Langevin model yields good agreement only for a restricted range of temperatures. The lower limit of the model prediction is restricted by the number of partial waves included in the calculations. In previous studies, it has been found that when three or more partial waves are included, the quantum and classical results are in good agreement. If less than three partial waves are involved, the quantum character becomes dominant and the results cannot be compared with the classical model. These previous studies have also shown that the maximum of the quenching rate coefficient for a given partial wave J occurs at about a collision energy comparable to the height of the barrier, E J Lang. Thus, the lower limit corresponds to a collision energy of E J=3 Lang = 0.32 K (see Tab.III) for the present system. The upper limit is bounded by the long-range part of the potential. When the Langevin radius R J Lang is located at a distance where the long-range part of the potential is not described by the van der Waals interaction, E J Lang will differ from E J shift. In this case, the classical results will differ from the quantum calculations. Tab. III shows that this is the case for J = 3 and the upper limit of the model also corresponds to a collision energy of E J=3 Lang = 0.32 K. Thus, the Langevin model gives quantitative agreement for temperatures around T ≈ 0.3 K, as seen in Fig. 8. For T > 0.3 K, the rate coefficient depends on the exact details of the effective potential in the entrance channel. However, the classical result is in overall agreement with the quantum result, though the classical model predicts a smaller value for the rate coefficient. This is because E J shift < E J Lang for J > 3 (see Tab. III) and reactivity is less probable to occur with the Langevin model. Therefore, the Langevin model provides a lower limit of the rate coefficients for T = 1 − 100 K which affirms the theoretical conclusions of Ref. and experimental conclusions of Ref., that the rate coefficient of reaction is unlikely to vanish for T < 10 K. We also note that the Langevin rate coefficient is in semiquantitative agreement with the inelastic rate coefficient in the range T = 100−1000 K. The difference is less than 30 %. IV. CONCLUSION This paper presents the first quantum mechanical investigation of an ultracold barrierless reaction with chemically distinct reactants and products. We investigated dynamics of molecular oxygen formation in ultracold collisions of the hydroxyl radical and atomic oxygen using a time-independent quantum mechanical method based on hyperspherical coordinates. It has been found that formation of molecular oxygen occurs with a relatively large rate coefficient of 6.2 10 −12 cm 3 molecule −1 s −1 at ultracold temperatures. The oxygen molecules are mainly formed in the v = 0 − 2 vibrational levels with a slight preference for the v = 0 level. Calculations show that at temperatures of T = 10 − 100 mK, the elastic cross sections are not large enough to achieve efficient evaporative cooling in collisions between OH molecules and O atoms. We predict a lower limit of 4.910 −12 cm 3 molecule −1 s −1 for the rate coefficient for the O + OH(v = 0, j = 0) reaction at T = 5 10 −3 K. This shows that formation of O 2 molecules is significant even at ultracold temperatures. It has been found that a classical capture model is valid for temperatures around T ≈ 0.3 K where quantum and classical calculations yield comparable results. Based on our analysis of the longrange interaction potential we find that for T = 1 − 10 K the Langevin model can provide a lower limit to the quantum reactive rate coefficients calculated within the J-shifting approximation. Future work will consider the effects of the geometric phase and non-adiabatic couplings between different PESs of HO 2 on the reaction dynamics. The geometric phase due to the conical intersection of two PESs may have an important effect at low and ultralow collision energies where only a few partial waves contribute to the reaction probabilities. V. ACKNOWLEDGMENTS This work was supported by NSF grants #PHY-0555565 (N.B.) and #ATM-0635715 (N.B.). B.K.K. acknowledges that part of this work was done under the auspices of the US Department of Energy at Los Alamos National Laboratory. Los Alamos National Laboratory is operated by Los Alamos National Security, LLC, for the National Nuclear Security Administration of the US Department of Energy under contract DE-AC52-06NA25396. |
<gh_stars>1-10
package SecAgent.utils.DefaultLoggerHelper;
import java.io.IOException;
import java.util.logging.ConsoleHandler;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;
public class DefaultLogConsoleHandler extends ConsoleHandler {
/**
* construct DefaultLogConsoleHandler with DefaultLogFormatter
*
* @throws IOException
*/
public DefaultLogConsoleHandler() {
super();
setFormatter(new DefaultLogFormat());
}
public DefaultLogConsoleHandler(Formatter formatter) throws IOException, SecurityException {
super();
setFormatter(formatter);
}
@Override
public void publish(LogRecord record) {
super.publish(record);
}
@Override
public void close() {
super.close();
}
}
|
When we think about all the great games and systems we’ve enjoyed over the years, it’s all too easy to forget about the fallen pieces of hardware that lay in our wake. Such as:
SNES Pad: Street Fighter 2: The World Warrior is a great game, and you know how much I love playing it even though I’m terrible at it. But MAN, M. Bison in World Warrior was a cheap little PUNK. He’d pull out the Psycho Crushers at a moment’s notice and that flying head stomp thing would cross me up at every opportunity. And yep, I have to admit that I got so enraged by this continual stream of BS that I threw my SNES controller at the wall, smashing it into pieces in what could only be called “A God damn infantile temper tantrum”. So not only did the game cost me a small fortune to buy in the first place but I was out $40 for another controller too.
Commodore 64: One day I was reading a local gaming magazine and saw this bad boy:
No, not the koala – a real arcade-style joystick for the Commodore 64, with real arcade buttons and everything! Far out, that is seriously hardcore. I can’t remember if they were only available via mail order if they had a local store distribution deal but I do remember being insanely excited when I finally got my own Star Cursor joystick for the C64. Except one little problem: the bloody thing didn’t work.
For some reason that I could never understand plugging a Star Cursor into my C64 completely drove the C64 berserk, spamming the screen with keyboard commands and making every game unplayable. It was the weirdest thing, and then when I took it back to the store (oh, so I guess I did get it from a store then) to get a replacement the replacement fried my C64 so it never booted again. I guess I had faulty joystick ports or something. That’s the last time I bought an Australian-made joystick! 3 year guarantee my big bottom.
Sega MegaDrive: When the MegaDrive first came out there were cheat codes being printed in EGM and the like for games such as AfterBurner and Space Harrier that gave you unlimited lives – but you had to rip the cartridge out of the slot and put another cartridge in its place. (There’s a great list of these cheats here) Now, this seems like utter madness now but I was young and stupid and didn’t really get what I was doing. And yep, you guessed it, I broke a MegaDrive in the process of ripping a cart out. Instead of pulling Altered Beast out of the cartridge slot I ended up flinging the MegaDrive across the room and it never worked right since. What the hell, man? That was just DUMB.
Another Commodore 64: Speaking of cheat codes, the essential item you needed as a Commodore 64 gamer was a reset switch. This handy little gizmo was usually available as part of an Action Replay cartridge or similar, and basically let you jump out of the game back to the BASIC prompt where you could then enter POKE codes to change how many lives you had or whatever. Now, being stuck in the middle of nowhere with no access to an actual reset switch, I had to resort to McGuyvering my own reset switch with a paper clip carefully jammed into the computer’s expansion port. What I didn’t realise then that doing so basically connects the expansion sort with the power supply, so I shouldn’t have been surprised that I fried the machine after a couple of weeks of doing this. I was an idiot who really didn’t deserve to have a computer.
Countless dodgy joysticks: The sticks that came with the Commodore 64 were pure garbage that didn’t even last a day, but they were freebies so who cares. There was a plentiful supply of cheap and cheerful sticks available at the local store, but they too were wrecked by ‘waggle the stick really fast’ games like Decathlon and Combat School. It’s like these games were designed by joystick companies to encourage kids to keep buying more joysticks.
Every pinball machine I ever touched: For some reason every time I go near a pinball machine something happens to it. A brand new machine fresh out of the crate will somehow develop a flipper issue within minutes of me playing it, or something goes wrong with the display, or the coin box stops working, or whatever. Damn it, I want to get into buying pinball machines one day but I guess I’ve fallen afoul of some ancient curse.
The first PlayStation 2 Sony sent me: “Here’s your review PlayStation 2, fresh from Japan” the nice PR person told me, “you can just use your regular PlayStation 1 cables with it”. Well, I promptly hooked it all up and turned it on. A few minutes into Ridge Racer and people around me started asking what the smell was. Oh, it turns out that the PR guy meant I could use all my regular Japanese PlayStation 1 power cables (110 watts) with it, not the over-powered Australian ones (240 watts). One completely fried PlayStation 2 later I was politely informed Sony would not be sending me a replacement. Greedy mongrels!
Guitar Hero Guitar: I was drunk. I was a jerk. I later regretted it. But man oh man did it feel good to finally get a perfect score on Matthew Sweet’s “Girlfriend” in Guitar Hero 2 and then proceed to smash the living crap out of the guitar in true rock and roll style. I wish there was an achievement I could have unlocked or something.
PC monitors: Did you know that I blame my horrendous eyesight on Commodore’s line of incredibly blurry and bulky PC monitors? I thought they would have been awesome after how good the 1084 was (and still is!) but NOOO they were crap. HOWEVER, did you also know that it feels really, really good to throw Commodore’s line of incredibly blurry and bulky PC monitors into a dam? They’re heavy bastards for sure but make a satisfying CRUNCH against the concrete wall and then a big SPLASH a few seconds later. Wow, thinking back, that was a really dumb thing to do and I probably contaminated the local water supply for weeks. WHOOPS SORRY!
The house’s power supply: I had one (1) power point in my room growing up, and about 16 computers, consoles, computers and televisions all being powered from that thanks to a complex series of power point expanders and extension cables. At some point I decided, what the heck, let’s add some more power points to this mix so I can have an extra Amiga going. All I remember next was a loud bang and flying across the room, and then people being mad at me because apparently electricians are expensive? Pfft whatever I had to go without playing Elite for a while.
Daytona Arcade: Serious Daytona USA players don’t use the brakes to get around the tight corners – they just downshift the car for a second before going back up to regular gear and going on their merry way. Well, for some reason I found it really, really satisfying to wrench the crap out of the gearstick in the local arcade on my daily Daytona session, and then the damn thing broke. The greedy bastards who ran the arcade had the audacity to charge $2 a go, but then I’m the monster for breaking the gear stick? What a world.
My Grandmother’s Television: Christmas 1992. Imagine, if you will, a young me being ferried over to my grandmother’s house for the annual family reunion Christmas booze-up. I HATED these events. I didn’t really fit in with the rest of the family, who were all into sports and being loud and playing cricket in the back yard. All I wanted to do was play video games and read magazines about video games and draw pictures of video games I wanted to make one day. But! I had managed to convince the parents to let me take my SNES and new copy of Super Mario Kart along to play all day while everyone else had their own fun. And it was a great Christmas! Basically my sister, brother and I played Super Mario Kart and Game Boy by ourselves while 50 relatives drank and argued all day. But MAN, ever since then, TO THIS GOD DAMN DAY, my Grandmother STILL complains that plugging a Super Nintendo into her TV somehow broke it. She can’t even see TV any more and she still complains that evil video games destroyed her precious antique TV. IT WAS 22 YEARS AGO GRANDMA LET IT GO ALREADY.
Let’s all pour out a virtual 40 ounce for our fallen gaming hardware. Do you have any hardware failure stories? |
<reponame>Mimino666/python-xextract
import re
import six
class Quantity(object):
'''
Quantity is used to verify that the number of items satisfies the
expected quantity, which you specify with a regexp-like syntax.
Syntax:
* - zero or more items
+ - one or more items
? - zero or one item
num - specified number of items (0 <= num)
lower, upper - number of items in interval [lower, upper] (0 <= lower <= upper).
'''
def __init__(self, quantity='*'):
self.raw_quantity = quantity
self.lower = self.upper = 0 # lower and upper bounds on quantity
self._check_quantity_func = self._parse_quantity(quantity)
def check_quantity(self, n):
'''Return True, if `n` matches the specified quantity.
'''
if not isinstance(n, six.integer_types):
raise ValueError('Invalid argument for "check_quantity()".'
'Integer expected, %s received: "%s"' % (type(n), n))
return self._check_quantity_func(n)
def _check_star(self, n):
return n >= 0
def _check_plus(self, n):
return n >= 1
def _check_question_mark(self, n):
return n == 0 or n == 1
def _check_1d(self, n):
return n == self.upper
def _check_2d(self, n):
return self.lower <= n <= self.upper
_quantity_parsers = (
# regex, check_funcname
(re.compile(r'^\s*\*\s*$'), '_check_star'),
(re.compile(r'^\s*\+\s*$'), '_check_plus'),
(re.compile(r'^\s*\?\s*$'), '_check_question_mark'),
(re.compile(r'^\s*(?P<upper>\d+)\s*$'), '_check_1d'),
(re.compile(r'^\s*(?P<lower>\d+)\s*,\s*(?P<upper>\d+)\s*$'), '_check_2d'))
def _parse_quantity(self, quantity):
'''
If `quantity` represents a valid quantity expression, return the
method that checks for the specified quantity.
Otherwise raise ValueError.
'''
# quantity is specified as a single integer
if isinstance(quantity, six.integer_types):
self.upper = quantity
if 0 <= self.upper:
return self._check_1d
else:
raise ValueError('Invalid quantity: "%s"' % repr(quantity))
# quantity is specified as a pair of integers
if isinstance(quantity, (list, tuple)) and len(quantity) == 2:
self.lower, self.upper = quantity
if (isinstance(self.lower, six.integer_types) and
isinstance(self.upper, six.integer_types) and
0 <= self.lower <= self.upper):
return self._check_2d
else:
raise ValueError('Invalid quantity: "%s"' % repr(quantity))
# quantity is specified as a string
if isinstance(quantity, six.string_types):
for parser, check_funcname in self._quantity_parsers:
match = parser.search(quantity)
if match:
# set lower and upper values
gd = match.groupdict()
self.lower = int(gd.get('lower', 0))
self.upper = int(gd.get('upper', 0))
# check lower/upper bounds
if self.lower <= self.upper:
return getattr(self, check_funcname)
else:
raise ValueError('Invalid quantity: "%s"' % repr(quantity))
# quantity is of a bad type
raise ValueError('Invalid quantity: "%s"' % repr(quantity))
@property
def is_single(self):
'''True, if the quantity represents a single element.'''
return (
self._check_quantity_func == self._check_question_mark or
(self._check_quantity_func == self._check_1d and self.upper <= 1))
|
<reponame>markhaehnel/blitz
import {createIdleHandler} from "."
import {pipeline, through} from "../../streams"
import {testStreamItems} from "../../test-utils"
import {IDLE, READY} from "../../events"
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
describe("idlehander", () => {
it("should fire the idle event", async () => {
// Setup an input stream
const input = through.obj()
const bus = through.obj()
// setup the test pipeline
const idleHandler = createIdleHandler(bus, 100)
pipeline(input, idleHandler.stream)
const arr = [1, 2, 3, 4]
for (const item of arr) {
input.write(item)
}
await sleep(150)
for (const item of arr) {
input.write(item)
}
input.write("ready")
await sleep(150)
for (const item of arr) {
input.write(item)
}
await testStreamItems(bus, [{type: IDLE}, {type: READY}, {type: IDLE}], (a) => a)
})
})
|
<gh_stars>0
#include "crypto_functions.h"
#include <cryptopp/osrng.h>
#include <limits.h>
#include <random>
#include <string>
void createRsaKeys(RSA::PublicKey &publicKey, RSA::PrivateKey &privateKey) {
CryptoPP::AutoSeededRandomPool rng;
CryptoPP::InvertibleRSAFunction params;
params.GenerateRandomWithKeySize(rng, RSA_KEY_LEN);
publicKey = RSA::PublicKey(params);
privateKey = RSA::PrivateKey(params);
}
int32_t getIntegerRand(void) {
std::default_random_engine generator;
std::uniform_int_distribution<int> distribution(INT32_MIN, INT32_MAX);
return (int32_t) distribution(generator);
}
string signMessage(string message, RSA::PrivateKey privateKey) {
string signature;
CryptoPP::AutoSeededRandomPool rng;
CryptoPP::RSASSA_PKCS1v15_SHA_Signer signer(privateKey);
CryptoPP::StringSource stringSource(
message, true, new CryptoPP::SignerFilter(rng, signer, new CryptoPP::StringSink(signature)));
return message + signature;
}
string encryptString(string message, RSA::PublicKey publicKey) {
CryptoPP::AutoSeededRandomPool rng;
string cipher;
CryptoPP::RSAES_OAEP_SHA_Encryptor enc(publicKey);
CryptoPP::StringSource stringSource(
message, true, new CryptoPP::PK_EncryptorFilter(rng, enc, new CryptoPP::StringSink(cipher)));
return cipher;
}
string decryptString(string cipher, RSA::PrivateKey privateKey) {
CryptoPP::AutoSeededRandomPool rng;
CryptoPP::RSAES_OAEP_SHA_Decryptor dec(privateKey);
string message;
CryptoPP::StringSource ss2(cipher, true,
new CryptoPP::PK_DecryptorFilter(rng, dec, new CryptoPP::StringSink(message)));
return message;
}
bool verifySign(string signed_message, RSA::PublicKey publicKey) {
CryptoPP::RSASSA_PKCS1v15_SHA_Verifier verifier(publicKey);
CryptoPP::StringSource ss2(signed_message, true,
new CryptoPP::SignatureVerificationFilter(
verifier, NULL, CryptoPP::SignatureVerificationFilter::THROW_EXCEPTION));
return true;
} |
package privval
import (
"fmt"
"net"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/tendermint/tendermint/crypto/ed25519"
cmn "github.com/tendermint/tendermint/libs/common"
"github.com/tendermint/tendermint/libs/log"
p2pconn "github.com/tendermint/tendermint/p2p/conn"
"github.com/tendermint/tendermint/types"
)
var (
testAcceptDeadline = defaultAcceptDeadlineSeconds * time.Second
testConnDeadline = 100 * time.Millisecond
testConnDeadline2o3 = 66 * time.Millisecond // 2/3 of the other one
testHeartbeatTimeout = 10 * time.Millisecond
testHeartbeatTimeout3o2 = 6 * time.Millisecond // 3/2 of the other one
)
type socketTestCase struct {
addr string
dialer Dialer
}
func socketTestCases(t *testing.T) []socketTestCase {
tcpAddr := fmt.Sprintf("tcp://%s", testFreeTCPAddr(t))
unixFilePath, err := testUnixAddr()
require.NoError(t, err)
unixAddr := fmt.Sprintf("unix://%s", unixFilePath)
return []socketTestCase{
socketTestCase{
addr: tcpAddr,
dialer: DialTCPFn(tcpAddr, testConnDeadline, ed25519.GenPrivKey()),
},
socketTestCase{
addr: unixAddr,
dialer: DialUnixFn(unixFilePath),
},
}
}
func TestSocketPVAddress(t *testing.T) {
for _, tc := range socketTestCases(t) {
// Execute the test within a closure to ensure the deferred statements
// are called between each for loop iteration, for isolated test cases.
func() {
var (
chainID = cmn.RandStr(12)
sc, rs = testSetupSocketPair(t, chainID, types.NewMockPV(), tc.addr, tc.dialer)
)
defer sc.Stop()
defer rs.Stop()
serverAddr := rs.privVal.GetPubKey().Address()
clientAddr := sc.GetPubKey().Address()
assert.Equal(t, serverAddr, clientAddr)
}()
}
}
func TestSocketPVPubKey(t *testing.T) {
for _, tc := range socketTestCases(t) {
func() {
var (
chainID = cmn.RandStr(12)
sc, rs = testSetupSocketPair(t, chainID, types.NewMockPV(), tc.addr, tc.dialer)
)
defer sc.Stop()
defer rs.Stop()
clientKey := sc.GetPubKey()
privvalPubKey := rs.privVal.GetPubKey()
assert.Equal(t, privvalPubKey, clientKey)
}()
}
}
func TestSocketPVProposal(t *testing.T) {
for _, tc := range socketTestCases(t) {
func() {
var (
chainID = cmn.RandStr(12)
sc, rs = testSetupSocketPair(t, chainID, types.NewMockPV(), tc.addr, tc.dialer)
ts = time.Now()
privProposal = &types.Proposal{Timestamp: ts}
clientProposal = &types.Proposal{Timestamp: ts}
)
defer sc.Stop()
defer rs.Stop()
require.NoError(t, rs.privVal.SignProposal(chainID, privProposal))
require.NoError(t, sc.SignProposal(chainID, clientProposal))
assert.Equal(t, privProposal.Signature, clientProposal.Signature)
}()
}
}
func TestSocketPVVote(t *testing.T) {
for _, tc := range socketTestCases(t) {
func() {
var (
chainID = cmn.RandStr(12)
sc, rs = testSetupSocketPair(t, chainID, types.NewMockPV(), tc.addr, tc.dialer)
ts = time.Now()
vType = types.PrecommitType
want = &types.Vote{Timestamp: ts, Type: vType}
have = &types.Vote{Timestamp: ts, Type: vType}
)
defer sc.Stop()
defer rs.Stop()
require.NoError(t, rs.privVal.SignVote(chainID, want))
require.NoError(t, sc.SignVote(chainID, have))
assert.Equal(t, want.Signature, have.Signature)
}()
}
}
func TestSocketPVVoteResetDeadline(t *testing.T) {
for _, tc := range socketTestCases(t) {
func() {
var (
chainID = cmn.RandStr(12)
sc, rs = testSetupSocketPair(t, chainID, types.NewMockPV(), tc.addr, tc.dialer)
ts = time.Now()
vType = types.PrecommitType
want = &types.Vote{Timestamp: ts, Type: vType}
have = &types.Vote{Timestamp: ts, Type: vType}
)
defer sc.Stop()
defer rs.Stop()
time.Sleep(testConnDeadline2o3)
require.NoError(t, rs.privVal.SignVote(chainID, want))
require.NoError(t, sc.SignVote(chainID, have))
assert.Equal(t, want.Signature, have.Signature)
// This would exceed the deadline if it was not extended by the previous message
time.Sleep(testConnDeadline2o3)
require.NoError(t, rs.privVal.SignVote(chainID, want))
require.NoError(t, sc.SignVote(chainID, have))
assert.Equal(t, want.Signature, have.Signature)
}()
}
}
func TestSocketPVVoteKeepalive(t *testing.T) {
for _, tc := range socketTestCases(t) {
func() {
var (
chainID = cmn.RandStr(12)
sc, rs = testSetupSocketPair(t, chainID, types.NewMockPV(), tc.addr, tc.dialer)
ts = time.Now()
vType = types.PrecommitType
want = &types.Vote{Timestamp: ts, Type: vType}
have = &types.Vote{Timestamp: ts, Type: vType}
)
defer sc.Stop()
defer rs.Stop()
time.Sleep(testConnDeadline * 2)
require.NoError(t, rs.privVal.SignVote(chainID, want))
require.NoError(t, sc.SignVote(chainID, have))
assert.Equal(t, want.Signature, have.Signature)
}()
}
}
// TestSocketPVDeadlineTCPOnly is not relevant to Unix domain sockets, since the
// OS knows instantaneously the state of both sides of the connection.
func TestSocketPVDeadlineTCPOnly(t *testing.T) {
var (
addr = testFreeTCPAddr(t)
listenc = make(chan struct{})
thisConnTimeout = 100 * time.Millisecond
sc = newSocketVal(log.TestingLogger(), addr, thisConnTimeout)
)
go func(sc *SocketVal) {
defer close(listenc)
assert.Equal(t, sc.Start().(cmn.Error).Data(), ErrConnTimeout)
assert.False(t, sc.IsRunning())
}(sc)
for {
conn, err := cmn.Connect(addr)
if err != nil {
continue
}
_, err = p2pconn.MakeSecretConnection(
conn,
ed25519.GenPrivKey(),
)
if err == nil {
break
}
}
<-listenc
}
func TestRemoteSignVoteErrors(t *testing.T) {
for _, tc := range socketTestCases(t) {
func() {
var (
chainID = cmn.RandStr(12)
sc, rs = testSetupSocketPair(t, chainID, types.NewErroringMockPV(), tc.addr, tc.dialer)
ts = time.Now()
vType = types.PrecommitType
vote = &types.Vote{Timestamp: ts, Type: vType}
)
defer sc.Stop()
defer rs.Stop()
err := sc.SignVote("", vote)
require.Equal(t, err.(*RemoteSignerError).Description, types.ErroringMockPVErr.Error())
err = rs.privVal.SignVote(chainID, vote)
require.Error(t, err)
err = sc.SignVote(chainID, vote)
require.Error(t, err)
}()
}
}
func TestRemoteSignProposalErrors(t *testing.T) {
for _, tc := range socketTestCases(t) {
func() {
var (
chainID = cmn.RandStr(12)
sc, rs = testSetupSocketPair(t, chainID, types.NewErroringMockPV(), tc.addr, tc.dialer)
ts = time.Now()
proposal = &types.Proposal{Timestamp: ts}
)
defer sc.Stop()
defer rs.Stop()
err := sc.SignProposal("", proposal)
require.Equal(t, err.(*RemoteSignerError).Description, types.ErroringMockPVErr.Error())
err = rs.privVal.SignProposal(chainID, proposal)
require.Error(t, err)
err = sc.SignProposal(chainID, proposal)
require.Error(t, err)
}()
}
}
func TestErrUnexpectedResponse(t *testing.T) {
for _, tc := range socketTestCases(t) {
func() {
var (
logger = log.TestingLogger()
chainID = cmn.RandStr(12)
readyc = make(chan struct{})
errc = make(chan error, 1)
rs = NewRemoteSigner(
logger,
chainID,
types.NewMockPV(),
tc.dialer,
)
sc = newSocketVal(logger, tc.addr, testConnDeadline)
)
testStartSocketPV(t, readyc, sc)
defer sc.Stop()
RemoteSignerConnDeadline(time.Millisecond)(rs)
RemoteSignerConnRetries(100)(rs)
// we do not want to Start() the remote signer here and instead use the connection to
// reply with intentionally wrong replies below:
rsConn, err := rs.connect()
defer rsConn.Close()
require.NoError(t, err)
require.NotNil(t, rsConn)
// send over public key to get the remote signer running:
go testReadWriteResponse(t, &PubKeyResponse{}, rsConn)
<-readyc
// Proposal:
go func(errc chan error) {
errc <- sc.SignProposal(chainID, &types.Proposal{})
}(errc)
// read request and write wrong response:
go testReadWriteResponse(t, &SignedVoteResponse{}, rsConn)
err = <-errc
require.Error(t, err)
require.Equal(t, err, ErrUnexpectedResponse)
// Vote:
go func(errc chan error) {
errc <- sc.SignVote(chainID, &types.Vote{})
}(errc)
// read request and write wrong response:
go testReadWriteResponse(t, &SignedProposalResponse{}, rsConn)
err = <-errc
require.Error(t, err)
require.Equal(t, err, ErrUnexpectedResponse)
}()
}
}
func TestRetryConnToRemoteSigner(t *testing.T) {
for _, tc := range socketTestCases(t) {
func() {
var (
logger = log.TestingLogger()
chainID = cmn.RandStr(12)
readyc = make(chan struct{})
rs = NewRemoteSigner(
logger,
chainID,
types.NewMockPV(),
tc.dialer,
)
thisConnTimeout = testConnDeadline
sc = newSocketVal(logger, tc.addr, thisConnTimeout)
)
// Ping every:
SocketValHeartbeat(testHeartbeatTimeout)(sc)
RemoteSignerConnDeadline(testConnDeadline)(rs)
RemoteSignerConnRetries(10)(rs)
testStartSocketPV(t, readyc, sc)
defer sc.Stop()
require.NoError(t, rs.Start())
assert.True(t, rs.IsRunning())
<-readyc
time.Sleep(testHeartbeatTimeout * 2)
rs.Stop()
rs2 := NewRemoteSigner(
logger,
chainID,
types.NewMockPV(),
tc.dialer,
)
// let some pings pass
time.Sleep(testHeartbeatTimeout3o2)
require.NoError(t, rs2.Start())
assert.True(t, rs2.IsRunning())
defer rs2.Stop()
// give the client some time to re-establish the conn to the remote signer
// should see sth like this in the logs:
//
// E[10016-01-10|17:12:46.128] Ping err="remote signer timed out"
// I[10016-01-10|17:16:42.447] Re-created connection to remote signer impl=SocketVal
time.Sleep(testConnDeadline * 2)
}()
}
}
func newSocketVal(logger log.Logger, addr string, connDeadline time.Duration) *SocketVal {
proto, address := cmn.ProtocolAndAddress(addr)
ln, err := net.Listen(proto, address)
logger.Info("Listening at", "proto", proto, "address", address)
if err != nil {
panic(err)
}
var svln net.Listener
if proto == "unix" {
unixLn := NewUnixListener(ln)
UnixListenerAcceptDeadline(testAcceptDeadline)(unixLn)
UnixListenerConnDeadline(connDeadline)(unixLn)
svln = unixLn
} else {
tcpLn := NewTCPListener(ln, ed25519.GenPrivKey())
TCPListenerAcceptDeadline(testAcceptDeadline)(tcpLn)
TCPListenerConnDeadline(connDeadline)(tcpLn)
svln = tcpLn
}
return NewSocketVal(logger, svln)
}
func testSetupSocketPair(
t *testing.T,
chainID string,
privValidator types.PrivValidator,
addr string,
dialer Dialer,
) (*SocketVal, *RemoteSigner) {
var (
logger = log.TestingLogger()
privVal = privValidator
readyc = make(chan struct{})
rs = NewRemoteSigner(
logger,
chainID,
privVal,
dialer,
)
thisConnTimeout = testConnDeadline
sc = newSocketVal(logger, addr, thisConnTimeout)
)
SocketValHeartbeat(testHeartbeatTimeout)(sc)
RemoteSignerConnDeadline(testConnDeadline)(rs)
RemoteSignerConnRetries(1e6)(rs)
testStartSocketPV(t, readyc, sc)
require.NoError(t, rs.Start())
assert.True(t, rs.IsRunning())
<-readyc
return sc, rs
}
func testReadWriteResponse(t *testing.T, resp RemoteSignerMsg, rsConn net.Conn) {
_, err := readMsg(rsConn)
require.NoError(t, err)
err = writeMsg(rsConn, resp)
require.NoError(t, err)
}
func testStartSocketPV(t *testing.T, readyc chan struct{}, sc *SocketVal) {
go func(sc *SocketVal) {
require.NoError(t, sc.Start())
assert.True(t, sc.IsRunning())
readyc <- struct{}{}
}(sc)
}
// testFreeTCPAddr claims a free port so we don't block on listener being ready.
func testFreeTCPAddr(t *testing.T) string {
ln, err := net.Listen("tcp", "127.0.0.1:0")
require.NoError(t, err)
defer ln.Close()
return fmt.Sprintf("127.0.0.1:%d", ln.Addr().(*net.TCPAddr).Port)
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.