text:
В'язів Яр () — балка (річка) в Україні у Дергачівському районі Харківської області. Права притока річки Уди (басейн Азовського моря).

Опис
Довжина балки приблизно 9 км, найкоротша відстань між витоком і гирлом — 8,18  км, коефіцієнт звивистості річки — 1,10 . Формується декількома балками та загатами.

Розташування
Бере початок на північно-східній околиці села Горіхове у листяному лісі. Тече переважно на північний схід через село В'язове і на північно-східній околиці селища Курортне впадає у річку Уду, праву притоку Сіверського Дінця.

Населені пункти вздовж берегової смуги: Березівське.

Цікаві факти
 Біля гирла балки пролягає автошлях  (територіальний автомобільний шлях в Україні,   — Пересічне. Проходить територією Дергачівського району Харківської області.).
 У минулому столітті на балці існувало 2 газгольдери та багато газових свердловин.

Примітки

Джерела
 Словник гідронімів України — К.: Наукова думка, 1979. — С. 124 (В'язовий № 4)

Малі річки України
Річки Харківської області
Річки Дергачівського району


Receiving reports from an NSA attempt to eavesdrop on the Russian leader, Dmitry Medvedev, as his phone calls passed through satellite links to Moscow.
Of course, this seems like traditional espionage that has gone on for ages, which by itself is less troubling to me. What's more revealing is some of the methods -- such as the ability to get around the security on the BlackBerry. As for the "internet cafe" -- who in their right mind would use such a thing, knowing that it was almost certainly being monitored?
What's Illegal About Using Twitter To Organize Protests?
A bunch of folks have been sending in various versions of the story of a guy (described as an "anarchist") who was allegedly arrested for using social media tools like Twitter to organize protesters at the recent G20 Summit in Pittsburgh. The specific charges are for "hindering prosecution," but it seems like there must be some details missing. All around, the whole thing sounds pretty extreme. What's illegal about organizing protesters?


text:
Why Harvard's case studies are under fire
Students love the classroom buzz and collaborative approach, but critics are circling
Jan Rivkin teaches a class at Harvard Business School © Kent Dayton
In the basement of Harvard Business School's Aldrich building at 9am, 90 chattering first-year MBA students file into a semi-circular amphitheatre and take their pre-assigned places, marked by name cards. They are about to participate in the Finance 1 course, one of their first experiences of the institution's signature approach to teaching and research.
Each student lays out in front of them a case: a stapled booklet containing a dozen or more pages of text interspersed with data. Many have scribbled and highlighted sections on the paper, symbols of their debates and calculations from the "learning teams" in which they prepare for classes in small groups.
During two years of study, the typical student will analyse and discuss 500 cases: a pedagogical approach that has achieved near-religious status at Harvard and proved highly lucrative with sales to hundreds of business schools around the world. But case studies are now being written in varied ways, or rejected outright by rivals as business education trends shift.
After some brief banter, Chris Malloy, a finance professor, makes the first of many unsolicited "cold calls" to question a student picked at random on the case they are studying, called "Ocean Carriers" about leasing and cash flow, designed to spark discussion on whether a company should commission a new cargo ship.
Over the next 80 minutes, he paces up and down the aisles, energetically teasing out contributions from students in the room. Their comments are noted down by a "scribe" since they will account for half of their course grade. Their views differ but the mood is collegiate, with comments sparking periodic applause from peers, laughter or three sharp knocks on desks if they speak too quietly.
"I used to lecture when I was at the London Business School," says Prof Malloy afterwards. "But you don't get the same interaction or engagement from students as you do with the case method."
For the past century, since shortly after Wallace Donham was appointed dean in 1919, the business school has adopted the case method as its dominant approach to teaching. It was pioneered 50 years earlier at Donham's own alma mater, Harvard Law School, to analyse judicial decisions.
In contrast to lectures, in which the professor delivers to a silent auditorium, cases require students to prepare in advance, studying the range of information provided and putting themselves in the position of the protagonist — normally a senior corporate executive. They then debate their decision in class while the teacher — in the Socratic tradition — acts primarily as facilitator.
Advocates say the method forces students to master the material, trains them in making decisions and defending them to a group, focuses on practical examples, allows them to share their own work experience and ensures they retain the lessons learnt — in part by making the approach entertaining.
An extract from a recent, Manga-syle Harvard case study
"There is something magical about the buzz in the classroom," says Jan Rivkin, senior associate dean. "It's tremendously rewarding. You can see the lightbulb go on and know when they are getting it right, which is very hard in lectures."
Not everyone is convinced. The largest share of Harvard's cases are dominated by US examples. Critics say women leaders are insufficiently represented, and some themes, sectors and perspectives — including those of labour unions — are played down.
Yubo Chen, associate dean of Tsinghua University's School of Economics and Management in Beijing, says the different demands of his students explains why his school is one of a growing number in Asia writing their own — often shorter, more practical — teaching cases. "Our students are not satisfied with Harvard cases," he says. "The environment is changing so fast, and we need cases on China. It's very difficult to talk, say, about Amazon. They want to know about ecommerce in China."
Some raise more fundamental questions about the case method. It requires not only good cases but also skilful teaching, without which class discussions can be flat.
Steven Shugin, professor in marketing at the University of Florida's College of Business Administration, argues that the scientific method — of rigorously testing theories — in business schools should displace both the writing and Socratic-style teaching of cases, which are typically based on historic events in a single company.
"I'm not saying the case has no value but it is not generalisable," he says. "So many cases highlighted the best companies of the 1980s like Kodak, which had gone out of business by the 1990s." A series of Harvard cases of "innovative" Enron financial transactions have since been superseded by ones on the ethics raised by its collapse.
He says case teaching is popular with students, who consequently rank their professors highly in satisfaction surveys, because it is entertaining but diverts research from studying and developing more robust theories that should be more widely taught.
News in-depthThe Big Read
Business education: have we reached peak MBA?
"Teaching should keep students up with current thinking," he says. "Cases may teach presentation skills, but they should be taught those in communications classes, not in finance and marketing courses."
A few minutes away from Harvard at the Massachusetts Institute of Technology's Sloan School, Maura Herson, assistant dean for the MBA programme, says less than half of its core courses are taught using cases.
She stresses the growing role of simulations, the use of mentors and consultancy projects working with real local companies rather than case studies on paper. She says case studies are less useful for technical skills in ever higher demand, such as artificial intelligence.
Competition: Yale's alternative
Just as Yale has long been Harvard's academic rival, so its School of Management has developed a different approach to cases. Jaan Elias, director of its case research centre who previously worked at Harvard, contrasts to his former employer's self-contained, relatively short "cooked" cases "in which faculty know every point and comma" with Yale's longer "raw" ones.
It has produced some 150 such open-ended cases, which include links to articles and videos online to encourage "multiple perspectives" designed to mimic the vast quantity of information in the modern world. They are used in multiple courses, though some say they are not easily taught by professors other than the original author.
Different Yale faculty members spurn case teaching altogether. Prof Paul Bracken, who teaches leadership using scenario-planning, says: "Cases are about the past, when you already know the answers. Scenarios are about role playing the future. We have far fewer people asking which choices are the right decisions. That's leadership."
Prof Rivkin says that Harvard too now offers simulations and "immersion" placements to complement cases, which have evolved in theme, content and style, including online versions and even a "Manga" version.
But he stresses: "We are trying to produce general managers, not students with the deepest technical knowledge in narrow functional areas. For the best financial services training you'd go to Wharton, for technology to Sloan or to Kellogg for marketing.
"It's incumbent on critics of the case method to suggest a better alternative," he says. The school produces some 350 new cases annually to add to a stock of about 7,500. Last year, it sold about 15m copies globally mostly to business schools, from 11.5m in 2013. Cases contributed much of the $221m in its publishing division's revenue in 2017, which generate more than a quarter of the school's total income.
At least measured by the top line, Harvard's model is far from waning.
Letter in response to this article:
Our field method supports case studies here at HBS / From Jim Aisner, Director of Media and Public Relations, Harvard Business School, Boston, MA, US
Get alerts on Work & Careers when a new story is published

redpajama_set_name: RedPajamaCommonCrawl


As Britain's population ages, more and more of us will end up looking after a loved one.
1. It's Carers Week. About 6.5 million Britons are unpaid carers. And that number is going to go up and up.
That's 6.5 million people who give an hour or more of their time, for free, to look after someone else, usually a family member. Britain is going to face a crisis in the next few years: There are simply going to be too many people in need of care and not enough people to look after them.
2. Here's why. The population of the UK is going up.
It was a little over 62 million five years ago; it's almost 65 million now. And by 2035, it's projected to be around 73 million.
3. In one sense, that's not an urgent problem. There's still plenty of room for everyone to live.
Less than 10% of Britain is built on. Large areas around 14 major urban centres are protected by green belts, and there about 29% of the rest of the land falls into national parks, areas of outstanding natural beauty, or sites of special scientific interest. But there're lots of places to build houses for more people to live in (although that isn't happening fast enough).
4. The reason we do need to worry about it is that as the population grows, it's getting older.
The median age of the population was 39.7 years in 2010; by 2020 it's expected to be 39.9, and by 2035 it'll be 42.2.
5. What that means is that there will be more and more older people as a proportion of the population.
Five years ago, there were almost four working adults for every one person above the (current) retirement age of 65. Now it's more like two and a half. The government has changed the retirement age so younger people will now have to work until they're 68, but even taking that into account, the Office for National Statistics (ONS) says "the number of people of state pension age (SPA) is projected to increase by 28 per cent from 12.2 million to 15.6 million by 2035".
That's a problem for a variety of reasons – most obviously, it'll be harder to pay for state pensions with the taxes of working people.
6. And that means lots more people are going to have to become carers, because older people are disproportionately likely to require care.
Two-thirds of dementia sufferers live at home, and most of those are looked after by unpaid carers. The number of people with dementia was about 850,000 in 2013. That figure is predicted to go up 40% by 2025, and 156% by 2051.
And, of course, dementia is just one of the problems which strike older people more than younger people.
7. The Carers Trust estimates that an extra 3.4 million carers will be needed by 2040.
That's an increase of around 60% from its 2010 estimate of 7 million (a little higher than the Carers Week estimate). In the same time, the ONS estimates that the population as a whole will have grown by just 18%.
9. …and less likely to be in work.
Comparing the ONS estimate of the employment rate of the population as a whole with the Carers Trust stats on employment of carers.
The Carers Trust says that more than half of carers who are not in work say they would like to be. It says that "£5.3 billion a year has been wiped off the economy".
11. …and young people suffer a lot too.
A 2010 survey estimated that there are 700,000 young carers in Britain, and they're twice as likely to be "not in education, employment or training" (NEET). If that stat is right, it means that one young person in 12 is caring for a loved one.
This isn't a problem that's going to go away.


text:
Lion-Witch-Wardrobe
Sprouts: Harriet-Tubman
enGAGE Program: Perseverance
Sprouts: Boxcar-Children
Prime Stage Sprout
Sprouts: Lemonade Girl
Voice Over Boot Camp
Drama Awards
Plan Evening
Literacy in ACTion
Student Matinee Field Trips
enGAGE Program
The White Rose
Act-48 Workshop
Literacy Statement
Creative Arts Festival (Archive)
Champions of Life Building (Archive)
Stage Tunes
Young Women's Collaborative
Prime Stage Sprouts
EVENTS>> Frankenstein | The Lion, the Witch and the Wardrobe | The 39 Steps
CATEGORY: MAIN EVENT
Based on the Novel by Mary Shelley's
Adapted by Lawrence C. Connolly
Directed by Liam Macik
Playbill - Link to Frankenstein Playbill
Flipbook - Link to Frankenstein Social Story
Burg Vivant - '"Mary Shelley and Frankenstein – Together at Last" – a Review of "Frankenstein"
Pittsburgh Today Live - Thing to do this weekend in Pittsburgh
Pittsburgh Magazine - Top Pick: Frankenstein's Monster (and Maker) at the New Hazlett
TribLive - Pittsburgh's Prime Stage Theatre reimagines 'Frankenstein'
Local Pittsburgh - Prime Stage Theatre opens a new "Frankenstein" at New Hazlett
The Almanac - Mt. Lebanon native directs Prime Stage Theatre adaptation of 'Frankenstein'
A storm rages. Five friends take shelter in a Swiss mansion. One of them is eighteen-year-old Mary Shelley. Before the night is over, you will see her conceive one of the most horrifying and suspenseful stories ever written – the tale of a man who created life and became a monster.
Performance Dates and Times
Friday, November 4th - 8pm Friday, November 11th - 8pm
Saturday, November 5th - 8pm Saturday, November 12th - 2:30pm & 8pm
Sunday, November 6th - 2:30pm Sunday, November 13th - 2:30pm
Preview: Friday, November 4th at 8pm - Pay What You Can
Opening Night: Saturday, November 5th at 8pm
Prime Stage Theatre is committed to providing an environment that is inclusive and welcoming to all patrons. Please identify any special seating needs to our Box Office staff when reserving your tickets in advance on-line or by calling Prime Stage Public Performance Box Office at the New Hazlett 412.320.4610
Post-Show Discussion
Following the Saturday, November 12th performance of Frankenstein there will be a Post-Show discussion.
The discussion will feature Ryan O'Shea entrepreneur and Communications and Engagement Manager for the Pittsburgh Robotics Network and will explore themes from Frankenstein and how they intersect with technology of today and the future.
Frankenstein Cast
Carolyn Jerz
Will portray the roles of Safie and the Servant
Carolyn is happy to return to Prime Stage, where she's played Viola in Twelfth Night and Cherry Valance in The Outsiders. Carolyn's credits include: Front Porch (Grand Hotel); PICT (Jane Eyre; Merchant of Venice; Oliver Twist; Great Expectations; & The Strange Case of Dr. Jekyll); St. Vincent Summer Theatre (Beauty & the Beast); PPT's "Bard in Bloom" Showcase; Theatre Factory (Luisa/The Fantasticks); UnRehearsed Shakespeare (Tempest; Merry Wives; A Comedy of Errors); Heritage Players (Hermia/A Midsummer Night's Dream); Geyer PAC (Margot/Bright Star; Maggie/A Chorus Line; Winnifred/Mattress; Amy/Little Women; Dani/Dani Girl; & Mary Warren/The Crucible); and choreography for Stage Right's Joseph/Dreamcoat, for the Geyer's Once Upon a Mattress, and for the workshop debut of The Cabinet of Dr. Caligari (in which she played Jane Bradbury). Carolyn studies musical theater and dance/choreography at Seton Hill, where she just performed the Lead Player in Pippin.
Maddie Kocur
Will portray the roles of Claire Claremont and Justine Moritz
Maddie is thrilled to be making her return to the stage with Prime Stage Theatre! She hails from Seton Hill University with a BFA in Musical Theatre ('20). Some of her college theatre credits include Roxie in Chicago, Joanne in Company, and The Seagull in The Seagull. She has also performed as Wendy Jo (u/s Rusty) in Footloose at Keystone State MT and Time in Everybody at 12 Peers Theatre. Many thanks to the fantastic cast and crew of Frankenstein for working so hard to put on this monster of a show! Much love to all of her family, friends, and coaches for their unwavering support!
Andrew Lesnett
Will portray the roles of Felix Delacey, the Young Sailor and Servant
Andrew is thrilled to be making his prime stage debut! He is a recent graduate of Point Park University with a BA in Theatre Arts: performance and practice. He would like to thank his friends and family as well as the amazing cast and crew who have made this such an incredible experience
Everett Lowe
Will portray the role of the Creature
Everett is thrilled to be working with Prime Stage once again - particularly on such an original adaptation of Shelley's enduring classic. Everett last appeared on their stage as Hawthorne in The Scarlet Letter, as Malvolio in Twelfth Night, and previously in their productions of The Great Gatsby, The Importance of Being Earnest, and A Lesson Before Dying. A performance theater graduate of Geneva College and Pittsburgh native, Everett has been privileged to work with several theater companies and festivals around the city, including PICT Classic Theatre, 12 Peers Theatre, No Name Players, Pittsburgh Playwrights Theatre, Throughline Theatre, The Summer Company, Pittsburgh Fringe Festival, Little Lake, Cup-A-Jo Productions (where he also serves as Managing Director), and many more. Many thanks to Liam, Wayne and Connie, and to the cast and crew for this wonderful experience. Love always to my family and friends for their continual support. Bless the Lord, O my soul!
Michael McBurney
Wil portray the roles of Lord Byron and Robert Walton
Michael is so excited to be performing with Prime Stage again, having appeared earlier this year in Arsenic and Old Lace. He has performed previously with Bricolage in Yinz'r Scrooged and Dodo, and has worked with several other companies locally, including Throughline Theatre Company, Alarum Theatre, PICT, No Name Players, Carlow University Theatre Group, the Duquesne Red Masquers, and the Summer Company at Duquesne. He has also been involved with Arcade Comedy Theater as a performer and coach since 2014, and is so very happy that improv, and theatre in general, is starting to become more frequent again.
Will portray the roles of Percy Shelley and Victor Frankenstein
Isaac is a CMU School of Drama graduate and is thrilled for the opportunity to make his Prime Stage debut in his hometown of Pittsburgh. New York credits include America's Favorite Newscaster and What Elsa's Knew in a Peril. He has starred in shows such as Beauty and the Beast, Ragtime and Little Shop of Horrors. Isaac is also a musician
David Nackman
Will portray the roles of M. Delacey, the Constable, Liam, the Old Sailor and Servant
David was last seen at Prime Stage as multiple characters in The White Rose, and as Boris Karloff in the one-person show Karloff. Other local appearances include Mamma Mia! (Theatre Factory/Apple Hill Players), Scrooge in A Christmas Carol (Theatre Factory), and Claudius in a forthcoming audio production of Hamlet (Food for Groundlings/Play On Words). Highlights from the previous four decades include regional and summer stock appearances, the first national tour of Neil Simon's Biloxi Blues, a stint on Broadway in Simon's Broadway Bound (with Joan Rivers), and 20 years as a director, improviser and ensemble member at NYC's Castillo Theatre.
Stacia Paglieri
Will portray the roles of Mary Godwin Shelley and Elizabeth Lavenza
Stacia is delighted to be welcomed back to the Steel City with her debut at Prime Stage Theatre, after a four year stint in NYC. Recent theatre credits include As You Like It and All's Well That Ends Well at Longmont Theatre Company, and The House of Bernarda Alba at the Pittsburgh Playhouse. Stacia has also performed various roles in film and TV, both in Pittsburgh and NYC. She has a BFA in Acting from Point Park University, with additional training from Heidi Marshall Studios NYC, the Squirrel Comedy Theatre NYC, and more. She's grateful to get to share a glimpse into this iconic author's world, and she'd like to thank her friends and family for their incredible support.
Adam Seligson
Will portray the roles of John Polidori and Henry Clerval
Adamis elated to be performing with Prime Stage once again, especially with such a lovely ensemble of people and with such a unique and wonderful story being told with this production! Recent credits include The Importance of Being Earnest with Pittsburgh Savoyards, Pittsburgh Playwrights Theatre Festival in Black & White, Arsenic and Old Lace with Prime Stage, Company with Riverfront Theatre Company, and Into the Woods with The Theatre Factory. Special thanks to Mr. Lawrence Connolly for sharing his creation with us and for all of his knowledge and insight throughout the process of our "bringing it to life", if you will.
Suzanne Ward
Will portray the roles of the Ghost of Caroline Frankenstein and Anna
Suzanne is very grateful to be appearing in another stellar Prime Stage Theater production. Having the opportunity to appear as the Ghost of Caroline Frankenstein/Anna in Larry Connor's original stage play has been an honor for her. She has previously appeared as Martha Brewster in Prime Stage's production of Arsenic and Old Lace, and Pelican Players of Coraopolis in their rousing rendition of The Drowsy Chaperone as Mrs. Tottendale. Suzanne is exceptionally blessed to have her supportive family and friends giving her lift and inspiration.
Link to information about Playwright, award winning Sci-Fi author Lawrence C. Connolly
Link to Mary Shelley Biography
Link to Mary Shelly, The First Female Futurist
Link to a Quick introduction to Mary Shelley and Frankenstein
Link to Lord Byron's first edition presentation copy of Mary Shelley's Frankenstein
"Suspense, Hope and Wonder."
#PRIMESTAGE
Link to Contact Us
Link to Tickets
Prime Stage Public Performance Box Office at the New Hazlett
Prime Stage Student Matinee Field Trips & Education
Prime Stage Information
Prime Stage Administrative Office
Link to directions to the New Hazlett Theater
Non-Profit Information
Link to Americans for the Arts
Link tto Gold GuideStar Non-Profit
Link to Great Nonprofits
Link to Greater Pittsburgh Arts Council
Link to PA Council on the Arts
Link to Theatre Communications Group
Follow prime_stage1 on Snapchat!
© 2022 Prime Stage. All Rights Reserved.


text:
SafeVisitor Advisory Board
SHS School Advisory Board
Arrest Monitoring
Automated Reference Checks
SafeVisitor Solutions
Brotherhood Mutual
Mennonite Mutual
Alliant Purchasing
Reflynk
Become Client
Dr. Jeff Butts
M.S.D. Of Wayne Township Superintendent
Dr. Jeff Butts is a proud graduate of Millikin University (BS), Illinois State University (MS), and Purdue University (PhD). He began his career as a public educator in 1992 in central Illinois. Over the past 26 years he has held positions as a bus driver, coach, teacher, athletic director, principal, assistant superintendent, and now superintendent. He became the fifth superintendent in the history of the M.S.D. of Wayne Township on January 1, 2011. He is a recipient of the 2019 IAPSS Indiana Superintendent of the Year, District V Principal of the Year from the Indiana Association of School Principals, Administrator of the Year from the Indiana High School Press Association, the Indiana Council for Exceptional Children Advocate of the Year, Minority Police Officers Association Award for Outstanding Work in the Community, Cause Driven Leadership Award from the YMCA, Indiana National Guard Awards for Exceptional Support to the Community, The Center for Digital Education Digital Content and Curriculum Achievement Award, Hobson's Education Advances Award, and the Center for Digital Education Top 30 Technologists, Transformers and Trailblazers.
Dr. Butts holds leadership positions as the past president for the Indiana Association of Public School Superintendents, past board chair with the Hendricks Regional Health YMCA, president of the Indiana Partnershare, and past president for the Indiana Urban Schools Association. He was selected to serve on the transition team for Dr. Jennifer McCormick, Indiana Superintendent of Public Instruction and remains active on several advisory committees with the Indiana Department of Education. He also serves as a board member for the West Side Chamber of Commerce, board member for Indy Gateway Inc., advisory board member for Safe Hiring Solution, member of the Indianapolis Metropolitan Police Department's Diversity Task Force, and member of the Greater Indianapolis Progress Committee Race and Cultural Relations Leadership Network. He is a co-facilitator and presenter for EPIC, a groundbreaking leadership excellence program for Indiana's public school superintendents through Butler University and the Indiana Association of Public School Superintendents, in collaboration with the College of Education and the Lacy School of Business. Dr. Butts previously served as an executive committee member for the Central Indiana Education Alliance, executive committee member for the Indiana Public Schools Study Council, and the Urban Education Excellence Advisory Council. In addition, Dr. Butts holds memberships with the Indiana Association of Public School Superintendents, Midwest Suburban Superintendents Association, Northern Indiana Superintendents Association, American Association of School Administrators, Association for Supervision and Curriculum Development, Phi Delta Kappa, National Association of Secondary School Principals, Indiana Association of School Principals, and Lions Clubs International. He has served as honorary co-chair of the UNCF Masked Ball since 2014 and served on the local planning team for the National Council for the Education of Black Children National Conference.
His wife, Tammy, is a lead teacher for the M.S.D. of Wayne Township's volunteer literacy mentoring program, HOSTS. They are proud grandparents to Loela, daughter of Collin and Kassie Butts. A little-known fact about Dr. Butts is he is a fourth generation Standardbred horse trainer.
Open Screening Account
Open SafeVendor Account
FCRA Disclosure Forms
E-verify Registration Forms
Safe Hiring Solutions, 64 East Marion Street, Danville, IN, 46122, United States317-745-6946info@safehiringsolutions.com
64 E. Marion St.
Danville, IN 46122
119 S. Washington St. #200
Crawfordsville, IN 47933
15371 Roosevelt Blvd #103
Copyright © 2015-2019 SafeVisitor Solutions LLC All Rights Reserved


178 people have been pronounced dead from the storms that pummeled the South yesterday.
That is the highest tornado death count since the outbreak on April 3, 1974, when 300 people died.
In fact, there were more storms reported yesterday than in 1974. There were 164 reported tornadoes, along with 180 hailstorms and high wind.
Maptd created an interactive map based on NOAA data, showing tornadoes in red, hailstorms in yellow and high wind in blue.


text:
Q: performing nested select using grails and gorm I have the following SQL query, I was wondering if I could rewrite this in GORM style with grails, possibly using criteria, where, or other programming style querying that HQL.
SELECT count(USERID) as Result FROM Answer
WHERE USERID IN
      (SELECT USERID FROM Answer
       WHERE USERID IN (SELECT USERID FROM Answer
             WHERE USERID IN (SELECT USERID FROM Answer WHERE QID=1 AND ATxt='30') AND
       QID=2 AND ATxt='M') AND QID=3 AND ATxt='6') AND QID=4 AND ATxt='160'

A: Instead of using this nested in's you could use or. Without knowing your domain classes, I'm assuming that you have something like:
class User {
}

class Question {
}

class Answer {
  static belongsTo = [user: User, question: Question]
}

def question2 = Question.findById(2)
def question3 = Question.findById(3)
def question4 = Question.findById(4)

Answer.withCriteria {
  projections {
    count('user')
  }
  or {
    and {
      eq('question', question2)
      eq('aTxt', 'M')
    }
    and {
      eq('question', question3)
      eq('aTxt', '6')
    }
    and {
      eq('question', question4)
      eq('aTxt', '160')
    }
  }
}

redpajama_set_name: RedPajamaStackExchange


text:
Stig Halvard Dagerman (* 5. Oktober 1923 in Älvkarleby; † 4. November 1954 in Enebyberg bei Stockholm) war ein schwedischer Journalist und Schriftsteller.

Leben
Stig Dagerman, Sohn eines Sprengmeisters und einer Telefonistin, wuchs bei den Großeltern väterlicherseits auf. Seine Mutter hatte ihn gleich nach seiner Geburt verlassen. Der Vater kümmerte sich wenig um ihn. Der bäuerliche Alltag auf Norrgärdet, einem kargen, ärmlichen Hof am sandigen Ufer des Dalälven, prägte seine Kindheit. Diesen Lebensabschnitt schilderte er später als glücklich, aber nicht sorgenfrei: "Zinsen war eines der ersten Worte, die ich lernte, und ich weiß, wenn ein Haus bis über die Dachbalken verschuldet ist, dann ist es nicht nur eine Phrase." Ebenso tiefe Spuren in seinen Werken hinterließen die Erfahrungen als Jugendlicher. Über allem lag der Schatten einer "Wahnsinnstat": Sein Großvater wurde 1940 von einem Psychopathen erstochen. Dagerman fühlte sich verlassen. Auf dem Gymnasium in Stockholm verspotteten ihn die Mitschüler als plumpen Bauernjungen. An den Wochenenden trug er Zeitungen aus. Ein Schulwettbewerb für Literatur sollte ihn aufmuntern: Dagerman gewann einen einwöchigen Aufenthalt in den Bergen. Doch die Reise endete tragisch, als ein Freund und Zimmergenosse bei einem Lawinenunglück starb.

Am Ende der Schulzeit erkannte Dagerman seine Berufung, als Schriftsteller und Journalist zu arbeiten. In Stockholm schloss er sich der syndikalistischen Gewerkschaft Sveriges Arbetares Centralorganisation (SAC) an und schrieb bis zu seinem Tod für deren Wochenzeitung Arbetaren Kolumnen, Reportagen und Artikel. Auf literarischem Gebiet gelang ihm mit 22 Jahren sein Debüt. In Die Schlange schildert Dagerman das Entsetzen vor dem Inferno einer von Krieg und Barbarei zerrütteten Welt und seine bedrückenden Erlebnisse während seines Militärdienstes. Im Spätherbst 1946 machte Dagerman im Auftrag der Zeitung Expressen eine Reise in das kriegszerstörte Deutschland. Er berichtete in zwölf Zeitungsartikeln von dieser Reise und sie erschienen gesammelt im Mai 1947. Das Buch wurde nach dem Erscheinen ausgiebig besprochen, zum größten Teil sehr positiv. In der Zeitschrift Veckojournal äußerte Stig Ahlgren, das Buch sei "in den visuellen Partien ein Höhepunkt der schwedischen Reportage". Im Jahre 2009 drehte Regisseur Michael Gaumnitz auf der Basis der Reiseberichte 1946, Herbst in Deutschland.

Der Schwede wurde über die Grenzen seiner Heimat hinaus bekannt und stürzte sich in seine produktivste Schaffenszeit. Bis 1947 verfasste er mehrere Novellen und Romane. Die letzten Abschnitte von Die Insel der Verdammten, gedruckt etwa 60 Seiten, soll er in einer vierzehnstündigen Sitzung in einem Zuge getippt haben.

Es folgten Jahre der persönlichen Krise. Seine finanziellen Angelegenheiten entglitten ihm. Eine Schreibblockade kam hinzu: "Ich habe keine Philosophie, in welcher ich mich bewegen könnte wie der Vogel in den Lüften und der Fisch im Wasser. Alles was ich besitze ist ein Zweikampf, und in jedem Augenblick meines Lebens tobt dieser Zweikampf zwischen den falschen Tröstungen, die bloß die Ohnmacht steigern und meine Verzweiflung vertiefen, und diesen echten Tröstungen, die mich hinführen zu einer flüchtigen Befreiung", schrieb er damals über sich. Nach diversen Suizidversuchen setzte Dagerman am 4. November 1954 seinem Leben ein Ende, indem er in seiner abgeschlossenen Garage den Automotor laufen ließ. Die 1953 mit der Schauspielerin Anita Björk geschlossene Ehe, aus der eine Tochter hervorging, war zu jenem Zeitpunkt bereits gescheitert.

Stig Dagermans Biografie und seine Werke bilden ein Motiv in Siegfried Lenz' Roman Die Klangprobe. An seinem Geburtsort bewahrt die Stig Dagermansällskap das Andenken an den Schriftsteller. Sie verleiht seit 1996 jährlich den Stig-Dagerman-Preis. Zu seinen Empfängern zählten bisher u. a. Elfriede Jelinek, Lukas Moodysson und Jean-Marie Gustave Le Clézio.

Werke
 Ein Kind töten. In: Spiele der Nacht. Erzählungen. Dtv, München 1964.
 Ormen. 1945 (deutsch: Die Schlange)
 De dömdas ö. 1946.
 Übers. Jörg Scherzer: Die Insel der Verdammten
 Tysk höst. Resereportage från Tyskland 1946. 1947 (häufige Neuauflagen in skandinavischen Sprachen bis heute).
 Übers. Günter Barudio: Deutscher Herbst. Reisereportagen aus Deutschland 1946. Barudio und Hess, Frankfurt 1979.
 Übers. Jörg Scherzer: Deutscher Herbst. Reiseschilderung. Bibliothek Suhrkamp, 924. Frankfurt 1987.
 Übers. Paul Berf (mit einer Briefauswahl): Deutscher Herbst. Guggolz, Berlin 2021, ISBN 978-3-945370-31-5.
 Europa in Trümmern. Essays (auch als: Europa in Ruinen. Augenzeugenberichte aus den Jahren 1944–1948). Hrsg. Hans-Magnus Enzensberger. Die Andere Bibliothek, 65. Eichborn, Frankfurt 1993 u. ö.
 Nattens lekar. Erzählungen, Stockholm 1947.
 Dramer om dömda. Theaterstück, 1947.
 Att döda ett barn. Erzählung, 1948.
 Skuggan av Mart. Theaterstück, 1948.
 Streber. Theaterstück, 1948.
 Ett barns memoarer. Erzählung, 1948.
 Överraskningen. Erzählung, 1948.
 Bränt barn. 1948 (deutsch 1983: Gebranntes Kind, Roman).
 Ingen går fri. Theaterstück, 1949.
 Bröllopsbesvär. 1949.
 Übers. Herbert G. Hegedo: Schwedische Hochzeitsnacht. Die Andere Bibliothek, 304. Eichborn, Frankfurt am Main 2010, ISBN 978-3-8218-6230-9.
 Den ytttersta dagen. Theaterstück, 1952.
 Dagsedlar. Gedichte, 1954.

Hörspiel
 Unser kurzer Sommer. Aus dem Schwedischen von Verena Reichel. Produktion: SDR/NDR 1970.

Filmographie
Literarische Vorlage
 1953 und 2003: Ein Kind töten (Att döda ett barn)
 1964: Die schwedische Hochzeitsnacht (Bröllopsbesvär)
 1967: Ich – seine Geliebte (Bränt barn)
 2008: Spiele der Nacht (Nattens lekar)
Drehbuchverfilmung
 1965: Die Schlange (Ormen)
Biographische Dokumentation
 2011: Unser Verlangen nach Trost ist unersättlich (Vårt behov av tröst är omättligt)

Literatur
 Olof Lagercrantz: Stig Dagerman. Stockholm 1958, erneuert 1967.
 Agneta Pleijel: Djuret och skräcken. En studie i Stig Dagermans författerskap. In: Samalaren, 86, 1965, Seite 96–114.
 Arma Sastamoinen (Hrsg.): Stig Dagerman och syndikalismen. Stockholm 1974.
 Hans Sandberg: Stig Dagerman – författare och journalist. Stockholm 1975.
 Hans Sandberg: Den politiske Stig Dagerman. Tre studier. Stockholm 1979.
 Laurie Thompson: Stig Dagerman and Politics. In: Scandinavica. 1/1980, Seite 39–55.
 Georges Perilleux: Stig Dagerman et l'existentialisme. Paris 1982.
 Laurie Thompson: Stig Dagerman. Boston 1983.
 Kerstin Laitinen: Begärets irrvägar. Existentiell tematik i Stig Dagermans texter. Umeå 1986.
 Gösta Werner: De grymma skuggorna: en studie i Stig Dagermans författarskap och dess relationer till filmen som medium. Stockholm 1986.
 Georges Perilleux: Stig Dagerman: le mythe et l'œuvre. Paris 1993.
 Björn Ranelid: Mitt namn skall vara Stig Dagerman. Roman. Bonnier Alba, Stockholm 1993, ISBN 91-7643-077-4.

Weblinks

 Stig Dagermansällskapet
 Hansi Oostinga: "Entweder ein neuer Strindberg oder Du" – Annemarie Dagerman, Website der Freien Arbeiterinnen und Arbeiter-Union
 Die Entnazifizierung als Farce, Rezension zur Wiederveröffentlichung von Deutscher Herbst 2021

Einzelnachweise

Autor
Literatur (20. Jahrhundert)
Literatur (Schwedisch)
Erzählung
Roman, Epik
Hörspielautor
Person des Anarchismus
Schwede
Geboren 1923
Gestorben 1954
Mann

redpajama_set_name: RedPajamaWikipedia


text:
(function (arr) {
  return Array.isArray(arr) ? arr : Array.from(arr);
});

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Fuel\Core;

class Database_Dblib_Connection extends \Database_PDO_Connection
{
	/**
	 * Stores the database configuration locally and name the instance.
	 *
	 * [!!] This method cannot be accessed directly, you must use [static::instance].
	 *
	 * @param string $name
	 * @param array  $config
	 */
	protected function __construct($name, array $config)
	{
		// this driver doen't work on Windows
		if (is_windows())
		{
			throw new \Database_Exception('The "Dblib" database driver does not work well on Windows. Use the "Sqlsrv" driver instead.');
		}

		parent::__construct($name, $config);
	}

	/**
	 * List tables
	 *
	 * @param string $like
	 *
	 * @throws \FuelException
	 */
	public function list_tables($like = null)
	{
		$query = "SELECT name FROM sys.objects WHERE type = 'U' AND name != 'sysdiagrams'";

		if (is_string($like))
		{
			$query .= " AND name LIKE ".$this->quote($like);
		}

		// Find all table names
		$result = $this->query(\DB::SELECT, $query, false);

		$tables = array();
		foreach ($result as $row)
		{
			$tables[] = reset($row);
		}

		return $tables;
	}

	/**
	 * List table columns
	 *
	 * @param   string  $table  table name
	 * @param   string  $like   column name pattern
	 * @return  array   array of column structure
	 */
	public function list_columns($table, $like = null)
	{
		$query = "SELECT * FROM Sys.Columns WHERE id = object_id('" . $this->quote_table($table) . "')";

		if (is_string($like))
		{
			// Search for column names
			$query .= " AND name LIKE ".$this->quote($like);
		}

		// Find all column names
		$result = $this->query(\DB::SELECT, $query, false);

		$count = 0;
		$columns = array();
		foreach ($result as $row)
		{
			list($type, $length) = $this->_parse_type($row['Type']);
			$column = $this->datatype($type);
			$column['name']             = $row['Field'];
			$column['default']          = $row['Default'];
			$column['data_type']        = $type;
			$column['null']             = ($row['Null'] == 'YES');
			$column['ordinal_position'] = ++$count;
			switch ($column['type'])
			{
				case 'float':
					if (isset($length))
					{
						list($column['numeric_precision'], $column['numeric_scale']) = explode(',', $length);
					}
				break;
				case 'int':
					if (isset($length))
					{
						$column['display'] = $length;
					}
				break;
				case 'string':
					switch ($column['data_type'])
					{
						case 'binary':
						case 'varbinary':
							$column['character_maximum_length'] = $length;
						break;
						case 'char':
						case 'varchar':
							$column['character_maximum_length'] = $length;
						case 'text':
						case 'tinytext':
						case 'mediumtext':
						case 'longtext':
							$column['collation_name'] = $row['Collation'];
						break;
						case 'enum':
						case 'set':
							$column['collation_name'] = $row['Collation'];
							$column['options'] = explode('\',\'', substr($length, 1, -1));
						break;
					}
				break;
			}
			$column['comment']      = $row['Comment'];
			$column['extra']        = $row['Extra'];
			$column['key']          = $row['Key'];
			$column['privileges']   = $row['Privileges'];
			$columns[$row['Field']] = $column;
		}
		return $columns;
	}

	/**
	 * Set the charset
	 *
	 * @param string $charset
	 */
	public function set_charset($charset)
	{
		// does not support charsets
	}

}


text:
Nevada Projects
Nevada Pediatric Mental Health Care Access Program (PMHCAP)
New Mexico Projects
Care Coordination in New Mexico
Rhode Island Projects
Rhode Island Pediatric Psychiatry Resource Network (PediPRN)
Ohio Projects
Utah Projects
Transition to Adult Healthcare
University of Utah Pediatric Resident Writing Elective
University of Utah Writing & Career Development Group
Utah Children's Care Coordination Network
UCCCN 2017 to 2022
Resources of the Month 2022
Anxiety Disorders & Attention Deficit Hyperactivity Disorder (ADHD)
Attention-Deficit/Hyperactivity Disorder (ADHD) & Disruptive Behaviors
Attention-Deficit/Hyperactivity Disorder (ADHD) & Mood Disorders
Diagnosis Prevalence List
Mucopolysaccharidosis Type I & Motor Development
Mucopolysaccharidosis Type I (MPS 1) Genetics
Mucopolysaccharidosis Type I (MPS 1) Hematopoietic Stem Cell Transplantation & Enzyme Replacement Therapy
Mucopolysaccharidosis Type I (MPS 1) Orthopedic Manifestations & Treatments
Prader-Willi Syndrome & Cognitive & Psychiatric Issues
Prader-Willi Syndrome Nutrition & Diet
Premature Infant Growth Charts
Premature Infant and Low Birthweight
Other Names for Diagnoses & Conditions
Angelman Syndrome
Arginase Deficiency
Biotinidase Deficiency
Charcot-Marie-Tooth Disease (Hereditary Motor Sensory Neuropathy)
Cornelia de Lange Syndrome
Duchenne & Becker Muscular Dystrophy
Fetal Alcohol Spectrum Disorders
Galactosemia
Hearing Loss and Deafness
Intellectual Disability & Global Developmental Delay
LCHAD/TFP Deficiency
Leukodystrophies
Maple Syrup Urine Disease (MSUD)
Mucopolysaccharidosis Type I (MPS 1)
Myotonic Muscular Dystrophy Type 1
Neurofibromatosis Type 1
Obesity in Children
PKU and Pterin Defects
Prader-Willi Syndrome
Premature Infant Follow-Up
Rett Syndrome
Transgender and Gender-Diverse
Tuberous Sclerosis Complex (TSC)
22q11.2 Deletion Syndrome
Tyrosinemia Type 1
VLCADD
XXY (Klinefelter) Syndrome
Bronchopulmonary Dysplasia
Congenital Diaphragmatic Hernia (CDH)
Duchenne & Becker Muscular Dystrophy: Cardiomyopathy
Headache (Migraine & Chronic)
Homocystinuria (Classic)
Lennox-Gastaut Syndrome
MCADD (Medium-Chain Acyl-CoA Dehydrogenase)
Somatic Symptom Disorder & Functional Neurologic Disorders
Adrenoleukodystrophy (ALD)
Argininemia
Argininosuccinic Aciduria
Beta-Ketothiolase Deficiency (BKD)
CACT & CPT II Deficiencies
Carnitine Palmitoyltransferase 1A (CPT 1) Deficiency
Carnitine Uptake Defect
Citrullinemia Type I
Citrullinemia Type II & Citrin Deficiency
Congenital Adrenal Hyperplasia (CAH)
Congenital Hypothyroidism
Critical Congenital Heart Disease (CCHD)
Cystic Fibrosis (CF)
Glutaric Acidemia Type 1
Guanidinoacetate Methyltransferase (GAMT) Deficiency
Hearing Loss & Deafness
HMG-CoA Lyase Deficiency
Holocarboxylase/Multiple Carboxylase Deficiency
Isobutyryl-CoA Dehydrogenase Deficiency
Isovaleric Acidemia
LCHAD & TFP Deficiency
Malonic Acidemia
Medium-Chain Acyl-CoA Dehydrogenase Deficiency (MCADD)
Methylmalonic Acidemias
Pompe Disease
Propionic Acidemia
Pyruvate Carboxylase Deficiency
Severe Combined Immunodeficiency (SCID)
Short/Branched Chain Acyl-CoA Dehydrogenase (SBCAD) Deficiency
Short-Chain Acyl-CoA Dehydrogenase Deficiency (SCADD)
Spinal Muscular Atrophy (SMA)
3MCC Deficiency
3-Methylglutaconic Aciduria (3-MGA)
2M3HBA Deficiency
Very Long-Chain Acyl-CoA Dehydrogenase Deficiency (VLCADD)
The Medical Home Portal owes its existence to the in-kind, financial, and moral support of many individuals and organizations. Listed below are our current partners and other organizations that have provided substantial support to the Portal's development.
Through their Support Life License Donations program, Syncro Soft SRL provides the Medical Home Portal with use of oXygen XML Editor.
The Division of General Pediatrics, Department of Pediatrics, University of Utah Health is the Portal's administrative and academic home.
The Portal's roles in the Pediatric Patient Summary/Medical Home Portal project are supported through the Utah Division of Medicaid and Health Finance's 2017 State Health Information Technology (HIT) Implementation Advance Planning Document-Update (IAPD-U), awarded 9/1/17 by the Centers for Medicare and Medicaid Services (CMS) and the Office of the National Coordinator for Health Information Technology (ONC) with funds allocated by Health Information Technology for Economic and Clinical Health (HITECH) Act of 2009 ( 258 KB), part of the American Recovery and Reinvestment Act (ARRA) of 2009.
The Utah Department of Health & Human Services's, Utah DHHS Family Health Unit, Utah Maternal and Child Health Bureau (UDHHS) provides support and collaboration in the Portal's ongoing development and maintenance of its directory of Utah providers of services for children and youth with special health care needs and their families.
The Nevada Division of Public and Behavioral Health, Nevada Title V Maternal and Child Health Program provides funding and collaboration to develop the Nevada Medical Home Portal and maintain its directory of local service providers for children and youth with special health care needs and their families.
The Rhode Island Title V/Maternal and Child Health Program provides funding and collaboration to develop the Rhode Island Medical Home Portal and to maintain its directory of local service providers for children and youth with special health care needs and their families.
The Children's Medical Services/Children with Special Needs, New Mexico Department of Health and the University of New Mexico Center for Development and Disability collaborate to provide information about local service providers for children and youth with special health care needs and their families for the New Mexico Medical Home Portal.
Utah 2-1-1, a program of United Way of Salt Lake, is a key collaborator, sharing their robust database of human services relevant to children and families.
Utah Family Voices, the Utah chapter of Family Voices, has been a major partner in the Portal's development since its inception.
The Utah Parent Center partners with us, assisting in identifying and categorizing valuable services and other resources for children and families.
Between 2005 and 2017, development of the Medical Home Portal was funded in part by the Health Resources and Services Administration (HRSA), Maternal and Child Health Bureau (MCHB) for its role in supporting the aims of grants H02MC00082, D70MCD4477, H6MMC11061, U22MC16508, and D70MC275500100, each awarded to the Utah Department of Health & Human Services.
The Utah Chapter, American Academy of Pediatrics provides ongoing inspiration and support for the Portal.
Mountain States Regional Genetics Network (MSRGN) offers collaboration with and promotion of the Portal to enhance its use among MSGRN member states and across the Regional Genetics Networks.
Utah Regional Leadership Education in Neurodevelopmental and related Disabilities (URLEND) offers inspiration and collaboration in content development and our focus on families and partnerships.
Institute for Disability Research, Policy & Practice, Utah State University has provided support and collaboration in the Portal's ongoing development and engages us to help implement some of their grant-funded projects.
From 2/2010 thru 2/2016, the Portal was funded in part by a Children's Health Insurance Program Reauthorization Act (CHIPRA) Quality Demonstrations Grant (#1Z0C30547-01-00) awarded to the Utah Division of Medicaid and Health Finance.
The Idaho Department of Health and Welfare and their Idaho CareLine - Idaho 2-1-1 were key partners, providing local services information with funding from a Children's Health Insurance Program Reauthorization Act (CHIPRA) Quality Demonstrations Grant Quality Demonstrations grant, #1Z0C30547-01-00 (2/2010-2/2016).
Development of the Medical Home Portal was supported in part by the National Library of Medicine, grant #1 G08 LM007680-01A2 (3/2006-2/2009) and ARRA Administrative Supplement, 3 G08 LM007680-03S1 (9/2009-9/2010).
Knowledge Weavers, Spencer S. Eccles Health Sciences Library, University of Utah was a key partner and collaborator in the development of the Portal from its inception in 2001 through 2009.
Heartland Genetic Services Network (Arkansas, Iowa, Kansas, Missouri, Nebraska, North Dakota, Oklahoma, and South Dakota) collaborated with the Portal, providing support, content, and genetics-related services listings for their partner states between 2007 and 2010.
Genzyme Corporation, now Sanofi Specialty Care, provided funding at critical junctures in the Portal's development, 200-2008.
Ronald McDonald House Charities, Intermountain Area supported the Portal's acquisition of information about community services between 2005 and 2008.
The Primary Children's Medical Center Foundation, now the Intermountain Foundation at Primary Children's Hospital, provided funding for the very first iteration of the Portal in 2001.
Initial publication: January 2008; last update/revision: September 2019


FDA and other agency's requirements for spreadsheet validation - What do inspectors ask and what documents should be available.
How to design spreadsheets for Part 11/GxP/SOX/HIPAA compliance?
Validation during design, development, installation and on-going use.
Dealing with standard Excel functions: Recommendations from GAMP5.
How to ensure and validate spreadsheet integrity and security for GxP and Part 11?
How to apply risk based validation to spreadsheet applications?
How to document planning, specifications, installation, testing and changes?
Examples from manufacturing, laboratories and offices.


Your cake looks beautiful, and I love the cupcakes with the one fig in the middle, like a little surprise! I'll have to try mission figs, they look really juicy and delicious!
Wonderful looking cake and your figs look so wonderfully rich and delicious! Well done!
Awesome pictures! Great job on the cake.
Little cupcakes! What a great idea! I think I may make it in that form next time, as I'm the only one in my family who liked it. That way I could also just make a half batch and not have too many leftovers.
Yum! Your cake looks delicious. I love the little cupcakes.
Your cake looks great! I really like your pictures.
looks great, and cuppies too!
I love all your pictures. So beautiful. I could see them in Dorie's book! Great job!
Wow! It worked perfectly for you... I used the wrong pan (I know... a goose is smarter than me) and it got a little stuck. But still, it was pretty good.
thanks everyone for your comments! :) i'm glad you liked my photos!
Great photos! The fig hiding in the muffin looks delicious.
Your cake is beautiful, but the cupcakes are genius, well done!
I love the cupcake pic,.....and all the other pictures on your blog!
It look heavenly... what is in the little cup?
thanks again everyone :) Digits-- it is greek style yogurt with honey.
I've been a long time lurker, never actually made anything though, so i thought I'd give this a go!
But i have to ask you, how much butter am i supposed to add.?
I got to that point and had no idea!


text:
package com.roche.heatseq.cli;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.roche.heatseq.objects.ApplicationSettings;
import com.roche.heatseq.process.BamFileValidator;
import com.roche.heatseq.process.FastqReadTrimmer;
import com.roche.heatseq.process.FastqReadTrimmer.ProbeTrimmingInformation;
import com.roche.heatseq.process.FastqValidator;
import com.roche.heatseq.process.InputFilesExistValidator;
import com.roche.heatseq.process.PrimerReadExtensionAndPcrDuplicateIdentification;
import com.roche.heatseq.process.ReadNameTracking;
import com.roche.heatseq.utils.BamFileUtil;
import com.roche.sequencing.bioinformatics.common.alignment.IAlignmentScorer;
import com.roche.sequencing.bioinformatics.common.alignment.SimpleAlignmentScorer;
import com.roche.sequencing.bioinformatics.common.commandline.CommandLineOption;
import com.roche.sequencing.bioinformatics.common.commandline.CommandLineOptionsGroup;
import com.roche.sequencing.bioinformatics.common.commandline.ParsedCommandLine;
import com.roche.sequencing.bioinformatics.common.genome.GenomeIdentifier;
import com.roche.sequencing.bioinformatics.common.utils.DateUtil;
import com.roche.sequencing.bioinformatics.common.utils.FileUtil;
import com.roche.sequencing.bioinformatics.common.utils.LoggingUtil;
import com.roche.sequencing.bioinformatics.common.utils.StringUtil;
import com.roche.sequencing.bioinformatics.common.utils.probeinfo.ParsedProbeFile;
import com.roche.sequencing.bioinformatics.common.utils.probeinfo.ProbeFileUtil;
import com.roche.sequencing.bioinformatics.common.utils.probeinfo.ProbeFileUtil.ProbeHeaderInformation;

import htsjdk.samtools.SAMFileHeader;
import htsjdk.samtools.SAMRecord;
import htsjdk.samtools.SAMRecordIterator;
import htsjdk.samtools.SamReader;
import htsjdk.samtools.SamReaderFactory;
import htsjdk.samtools.ValidationStringency;

public class DeduplicationCli {
	private final static Logger logger = LoggerFactory.getLogger(DeduplicationCli.class);

	private final static int MAX_NUMBER_OF_PROCESSORS = 24;

	public final static int DEFAULT_EXTENSION_UID_LENGTH = 10;
	public final static int DEFAULT_LIGATION_UID_LENGTH = 0;
	private final static String BAM_EXTENSION = ".bam";

	private final static int BYTES_PER_MEGABYTE = 1000000;
	private final static DecimalFormat doubleFormatter = new DecimalFormat("#,###.##");

	final static CommandLineOption USAGE_OPTION = new CommandLineOption("Print Usage", "usage", 'h', "Print Usage.", false, true);
	public final static CommandLineOption FASTQ_ONE_OPTION = new CommandLineOption("FastQ One File", "r1", null,
			"Path to first input fastq file (as an uncompressed file with a fastq extension or a compressed file with the gz extension).", true, false);
	public final static CommandLineOption FASTQ_TWO_OPTION = new CommandLineOption("FastQ Two File", "r2", null,
			"Path to second input fastq file (as an uncompressed file with a fastq extension or a compressed file with the gz extension).", true, false);
	public final static CommandLineOption INPUT_BAM_OPTION = new CommandLineOption("Input BAM or SAM File Path", "inputBam", null, "Path to input BAM or SAM file containing the aligned reads.", true,
			false);
	public final static CommandLineOption PROBE_OPTION = new CommandLineOption("Probe Information File", "probe", null, "NimbleGen probe file.", true, false);
	final static CommandLineOption OUTPUT_DIR_OPTION = new CommandLineOption("Output Directory", "outputDir", null, "Location to store resultant files.", false, false);
	final static CommandLineOption OUTPUT_FILE_PREFIX_OPTION = new CommandLineOption("Output File Prefix", "outputPrefix", null, "Text to put at beginning of output file names.", false, false);
	private final static CommandLineOption TMP_DIR_OPTION = new CommandLineOption("Temporary Directory", "tmpDir", null, "Location to store temporary files.", false, false);
	private final static CommandLineOption NUM_PROCESSORS_OPTION = new CommandLineOption("Number of Processors", "numProcessors", null,
			"The number of threads to run in parallel.  If not specified this will default to the number of cores available on the machine.  The designated value and default value will be capped at "
					+ MAX_NUMBER_OF_PROCESSORS + ".",
			false, false);
	private final static CommandLineOption OUTPUT_BAM_FILE_NAME_OPTION = new CommandLineOption("Output Bam File Name", "outputBamFileName", 'o', "Name for output bam file.", true, false);
	private final static CommandLineOption MATCH_SCORE_OPTION = new CommandLineOption("Match Score", "matchScore", null,
			"The score given to matching nucleotides when extending alignments to the primers. (Default: " + SimpleAlignmentScorer.DEFAULT_MATCH_SCORE + ")", false, false);
	private final static CommandLineOption MISMATCH_PENALTY_OPTION = new CommandLineOption("Mismatch Penalty", "mismatchPenalty", null,
			"The penalty subtracted for mismatched nucleotides when extending alignments to the primers. (Default: " + SimpleAlignmentScorer.DEFAULT_MISMATCH_PENALTY + ")", false, false);
	private final static CommandLineOption GAP_OPEN_PENALTY_OPTION = new CommandLineOption("Gap Open Penalty", "gapOpenPenalty", null,
			"The penalty for opening a gap when extending alignments to the primers. (Default: " + SimpleAlignmentScorer.DEFAULT_GAP_OPEN_PENALTY + ")", false, false);
	private final static CommandLineOption GAP_EXTEND_PENALTY_OPTION = new CommandLineOption("Gap Extend Penalty", "gapExtendPenalty", null,
			"The penalty for extending a gap when extending alignments to the primers. (Default: " + SimpleAlignmentScorer.DEFAULT_GAP_EXTEND_PENALTY + ")", false, false);
	// public final static CommandLineOption LENIENT_VALIDATION_STRINGENCY_OPTION = new CommandLineOption("Lenient Validation Stringency", "lenientValidation", null,
	// "Use a lenient validation stringency for all SAM files read by this program.", false, true);
	private final static CommandLineOption MARK_DUPLICATES_OPTION = new CommandLineOption("Mark Duplicates", "markDuplicates", null, "Mark duplicate reads in the bam file instead of removing them.",
			false, true);
	private final static CommandLineOption KEEP_DUPLICATES_OPTION = new CommandLineOption("Disable Duplicate Removal", "disableDuplicateRemoval", null,
			"Keep duplicate reads in the bam file instead of removing them. ", false, true, true);
	private final static CommandLineOption MERGE_PAIRS_OPTION = new CommandLineOption("Merge Pairs", "mergePairs", null, "Merge pairs using the highest quality base reads from each read.", false,
			true);
	public final static CommandLineOption TRIMMING_SKIPPED_OPTION = new CommandLineOption("Reads Were Not Trimmed Prior to Mapping", "readsNotTrimmed", null,
			"The reads were not trimmed prior to mapping.", false, true, true);
	private final static CommandLineOption INTERNAL_REPORTS_OPTION = new CommandLineOption("Output interal reports", "internalReports", null, "Output internal reports.", false, true, true);
	private final static CommandLineOption EXCLUDE_NEW_PROGRAM_IN_BAM_HEADER_OPTION = new CommandLineOption("Exclude Program in Bam Header", "excludeProgramInBamHeader", null,
			"Don not include a program entry for this application in the bam header.", false, true, true);
	private final static CommandLineOption SAVE_TEMP_OPTION = new CommandLineOption("Save Temp Files", "saveTemp", null, "Save temporary files.", false, true, true);
	private final static CommandLineOption READ_NAMES_TO_TRACK_FILE_OPTION = new CommandLineOption("Read Names To Track File", "trackReadNamesFile", null,
			"File with line delimited read names (or indexes) to track in the log.", false, false, true);
	final static CommandLineOption VERSION_OPTION = new CommandLineOption("Print Version", "version", null, "Print the version for this application.", false, true);

	// Note: these variables are for debugging purposes
	// saveTemporaryFiles default is false
	private static boolean saveTemporaryFiles = false;
	// allowVaraibleLengthUids default is false
	private final static boolean allowVariableLengthUids = false;
	// useStrictReadToProbeMatching default is false
	private final static boolean useStrictReadToProbeMatching = false;
	private final static boolean useLenientValidation = true;

	static void identifyDuplicates(ParsedCommandLine parsedCommandLine, String commandLineSignature, String applicationName, String applicationVersion) {

		long applicationStart = System.currentTimeMillis();
		CliStatusConsole.logStatus("Deduplication has started at " + DateUtil.convertTimeInMillisecondsToDate(applicationStart) + "(YYYY/MM/DD HH:MM:SS)." + StringUtil.NEWLINE);

		String outputDirectoryString = parsedCommandLine.getOptionsValue(OUTPUT_DIR_OPTION);
		File outputDirectory = null;
		if (outputDirectoryString != null) {
			outputDirectory = new File(outputDirectoryString);
			if (!outputDirectory.exists()) {
				try {
					FileUtil.createDirectory(outputDirectory);
				} catch (IOException e) {
					throw new IllegalStateException("Could not create provided output directory[" + outputDirectory.getAbsolutePath() + "].", e);
				}
			}
			if (!outputDirectory.isDirectory()) {
				throw new IllegalStateException("Provided output directory[" + outputDirectory.getAbsolutePath() + "] is not valid.");
			}
		} else {
			// current working directory
			outputDirectory = new File(".");
		}

		String outputFilePrefix = parsedCommandLine.getOptionsValue(OUTPUT_FILE_PREFIX_OPTION);
		String sampleName = "";
		if (outputFilePrefix == null) {
			outputFilePrefix = "";
		} else if (!outputFilePrefix.isEmpty() && outputFilePrefix.charAt(outputFilePrefix.length() - 1) != '_') {
			// Add an underscore as a separation character for the prefix if there is not already an underscore as the last prefix character
			sampleName = outputFilePrefix;
			outputFilePrefix = outputFilePrefix + "_";
		}

		File logFile = HsqUtilsCli.getLogFile(outputDirectory, outputFilePrefix, applicationName, "dedup");

		try {
			LoggingUtil.setLogFile(HsqUtilsCli.FILE_LOGGER_NAME, logFile);
		} catch (IOException e2) {
			throw new IllegalStateException("Unable to create log file at " + logFile.getAbsolutePath() + ".", e2);
		}
		logger.info(applicationName + " version:" + applicationVersion);
		logger.info("command line signature: " + commandLineSignature);
		String tempDirectoryString = parsedCommandLine.getOptionsValue(TMP_DIR_OPTION);
		File tempDirectory = null;
		if (tempDirectoryString != null) {
			tempDirectory = new File(tempDirectoryString);
			try {
				FileUtil.createDirectory(tempDirectory);
			} catch (IOException e) {
				throw new IllegalStateException("Unable to create provided temporary directory[" + tempDirectory.getAbsolutePath() + "].");
			}
			if (!tempDirectory.exists() || !tempDirectory.isDirectory()) {
				throw new IllegalStateException("Unable to find provided temporary directory[" + tempDirectory.getAbsolutePath() + "].");
			}
		} else {
			// default temp directory
			tempDirectory = FileUtil.getSystemSpecificTempDirectory();
		}

		File fastQ1File = new File(parsedCommandLine.getOptionsValue(FASTQ_ONE_OPTION));
		File fastQ2File = new File(parsedCommandLine.getOptionsValue(FASTQ_TWO_OPTION));
		File probeInfoFile = new File(parsedCommandLine.getOptionsValue(PROBE_OPTION));
		String bamFileString = parsedCommandLine.getOptionsValue(INPUT_BAM_OPTION);
		File samOrBamFile = new File(bamFileString);

		if (parsedCommandLine.isOptionPresent(READ_NAMES_TO_TRACK_FILE_OPTION)) {
			File readTrackingFile = new File(parsedCommandLine.getOptionsValue(READ_NAMES_TO_TRACK_FILE_OPTION));
			try {
				String readNames = FileUtil.readFileAsString(readTrackingFile);
				for (String readName : readNames.split(StringUtil.NEWLINE)) {
					ReadNameTracking.addReadNameToTrack(readName);
				}
			} catch (IOException e) {
				logger.warn(e.getMessage(), e);
			}

		}

		InputFilesExistValidator.validate(fastQ1File, fastQ2File, probeInfoFile, samOrBamFile);

		int numberOfRecordsInFastq = FastqValidator.validateAndGetNumberOfRecords(fastQ1File, fastQ2File);

		ParsedProbeFile parsedProbeFile = ProbeFileUtil.parseProbeInfoFileWithValidation(probeInfoFile);

		long requiredTempSpaceInBytes = fastQ1File.length() * 4;
		long usableTempSpaceInBytes = tempDirectory.getUsableSpace();
		if (usableTempSpaceInBytes <= requiredTempSpaceInBytes) {
			throw new IllegalStateException("The amount of temporary storage space required by this application is "
					+ doubleFormatter.format((double) requiredTempSpaceInBytes / (double) BYTES_PER_MEGABYTE) + "MB which is greater than the amount of usable space["
					+ doubleFormatter.format((double) usableTempSpaceInBytes / (double) BYTES_PER_MEGABYTE) + "MB] in the temp directory[" + tempDirectory.getAbsolutePath() + "].");
		}
		long requiredOutputSpaceInBytes = fastQ1File.length() * 2;
		long usableOutputSpaceInBytes = outputDirectory.getUsableSpace();
		if (usableOutputSpaceInBytes <= requiredOutputSpaceInBytes) {
			throw new IllegalStateException("The amount of storage space required by this application's output is "
					+ doubleFormatter.format((double) requiredOutputSpaceInBytes / (double) BYTES_PER_MEGABYTE) + "MB which is greater than the amount of usable space ["
					+ doubleFormatter.format((double) usableOutputSpaceInBytes / (double) BYTES_PER_MEGABYTE) + "MB]  in the output directory[" + outputDirectory.getAbsolutePath() + "].");
		}

		int numProcessors = Runtime.getRuntime().availableProcessors();
		if (parsedCommandLine.isOptionPresent(NUM_PROCESSORS_OPTION)) {
			try {
				numProcessors = Integer.parseInt(parsedCommandLine.getOptionsValue(NUM_PROCESSORS_OPTION));

			} catch (NumberFormatException ex) {
				throw new IllegalStateException("Value specified for number of processors is not an integer[" + parsedCommandLine.getOptionsValue(NUM_PROCESSORS_OPTION) + "].");
			}
		}
		if (numProcessors > MAX_NUMBER_OF_PROCESSORS) {
			logger.info("The requested number of processors[" + numProcessors + "] is greater than the max number of processors allowed [" + MAX_NUMBER_OF_PROCESSORS
					+ "] so the max number of processors allowed will be used.");
			numProcessors = MAX_NUMBER_OF_PROCESSORS;
		}

		int extensionUidLength = DEFAULT_EXTENSION_UID_LENGTH;
		int ligationUidLength = DEFAULT_LIGATION_UID_LENGTH;
		String genomeNameFromProbeInfoFile = null;
		ProbeHeaderInformation probeHeaderInformation = null;
		boolean isGenomeNameFromProbeFileIsRecognized = false;
		try {
			probeHeaderInformation = ProbeFileUtil.extractProbeHeaderInformation(probeInfoFile);
			if (probeHeaderInformation != null) {
				genomeNameFromProbeInfoFile = probeHeaderInformation.getGenomeName();
				if (genomeNameFromProbeInfoFile != null) {
					isGenomeNameFromProbeFileIsRecognized = GenomeIdentifier.isGenomeNameRecognized(genomeNameFromProbeInfoFile);
					if (!isGenomeNameFromProbeFileIsRecognized) {
						CliStatusConsole.logStatus("WARNING: This version of HSQutils does not recognize the specified genome build [" + genomeNameFromProbeInfoFile
								+ "] and cannot verify that the BAM file header matches the indicated reference sequence.");
					}
				} else {
					CliStatusConsole.logStatus("Genome information was not found in the header of the probe information file.");
				}

				if (probeHeaderInformation.getExtensionUidLength() != null) {
					extensionUidLength = probeHeaderInformation.getExtensionUidLength();
				}
				if (probeHeaderInformation.getLigationUidLength() != null) {
					ligationUidLength = probeHeaderInformation.getLigationUidLength();
				}
			} else {
				CliStatusConsole.logStatus("There was no header found in the probe information file[" + probeInfoFile.getAbsolutePath() + "].");
			}
		} catch (FileNotFoundException e1) {
			// this should be picked up when the probe info file is originally validated
			throw new AssertionError();
		}

		String outputBamFileName = parsedCommandLine.getOptionsValue(OUTPUT_BAM_FILE_NAME_OPTION);
		if (outputBamFileName.contains("/") || outputBamFileName.contains("\\")) {
			throw new IllegalStateException("The value specified for " + OUTPUT_BAM_FILE_NAME_OPTION.getOptionName() + "[" + outputBamFileName
					+ "] contains a full file path but only a file name should be specified.  Use parameter --" + OUTPUT_DIR_OPTION.getLongFormOption() + " to specify the output directory.");
		}
		if (!outputBamFileName.endsWith(BAM_EXTENSION)) {
			outputBamFileName += BAM_EXTENSION;
		}

		// Set up our alignment scorer
		double matchScore = SimpleAlignmentScorer.DEFAULT_MATCH_SCORE;
		double mismatchPenalty = SimpleAlignmentScorer.DEFAULT_MISMATCH_PENALTY;
		double gapOpenPenalty = SimpleAlignmentScorer.DEFAULT_GAP_OPEN_PENALTY;
		double gapExtendPenalty = SimpleAlignmentScorer.DEFAULT_GAP_EXTEND_PENALTY;

		if (parsedCommandLine.isOptionPresent(MATCH_SCORE_OPTION)) {
			try {
				matchScore = Integer.parseInt(parsedCommandLine.getOptionsValue(MATCH_SCORE_OPTION));
				if (matchScore < 0) {
					throw new IllegalStateException("Value specified for match score must be >= 0 [" + parsedCommandLine.getOptionsValue(MATCH_SCORE_OPTION) + "].");
				}
			} catch (NumberFormatException ex) {
				throw new IllegalStateException("Value specified for match score is not an integer[" + parsedCommandLine.getOptionsValue(MATCH_SCORE_OPTION) + "].");
			}
		}
		if (parsedCommandLine.isOptionPresent(MISMATCH_PENALTY_OPTION)) {
			try {
				mismatchPenalty = -Integer.parseInt(parsedCommandLine.getOptionsValue(MISMATCH_PENALTY_OPTION));
				if (mismatchPenalty > 0) {
					throw new IllegalStateException("Value specified for mismatch penalty must be >= 0 [" + parsedCommandLine.getOptionsValue(MISMATCH_PENALTY_OPTION) + "].");
				}
			} catch (NumberFormatException ex) {
				throw new IllegalStateException("Value specified for mismatch penalty is not an integer[" + parsedCommandLine.getOptionsValue(MISMATCH_PENALTY_OPTION) + "].");
			}
		}
		if (parsedCommandLine.isOptionPresent(GAP_OPEN_PENALTY_OPTION)) {
			try {
				gapOpenPenalty = -Integer.parseInt(parsedCommandLine.getOptionsValue(GAP_OPEN_PENALTY_OPTION));
				if (gapOpenPenalty > 0) {
					throw new IllegalStateException("Value specified for gap open penalty must be >= 0 [" + parsedCommandLine.getOptionsValue(GAP_OPEN_PENALTY_OPTION) + "].");
				}
			} catch (NumberFormatException ex) {
				throw new IllegalStateException("Value specified for gap open penalty is not an integer[" + parsedCommandLine.getOptionsValue(GAP_OPEN_PENALTY_OPTION) + "].");
			}
		}
		if (parsedCommandLine.isOptionPresent(GAP_EXTEND_PENALTY_OPTION)) {
			try {
				gapExtendPenalty = -Integer.parseInt(parsedCommandLine.getOptionsValue(GAP_EXTEND_PENALTY_OPTION));
				if (gapExtendPenalty > 0) {
					throw new IllegalStateException("Value specified for gap extend penalty must be >= 0 [" + parsedCommandLine.getOptionsValue(GAP_EXTEND_PENALTY_OPTION) + "].");
				}
			} catch (NumberFormatException ex) {
				throw new IllegalStateException("Value specified for gap extend penalty not an integer[" + parsedCommandLine.getOptionsValue(GAP_EXTEND_PENALTY_OPTION) + "].");
			}
		}

		// boolean useLenientValidation = parsedCommandLine.isOptionPresent(LENIENT_VALIDATION_STRINGENCY_OPTION);
		if (useLenientValidation) {
			SamReaderFactory.setDefaultValidationStringency(ValidationStringency.LENIENT);
		}

		boolean markDuplicates = parsedCommandLine.isOptionPresent(MARK_DUPLICATES_OPTION);
		boolean keepDuplicates = parsedCommandLine.isOptionPresent(KEEP_DUPLICATES_OPTION);
		boolean shouldOutputInternalReports = parsedCommandLine.isOptionPresent(INTERNAL_REPORTS_OPTION);
		boolean shouldExcludeProgramInBamHeader = parsedCommandLine.isOptionPresent(EXCLUDE_NEW_PROGRAM_IN_BAM_HEADER_OPTION);
		saveTemporaryFiles = parsedCommandLine.isOptionPresent(SAVE_TEMP_OPTION);

		if (markDuplicates && keepDuplicates) {
			throw new IllegalStateException(MARK_DUPLICATES_OPTION.getLongFormOption() + " and " + KEEP_DUPLICATES_OPTION.getLongFormOption() + " cannot be used in the same run.");
		}

		boolean mergePairs = parsedCommandLine.isOptionPresent(MERGE_PAIRS_OPTION);

		IAlignmentScorer alignmentScorer = new SimpleAlignmentScorer(matchScore, mismatchPenalty, gapExtendPenalty, gapOpenPenalty, false);

		try {
			BamFileValidator.validate(samOrBamFile);

			String tempPrefix = HsqUtilsCli.getTempPrefix(applicationName, outputFilePrefix);
			Path tempOutputDirectoryPath = null;
			try {
				tempOutputDirectoryPath = Files.createTempDirectory(tempDirectory.toPath(), tempPrefix);
			} catch (Exception e) {
				throw new IllegalStateException("Unable to create temp directory at [" + tempDirectory.toString() + "].", e);
			}
			final File tempOutputDirectory = tempOutputDirectoryPath.toFile();
			// Delete our temporary directory when we shut down the JVM if the user hasn't asked us to keep it
			if (!saveTemporaryFiles) {
				Runtime.getRuntime().addShutdownHook(new Thread() {
					@Override
					public void run() {
						try {
							FileUtil.deleteDirectory(tempOutputDirectory);
						} catch (IOException e) {
							CliStatusConsole.logStatus("Couldn't delete temp directory [" + tempOutputDirectory.getAbsolutePath() + "]:" + e.getMessage());
						}
					}
				});
			}

			try (SamReader samReader = SamReaderFactory.makeDefault().open(samOrBamFile);) {
				SAMFileHeader header = samReader.getFileHeader();

				try {
					if (genomeNameFromProbeInfoFile != null && isGenomeNameFromProbeFileIsRecognized) {
						header = samReader.getFileHeader();
						Map<String, Integer> containerSizesByNameFromBam = BamFileUtil.getContainerSizesFromHeader(header);

						List<String> containerNamesToRemove = new ArrayList<String>();

						// remove any containers that are not in the probe info file
						for (String containerNameFromBam : containerSizesByNameFromBam.keySet()) {
							if (!parsedProbeFile.containsSequenceName(containerNameFromBam)) {
								containerNamesToRemove.add(containerNameFromBam);
							}
						}

						for (String containerNameToRemove : containerNamesToRemove) {
							containerSizesByNameFromBam.remove(containerNameToRemove);
						}

						String matchingGenomeBasedOnContainerSizes = GenomeIdentifier.getMatchingGenomeName(containerSizesByNameFromBam);
						if (matchingGenomeBasedOnContainerSizes == null) {
							String message = "The genome used for mapping is not a recognized genome so the system cannot verify that it matches the provided genome[" + genomeNameFromProbeInfoFile
									+ "] from the probe information file.";
							logger.info(message);
							CliStatusConsole.logStatus(message);
						} else if (!genomeNameFromProbeInfoFile.equals(matchingGenomeBasedOnContainerSizes)) {
							logger.info("Mismatch Genome Report" + StringUtil.NEWLINE + GenomeIdentifier.createMismatchGenomeReportText(genomeNameFromProbeInfoFile, containerSizesByNameFromBam));
							CliStatusConsole.logStatus(StringUtil.NEWLINE + "WARNING:");
							CliStatusConsole.logStatus(
									"It appears that the incorrect genome was used for mapping.  The names and sizes of the genome sequences used for mapping found in the provided BAM/SAM file ["
											+ samOrBamFile.getAbsolutePath() + "] do not match the sequence sizes expected based on the indicated genome build [" + genomeNameFromProbeInfoFile
											+ "] by the probe information file [" + probeInfoFile.getAbsolutePath()
											+ "].  Deduplication will continue but the results should be classified as suspect.  Please review the mismatch genome report in the log file["
											+ logFile.getCanonicalPath() + "] for details on how the expected genome and provided genome differ." + StringUtil.NEWLINE);
						}
					}
				} catch (FileNotFoundException e1) {
					throw new IllegalStateException("Could not find the provided BAM file[" + samOrBamFile.getAbsolutePath() + "].");
				}

			}

			try (SamReader samReader = SamReaderFactory.makeDefault().open(samOrBamFile)) {
				SAMRecordIterator samIter = samReader.iterator();

				boolean noEntriesInBam = false;
				boolean aPairedReadOneFound = false;
				boolean aPairedReadTwoFound = false;

				if (!samIter.hasNext()) {
					noEntriesInBam = true;
				} else {
					samLoop: while (samIter.hasNext()) {
						SAMRecord record = samIter.next();

						if (record.getReadPairedFlag()) {
							aPairedReadOneFound = aPairedReadOneFound || record.getFirstOfPairFlag();
							aPairedReadTwoFound = aPairedReadTwoFound || record.getSecondOfPairFlag();
							if (aPairedReadOneFound && aPairedReadTwoFound) {
								break samLoop;
							}
						}
					}
				}
				samIter.close();

				if (noEntriesInBam) {
					throw new IllegalStateException("The provided BAM file[" + samOrBamFile.getAbsolutePath() + "] contains no entries.");
				} else if (!aPairedReadOneFound && !aPairedReadTwoFound) {
					throw new IllegalStateException("The provided BAM file[" + samOrBamFile.getAbsolutePath() + "] contains no paired read entries.  Paired reads are required for deduplication.");
				} else if (!aPairedReadOneFound) {
					throw new IllegalStateException("The provided BAM file[" + samOrBamFile.getAbsolutePath() + "] contains no read one entries.");
				} else if (!aPairedReadTwoFound) {
					throw new IllegalStateException("The provided BAM file[" + samOrBamFile.getAbsolutePath() + "] contains no read two entries.");
				}

			}

			boolean readsNotTrimmed = parsedCommandLine.isOptionPresent(TRIMMING_SKIPPED_OPTION);

			ProbeTrimmingInformation probeTrimmingInformation;
			try {
				probeTrimmingInformation = FastqReadTrimmer.getProbeTrimmingInformation(parsedProbeFile, probeInfoFile, !readsNotTrimmed);
			} catch (IOException e1) {
				throw new IllegalStateException("Unable to read probe file[" + probeInfoFile + "].");
			}

			sortMergeFilterAndExtendReads(applicationName, applicationVersion, probeInfoFile, parsedProbeFile, samOrBamFile, fastQ1File, fastQ2File, outputDirectory, outputBamFileName,
					outputFilePrefix, tempOutputDirectory, shouldOutputInternalReports, shouldExcludeProgramInBamHeader, commandLineSignature, numProcessors, extensionUidLength, ligationUidLength,
					allowVariableLengthUids, alignmentScorer, markDuplicates, keepDuplicates, mergePairs, useStrictReadToProbeMatching, readsNotTrimmed, probeHeaderInformation, sampleName,
					numberOfRecordsInFastq, probeTrimmingInformation);

			// TODO do not make the original creation of prelim output bam be sorted
			// TODO sort the output bam based on readnames and readnumbers
			// TODO create new bam that contains read names from fastq
			// TODO sort new bam by coords

			long applicationStop = System.currentTimeMillis();
			CliStatusConsole.logStatus("Deduplication has completed successfully.");
			CliStatusConsole.logStatus(
					"Start Time: " + DateUtil.convertTimeInMillisecondsToDate(applicationStart) + "(YYYY/MM/DD HH:MM:SS)  Stop Time: " + DateUtil.convertTimeInMillisecondsToDate(applicationStop)
							+ "(YYYY/MM/DD HH:MM:SS)  Total Time: " + DateUtil.convertMillisecondsToHHMMSS(applicationStop - applicationStart) + "(HH:MM:SS)" + StringUtil.NEWLINE);

		} catch (Exception e) {
			throw new IllegalStateException(e.getMessage(), e);
		}
	}

	private static void sortMergeFilterAndExtendReads(String applicationName, String applicationVersion, File probeFile, ParsedProbeFile parsedProbeFile, File bamFile, File fastQ1File,
			File fastQ2File, File outputDirectory, String outputBamFileName, String outputFilePrefix, File tempOutputDirectory, boolean shouldOutputReports, boolean shouldExcludeProgramInBamHeader,
			String commandLineSignature, int numProcessors, int extensionUidLength, int ligationUidLength, boolean allowVariableLengthUids, IAlignmentScorer alignmentScorer, boolean markDuplicates,
			boolean keepDuplicates, boolean mergePairs, boolean useStrictReadToProbeMatching, boolean readsNotTrimmed, ProbeHeaderInformation probeHeaderInformation, String sampleName,
			int numberOfRecordsInFastq, ProbeTrimmingInformation probeTrimmingInformation) {
		try {

			long totalTimeStart = System.currentTimeMillis();
			ApplicationSettings applicationSettings = new ApplicationSettings(probeFile, parsedProbeFile, bamFile, fastQ1File, fastQ2File, outputDirectory, tempOutputDirectory, outputBamFileName,
					outputFilePrefix, bamFile.getName(), shouldOutputReports, shouldExcludeProgramInBamHeader, commandLineSignature, applicationName, applicationVersion, numProcessors,
					allowVariableLengthUids, alignmentScorer, extensionUidLength, ligationUidLength, markDuplicates, keepDuplicates, mergePairs, useStrictReadToProbeMatching, probeHeaderInformation,
					readsNotTrimmed, sampleName, numberOfRecordsInFastq, probeTrimmingInformation);

			PrimerReadExtensionAndPcrDuplicateIdentification.verifyReadNamesCanBeHandledByDedup(applicationSettings.getFastQ1File(), applicationSettings.getFastQ2File());

			PrimerReadExtensionAndPcrDuplicateIdentification extendReadsAndIdentifyDuplicates = new PrimerReadExtensionAndPcrDuplicateIdentification();
			extendReadsAndIdentifyDuplicates.filterBamEntriesByUidAndExtendReadsToPrimers(applicationSettings);

			long totalTimeStop = System.currentTimeMillis();
			logger.debug("done - Total time: (" + DateUtil.convertMillisecondsToHHMMSS(totalTimeStop - totalTimeStart) + ")");
		} catch (Exception e) {
			throw new IllegalStateException(e.getMessage(), e);
		}
	}

	static CommandLineOptionsGroup getCommandLineOptionsGroup() {
		CommandLineOptionsGroup group = new CommandLineOptionsGroup();

		group.addOption(USAGE_OPTION);
		group.addOption(VERSION_OPTION);
		group.addOption(FASTQ_ONE_OPTION);
		group.addOption(FASTQ_TWO_OPTION);
		group.addOption(PROBE_OPTION);
		group.addOption(INPUT_BAM_OPTION);
		group.addOption(OUTPUT_DIR_OPTION);
		group.addOption(OUTPUT_BAM_FILE_NAME_OPTION);
		group.addOption(OUTPUT_FILE_PREFIX_OPTION);
		group.addOption(TMP_DIR_OPTION);
		group.addOption(NUM_PROCESSORS_OPTION);
		group.addOption(SAVE_TEMP_OPTION);
		group.addOption(TRIMMING_SKIPPED_OPTION);

		// group.addOption(MATCH_SCORE_OPTION);
		// group.addOption(MISMATCH_PENALTY_OPTION);
		// group.addOption(GAP_OPEN_PENALTY_OPTION);
		// group.addOption(GAP_EXTEND_PENALTY_OPTION);
		// group.addOption(LENIENT_VALIDATION_STRINGENCY_OPTION);
		group.addOption(MARK_DUPLICATES_OPTION);
		group.addOption(KEEP_DUPLICATES_OPTION);
		// group.addOption(MERGE_PAIRS_OPTION);
		// group.addOption(NOT_TRIMMED_TO_WITHIN_CAPTURE_TARGET_OPTION);
		group.addOption(INTERNAL_REPORTS_OPTION);
		group.addOption(READ_NAMES_TO_TRACK_FILE_OPTION);
		group.addOption(EXCLUDE_NEW_PROGRAM_IN_BAM_HEADER_OPTION);
		return group;
	}
}


The Amnesic Incognito Live System (Tails) is a Debian-based distribution which is designed for anonymous web browsing and communication over the Internet. The Tails project has announced the availability of Tails 2.11. The new version features a number of bug fixes, including a fix for local root privilege escalation and the Tor Browser has been updated to version 6.5.1. The project has also reported the alternative anonymizing network utility I2P will be dropped in future versions of the distribution: "We are very sad to announce that Tails 2.11 will be the last version to include I2P, an alternative anonymizing network. Maintaining software like I2P well-integrated in Tails takes time and effort and our team is too busy with other priorities. Unfortunately, we failed to find a developer outside of our team to maintain I2P in Tails. As a consequence, the last version of I2P being shipped in Tails is 0.9.25, which is nearly one year old now at this moment. But we will be happy to reintroduce I2P if we find a volunteer to take care of maintaining it in Tails.


text:
Q: Has the pronunciation of 'heretic' changed over time? One says 'HERetic' and 'heRETical' and I was wondering if 'heRETic' is or has ever been correct, or v.v. 'HERetical' (doesn't feel ok')

A: Note that accented syllables can vary greatly especially between US and UK versions.

I'm British and I have only ever heard 'HERetic' for the noun.
If I heard 'heRETic' I would assume it was intended as an adjective not a noun - an abbreviation of 'heRETical'
Examples
Pelagius was a British HERetic. (noun)
Pelagius was a heRETical Briton. (adjective)
Pelagius was a heRETic Briton. (not standard usage but I would assume it was a form of "heretical")

A:
I was wondering if 'heRETic' is or has ever been correct, or v.v. 'HERetical'

No.
Lawrence is right in thinking that the stress in English is typically placed on the antepenultimate syllable.
Although heretic ends with -ic, it's a noun. I think the -ic in 'heretic' is not a suffix.
Words that end with the suffix -ic are usually stressed on the penultimate syllable (second last syllable).
Examples: Historic, ecstatic, empathetic etc.
Most nouns are usually stressed on the first syllable. So 'heretic' is stressed on the first syllable and is pronounced /'herətɪk/.
On the other hand, heretical is an adjective and adjectives that end with -ical are usually stressed on the antepenultimate syllable (third-last syllable), so 'heretical' is stressed on the antepenult: /hə'retɪk(ə)l/.
Other words that end with -ical and are stressed on the antepenult are historical, empirical, cynical etc.