content
stringlengths
10
4.9M
<filename>plugins/default/arcadePhysics2D/components/ArcadeBody2DUpdater.ts<gh_stars>0 import ArcadeBody2DMarker from "./ArcadeBody2DMarker"; import { ConfigPub } from "../componentConfigs/ArcadeBody2DConfig"; export default class ArcadeBody2DUpdater { projectClient: SupClient.ProjectClient; bodyRenderer: ArcadeBody2DMarker; config: ConfigPub; resource: any; constructor(projectClient: SupClient.ProjectClient, bodyRenderer: ArcadeBody2DMarker, config: ConfigPub) { this.projectClient = projectClient; this.bodyRenderer = bodyRenderer; this.config = config; this.setType(); } destroy() { /* Ignore */ } config_setProperty(path: string, value: any) { if (path === "width" || path === "height") this.bodyRenderer.setBox(this.config.width, this.config.height); if (path === "offset.x" || path === "offset.y") this.bodyRenderer.setOffset(this.config.offset.x, this.config.offset.y); if (path === "type") this.setType(); } setType() { if (this.config.type === "box") { this.bodyRenderer.setBox(this.config.width, this.config.height); this.bodyRenderer.setOffset(this.config.offset.x, this.config.offset.y); } else this.bodyRenderer.setTileMap(); } }
SALT LAKE CITY — Authorities say a Utah woman pulled two of her son’s teeth in a Walmart restroom. Prosecutors said Monday that the 47-year-old woman bought hand sanitizer and needle-nose pliers from the store, then took them into the restroom and pulled two of her 7-year-old son’s teeth. Police in American Fork, Utah, say the boy’s older brother heard the child screaming and got him out of the restroom on April 2. Charging documents say the boy told his brother that one of the teeth was loose, but the other was only slightly loose. Prosecutors say the woman didn’t use any kind of anesthetic. The woman was charged with felony child abuse. No attorney was immediately listed for her in court records. The Associated Press is not naming her to avoid identifying the child.
// Match returns true if the given path matches the any pattern. If the // pattern is meant for directories only, and the path is not a directory, // Match will return false. The matching is performed by recursively applying // fnmatch() with flags set to FNM_PATHNAME. It is assumed path is relative to // the base path of the owning GitIgnore. func (a *any) Match(path string, isdir bool) bool { if a._directory && !isdir { return false } _parts := strings.Split(path, string(_SEPARATOR)) return a.match(_parts, a._tokens) }
Protecting children from smoke exposure in disadvantaged homes. INTRODUCTION Smoke-free legislation and shifting norms in many countries have reduced secondhand smoke (SHS) exposure, but many children, particularly from disadvantaged homes, have high levels of exposure in homes and cars. We explored the particular challenges mothers who smoke face when attempting to protect their children from SHS exposure in disadvantaged homes. METHODS We conducted semi-structured interviews with 22 disadvantaged mothers of children aged 1-3 years in Scotland, using an innovative floor plan method to prompt accounts. Interviews were analyzed thematically. RESULTS Disadvantaged mothers reported attempting to protect their children from both SHS and becoming smokers, motivated by the perceived future health and financial burdens these entail. The variable strategies used to protect children during early childhood were constrained and/or facilitated by limited and changing living circumstances, single parenthood, increasing child mobility and awareness of parental smoking, and complex social relationships. In the context of several intersecting dimensions of disadvantage (unemployment, low income, alcohol/drug abuse, and domestic abuse), the imperative to be and to be seen to be a good mother was also key in shaping smoking practices in the home. CONCLUSIONS Challenging and changing domestic living circumstances and relationships and the increasing mobility of children in their first few years are key barriers to creating smoke-free homes for disadvantaged mothers. Key facilitators include mothers' concerns about children's increasing awareness of smoking and moving to accommodation with accessible outdoor space. Targeted public health initiatives need to acknowledge and support disadvantaged parents' existing motivations and attempts to protect children from both SHS and becoming smokers.
<gh_stars>0 package leveldb import ( "sync" "time" "github.com/syndtr/goleveldb/leveldb" "github.com/syndtr/goleveldb/leveldb/opt" ) const ( _DefaultCleanTimeout = time.Hour _DefaultMaxAge = time.Second * 31556926 ) // Interface is an interface type Interface interface { // Load loads the values Load(string) map[string]interface{} // Update updates the store Update(string, map[string]interface{}) } // impl is an implementation type impl struct { DB *leveldb.DB Cfg Config Err error doCloseUp chan bool doCloseDone sync.WaitGroup } // Config the leveldb configuration used inside sessions type Config struct { // Path to leveldb database Path string // Options LevelDB open database options Options *Options // ReadOptions LevelDB read database options ReadOptions *ReadOptions // WriteOptions LevelDB write database options WriteOptions *WriteOptions // CleanTimeout Waiting between starting database cleaning and compression. Default one hour CleanTimeout time.Duration // MaxAge how much long the LevelDB should keep the session. Default 1 year MaxAge time.Duration } // Options LevelDB open database options type Options opt.Options // ReadOptions LevelDB read database options type ReadOptions opt.ReadOptions // WriteOptions LevelDB write database options type WriteOptions opt.WriteOptions
00:00:00 John Donvan: What did Martin Luther King, Jr. have in common with Richard Nixon and with 18th century revolutionary Thomas Paine, author of Common Sense? Well, all three thought it was common sense to guarantee to every citizen who breathes a set amount of cash of every year, essentially as a right, and firstly, to protect against poverty. Nowadays, that idea is flying high again. And in fact, it’s being tried out in places like Finland and Canada and Kenya, and some are saying it is time to try it here in the United States. A universal basic income, a UBI of, say, $10,000 per American per year, with no strings attached. And is that a good thing? Is it the answer to some future predicted doomsday where robots will be crushing human employment? Will it give people room to pursue passions and not just a paycheck? Or is it wrongheaded and even dangerous to start telling people, “Don’t worry so much about work anymore, the UBI will take care of you.” 00:01:07 Well, all of that sounds to us like the makings of a debate, so let’s have it. Yes or no to this statement, “The Universal Basic Income is the Safety Net of the Future.” A debate from Intelligence Squared U.S. I’m John Donvan, and I stand between two teams of two, experts in the topic who will argue for and against the motion. As always, our debate will go in three rounds and then our audience here at the Kaufman Music Center in New York City will choose the winner. And if all goes well, civil discourse will win, too. Our motion is this, “The Universal Basic Income is the Safety Net of the Future.” First, let’s welcome the team arguing for the motion. Please welcome, first, Charles Murray. [applause] And, hi, Charles, welcome. Welcome, Charles. Tell us who your partner is. 00:02:00 Charles Murray: My partner is Andy Stern. John Donvan: Ladies and gentlemen, Andy Stern. [applause] So, I -- we do have a strange bedfellow paring on this side. Charles Murray is a libertarian-leaning political scientist at the American Enterprise Institute. Andrew Stern for 14 years was president of the Service Employees International Union, the country’s second largest union. So, you have a conservative academic, you have a liberal union man. Can you each tell me how this is going to work between the two of you? Charles, why don’t you go first? Charles Murray: It’s going to work great. I met Andy at a panel we were on together last August, and about 15 minutes in, I said, “I like this guy.” John Donvan: And how about you, Andy? Andrew Stern: John, I think you should never underestimate the power of a transformational idea. John Donvan: So, it brought you together. Ladies and gentlemen, the team arguing for the motion. [applause] That motion again, “The Universal Basic Income is the Safety Net of the Future.” We have two debaters arguing against it. First, let’s welcome Jared Bernstein. [applause] 00:03:00 Jared, welcome back. Your second debate with us. You’re a senior fellow at the Center on Budget and Policy Priorities. Before that, you were Vice President Biden’s economic adviser. You are also Charles Murray’s, your opponent’s, frequent sparring partner. You have debated over the UBI in the past. And among all of the issues, all of the many issues that the two of you disagree on, does the UBI make it to the top of the list? Jared Bernstein: Well, that’s a long list, but UBI would be at the top. It’s an idea that sounds benign, and while I wish I could like it, my fear is that it puts economically vulnerable people seriously at risk. John Donvan: Okay, so we see where you’re going. And can you tell us who your partner is? Jared Bernstein: My partner and my friend is Jason Furman. John Donvan: Ladies and gentlemen, Jason Furman. [applause] Hi, Jason, and you were chairman of the Council of Economic Advisers, where you served as President Obama’s chief economist. 00:04:00 The Washington Post has described you as the White House’s wonkiest wonk. They even tracked down your old college roommate, and your college roommate said that when he met you, he was so intimidated, he literally almost turned around and went home. Who was your college roommate? Jason Furman: Matt Damon. John Donvan: So, do Charles and Andy need to be scared as well as Matt Damon was scared? Jason Furman: I should be using this time to set expectations well, but instead I’ll use it to note that Matt did not graduate from Harvard. John Donvan: Yeah, and yet somehow it worked out. The team arguing against the motion, ladies and gentlemen. [applause] So, I want to let you know, you have already voted on the motion as you came in before hearing the argument, the motion the universal basic income is the safety net of the future. At the end of the evening, after you’ve heard all the arguments, we’ll have you vote a second time to see whether any of the debaters have persuaded you to change your minds or move from one side to the other. 00:05:04 And the way we declare victory is, we give victory to the team whose numbers have moved up the most in percentage points between the first and the second vote. I want to be clear, it's the difference between the first and the second vote that determines victory for our debaters. Let's begin with Round 1. Round 1 are opening statements by each debater in turn. The motion is, “The Universal Basic Income is the Safety Net of The Future.” Here to argue in support of the motion, first, Andrew Stern, a senior fellow at the Economic Security Project and former president of the Service Employees International Union. Ladies and gentlemen, Andrew Stern. [applause] Andrew Stern: Thanks, John. Maybe a little irony to start. Until three years ago, I had never even heard of a universal basic income. And tonight, my opponents are my progressive friends, while my partner, Charles, is often my ideological nemesis. 00:06:03 So, let me explain how I came to see the power of a universal basic income, offer a specific proposal, while Charles discusses its role in restoring choice and responsibility. Making it clear why a yes vote is really the only viable choice. At 22, my first real job was a welfare worker, determining eligibility for President Nixon's welfare programs. If you had a problem as a client, I had a regulation and a hoop you could jump through. I had no idea that two years earlier, the same President Nixon, with Milton Friedman's assistance, had proposed a far more radical safety net, a guaranteed income that'd be worth over $10,000 for each person today. Friedman explained, "We should replace the rag-bag of specific welfare programs with a single comprehensive program of income supplements in cash, and do more efficiently and humanely what our present system does so inefficiently and inhumanely." 00:07:06 John Kenneth Galbraith and a thousand other economists echoed Friedman. They wrote, "The answer for poverty is pretty clear. Everyone should be guaranteed a decent basic income." And only a year earlier, Martin Luther King had condemned President Johnson’s piecemeal approach to the war on poverty, saying, "I'm now convinced that the simplest approach will prove to be the most effective. The solution to poverty is to abolish it directly by the guaranteed income." He said, "The dignity of the individual flourished when decisions concerning his life are in his own hands." With so many people living in poverty, despite over 100 cash transfer programs, and the inhumanity of today's bureaucracy would be reason enough to institute a basic income as the new safety net. But there are two more even compelling reasons. First, despite all the touted job growth, and low employment rates, November's election was a shocking warning that the 21st century has gotten off, economically, to a really bad start. 00:08:10 47 percent of Americans couldn't find $400 for an unexpected expense. Nearly half are stuck in jobs that make less than $15 an hour. 40 percent perform unstable contingent work. A 30-year old's chances of earning more than their parents are down 40 percent, and the number of people engaged in any paid employment is at the lowest level in decades. A mere 34 percent of Americans feel financially secure. The rest feel, this is the United States of anxiety. So, secondly, a universal basic income, in this new age of insecurity, could be both a shock absorber and a supplement to work. Finally, accelerating technology may create the greatest disruption to jobs in history, and the Obama administration reports that 83 percent of the jobs paying less than $20 an hour, one-third of the jobs paying $40 an hour -- that's $80,000 a year -- are going to be impacted. 00:09:08 Oxford University,:47 percent of all American jobs will be lost. McKinsey: 45 percent of all tasks can be automated. And add to this chorus of disruptive technology the voices of the World Bank, the ILO, Joe Stiglitz, Elon Musk, Robert Reich, and Robin Chase. The first major disruption may actually be self-driving trucks. The largest job in 29 states, employing over 7 million people. Some may argue that we -- Charles and I, the new 21st century Luddites, but as the chair of the Bank of England makes clear, every technological revolution -- every single one, mercilessly destroys jobs well before the new ones emerge. So, how could a basic income work after a possible phase-in? 00:10:00 I propose that every citizen, 18 to 64, would have electronically deposited into their account a thousand dollars a month. That's $12,000 a year. No strings attached. It's that simple. According to government statistics that $12,000 ends poverty for the first time for 43 million people. It would allow entrepreneurs to start a business, women to escape domestic violence, or finally be compensated for their care giving jobs. Workers could be retrained or not accept poorly paid or irregularly scheduled work. Students could pay for books and fees while prisoners could survive once released. And if these payments only go to citizens 18 to 64 and seniors receiving less than $1,000 a month in Social Security, then by a combination of eliminating current welfare programs, not all but some, eliminating tax expenditures, not all but some, not health care or not disability benefits, and if we add new revenue whether it be a board or a vat, a carbon, or even Bill Gates robot tax and claw back the money from people at higher incomes, we can afford to do this in America. 00:11:10 The universal basic income is supported across the political ideologies because it's a fix -- efficient and flexible and humane and can end poverty once and for all. It promotes choice and freedom and offers security for the first time, both now and during the upcoming disruptive technological challenges we will face. A universal basic income is the safety net of the future and I urge you to vote yes. Thanks. John Donvan: Thank you, Andrew Stern. [applause] That is the motion, “The Universal Basic Income is the Safety Net of the Future.” And here to make his opening statement against the motion, Jason, you can make your way to the lectern, Jason Furman, a senior fellow at the Peterson Institute for International Economics and former chairman of the council of economic advisors during the Obama administration. Ladies and gentlemen, Jason Furman. [applause] 00:12:00 Jason Furman: Thank you. So, it's terrific to be here today and I'm particularly pleased to be in dialogue and debate with people who, especially in Andy's case, I very much share their goals and I share much of their diagnosis of the problem. I don't want to be here as the defender of the status quo, tell you everything's perfect in our economy, or that all of our public programs are working. Certainly, we need improvements; certainly, we need reforms. The argument that Jared and I are going to make is that universal basic income is based on a faulty premise, would take us in the wrong direction, and would make many of the problems that Andy is so rightly worried about even worse. Let me begin with the premise. Much of the premise for universal basic income is the notion that robots will take all of our jobs, and that if we can't be employed, that we'll need something else, some money from the government to take care of us. 00:13:11 People have thought this for a really long time. In the 19th Century, 70 percent of our population worked on farms making the food that we needed to eat. If you had told them that almost 150 years later, almost all of them would not need to work on the farms, less than 2 percent of our population could feed us, they would've wondered where all the jobs could come from. Today, machines do 90 percent of what workers could do 100 years ago, and yet the unemployment rate is a little bit below 5 percent just like the employment rate was in the year 1900. Switzerland has a much higher employment rate than Italy. 00:14:00 That isn't because there's lots of robots in Italy doing everyone's job and Switzerland people build the cuckoo clocks by hand. As people get richer, it creates new jobs that you never could've imagined in the 19th Century. It makes people want to spend more and support even more jobs, and consistently people have said just around the corner there's going to be a disruption and yet we're currently in the longest streak of job creation that we've ever seen in this country's history. Second, regardless of your views on this question of the future of work, the numbers in the UBI proposals tend to sound really, really attractive. They just have one downside. They violate the laws of arithmetic. Do not accept this idea unless you understand what the tradeoffs are. 00:15:01 It's really quite simple. If you give somebody a dollar, that dollar has to come from somewhere. It has to come from cutting benefits that someone is getting or raising taxes on someone. Now, maybe we’ll hear a little bit about all the bureaucracy that administers all these programs, but you could get rid of all that bureaucracy for unemployment insurance, food stamps, housing vouchers and the like, and only have $150 per person for UBI. So, if you want $10,000, you need to find the other $9,850. To put some scales on these proposals, Andy’s proposal that he just outlined will cost about $1.8 trillion. Charles has a proposal that’s a bit different that would also cost about $1.8 trillion. That’s twice what we spend on Social Security, our largest government program right now. That is more than we collect in income taxes every year. 00:16:03 So, you would have to double your income taxes. You would have to eliminate Social Security twice, or if you’re not touching Social Security, take all of the income support programs -- there’s 300 billion of them a year -- you can’t pay for $1.8 trillion for $300 billion a year. So, if you are tempted to support this motion, make sure you understand who the losers are, because you’re redistributing money that creates an equal number of winners as it does losers, because it’s just a dollar from here needs to come from there. In most of the proposals, the losers tend to be households with more children lose -- get a cut relative to a household without children, because today we support you based on your number or children. Or, older households, in Charles’ plan, a 90-year-old would lose relative to a 45-year-old, who would gain. 00:17:05 Or, somebody who’s unemployed, which is something we support quite strongly now with unemployment insurance, would lose, and somebody who is employed and went to college would gain. Or, somebody who makes $90,000 a year would win. They would get a better deal than they get today. And somebody who makes $30,000 a year would lose. Again, these details can change. We’re going to hear this isn’t true because of that. That’s not true because of that. But unless you’ve heard who’s winning, who’s losing and you understand the rationale for it, you shouldn’t support the motion. The final thing I would say is, we do need changes in our programs. We need to build on what works. We need to end what doesn’t work. And in particular, we need to support and encourage work, because while there will be jobs in the future, I don’t think it’s automatic that people can get them, and helping connect people to jobs, helping them work, helping fulfill their meaning and get an income is the most important thing for us to do. 00:18:06 Thank you. [applause] John Donvan: Thank you, Jason Furman. And a reminder of what’s going on. We are halfway through the opening round of this Intelligence Squared U.S. debate. I’m John Donvan. We have four debaters, two teams of two fighting it out over this motion, “The Universal Basic Income is the Safety Net of the Future.” You’ve heard from the first two opening speakers, and now on to the third debating for the motion, Charles Murray, the W.H. Brady Scholar at the American Enterprise Institute. Ladies and gentlemen, Charles Murray. [applause] Charles Murray: I’m going to engage along with Andy during the discussion period of a lot of the issues that Jason just raised, but I want to spend my time talking about some of the things that would be accomplished if we had a universal basic income. If we’ve learned anything over the last couple of years, and especially in 2016, it is that the working class in this country has a lot of problems. 00:19:02 They are not just in urban areas, they’re not limited to any one race, they’re all over the country. And these problems are ones that I think a UBI can deal with as the current system cannot possibly deal with. And I want to start out with the example of people who are doing everything right but are low-income. Let’s say we’re talking about a married couple with children. They’re near the minimum wage. Let’s say they each bring in $14,000 a year. That’s $28,000 for the two of them. They’re good parents. They are good neighbors. But they’re also just scraping by. Under the current system, do they get any welfare benefits? Yeah, they do. But at $28,000, a lot of those have been phased out, and also depends where you live in the country is what the other benefits are, and a lot of those benefits are in-kind benefits, as opposed to cash. 00:20:00 In the case of Andy’s plan -- which, by the way, for purposes of this debate, we’re going with Andy’s plan, both of us are. In terms of Andy’s plan, this couple now has $52,000 per year cash. That means that they are no longer having to rent a place which has Section 8 housing. They can go out and buy -- rent an apartment anywhere they want to that they can afford. It means that they are not giving out food stamps to the cashier at the grocery store. They're pulling cash out of their pocket. It means that they are not supplicating the welfare bureaucracy to please enroll them in this program, and please don't kick them off that program. They are able to have a qualitatively different life. In material terms, yes, but also in terms of the independence and options. They are moving toward -- basically approaching a middle-class income. There are millions of such people in this country. They deserve to have that kind of life. 00:21:00 We can afford to give it to them, and just doing that alone would be great. Now let me sort of go to the other extreme, and the ways in which a universal basic income gives moral agency, whether people want it or not. Let's think of the guy who is your complete screw-up. He drinks too much, he can't hold on to a job, and he runs out of money 10 days before the end of the month. Well, under the UBI, he can no longer plead helplessness. His friends and his relatives can say to him, as they cannot say now, "Okay, we aren't going to let you starve," but "You've got to get your act together, and don't tell us there's nothing you can do, because we know you've got a thousand bucks hitting your bank account next month. You got -- you've got to start dealing with your problems." That's good. That kind of interaction, multiplied millions of times around the country, is having friends and relatives deal with human needs in ways that bureaucracies inherently are unable to deal with them. 00:22:00 You have a situation whereby a guy who is living with his girlfriend is suddenly told, when the UBI is in effect, he's got to start paying part of the rent. Well, that's good for him, and it's good for her. You have other guys who have fathered children and walked away from them, and we really can't do much about it now with our child support laws, because the guy could say, "I don't have any money." Well, under the UBI, guess what? That money is deducted by court order before he ever sees it, as it goes into the account. That's good for the child. That's good for the mother, and that's good for the guy, and it's really good for all the guy's friends, who take notice of what's going on. But I don't want to go too far with getting people to shape up, giving people moral agency -- because they do, in fact, have resources and can take on responsibility. I really want to focus and elaborate in the rest of the debate on all the ways in which the UBI gives people options. So, let's go back to marriage again. 00:23:00 You have the guy making $14,000 a year. He wants to marry his girlfriend. Getting married with that little money is a problem. Now, with the UBI, they will have a family income of $39,000, if I'm -- 39, 38, I have to add it up -- even if his wife does not work at all. That makes marriage a possibility in a way it wasn't before. Or think of a woman who's married to a guy and they have a joint income. They both work, and they earn 60 or $70,000 a year. They're middle class, but she can't afford to do what she wants to do when she has a baby, which is to spend a couple of years with the baby. An awful lot of affluent women on the Upper West Side of New York who can make that choice and who have careers choose to stay at home with their children, which is good for the child. It's good for the mother. It's good for the dad. It's good for everybody. It's good for the community. Well, let's give middle-class women the kind of economic buffer whereby they can do the same thing. 00:24:00 In all of these ways, we have possibilities with the universal basic income, of augmenting incomes by dollar amounts, yes, but what we are really augmenting is options. We are augmenting dignity, we are augmenting independence. We are augmenting human flourishing. I hope you will agree, these are goals that not only deserve our economic support, but our enthusiastic moral support. Thank you. John Donvan: Thank you, Charles Murray. [applause] And that motion again, “The Universal Basic Income Is the Safety Net of the Future.” And here making his opening statement against the motion, Jared Bernstein, the senior fellow at the Center on Budget and Policy Priorities, the former chief economist to Vice President Joe Biden. Ladies and gentlemen, Jared Bernstein. [applause] Jared Bernstein: Thank you. Thank you. So, Jason started somewhere around 1800. 00:25:00 I'm going to start by taking you back just about a decade ago, when the two of us were working for a new historic presidential administration. That was very exciting. In the midst of the worst economic downturn since the Great Depression, that part was horrifying. These days, in a fact that poses a challenge to our opponent's end of work hypothesis, we're adding an average of 200,000 jobs per month, but back then we were shedding 700,000 jobs per month, over two million jobs lost in the first quarter. Why am I telling you about this? Because that recession threw 14 million additional people into poverty, 14 million people ended up poor. That's 5.5 million more people who lived -- than live in New York City. This was between 2007 and 2010. But -- and here's the first point I want to impart to you, once you account for the anti-poverty programs -- programs that lifted their income, their wages, that provided them with extra nutrition, with housing and with health care, the number of poor remained essentially flat. 00:26:04 Even amidst the worst recession, I hope of any of our lifetimes, once you account for these interventions, poverty was essentially unchanged, even in the midst of the Great Recession. Now, the reason I'm underscoring this is if our opponent's UBI proposals had been in place this would not have occurred. And that's for one of two reasons. Either, the resources that we're now using to support anti-poverty programs would be diluted as in Charles' plan, that's the universal part, or if you envision that we're somehow going to provide with a UBI on top of what we're now providing for them, you run head on into the constraints that Jason raised. The idea that you'd be spending the full amount of what our tax system already collects every year. The tax system needed to support a program that keeps the current safety net in place and builds a UBI on top of that is not one we should consider realistic, even in the context of this debate where I think we usefully suspend political disbelief to have a discussion in the age of Trump when conservatives are falling all over each other to cut taxes on rich people and cut spending for poor people. 00:27:17 Resource constraints exist even in that world, and a dollar going to someone who doesn't really need it is a dollar that isn't going to someone who really does. Now, of course, UBI supporters from the right argue that the help that we're providing to poor and elderly people today, doesn't work. From Ronald Reagan to Paul Ryan, they say we fought a war on poverty and poverty won. Charles writes in his book, "The welfare state produces its own destruction." But these claims are false. Back when Reagan first made that claim, the safety net listed 4 percent of the poor out of poverty. Today, it lifts 40 percent, more than 40 percent out of poverty, a 10-fold increase. 00:28:01 Today, our anti-poverty programs, which UBI proposals, both those of Andy and Charles, would wholly or partially end lift 40 million people out of poverty, including eight million kids and 18 million elderly persons. And in a deep and important contradiction to this claim of the welfare system self-destructing, we now have long-term research that shows that for children who benefit from poverty reduction, the benefits are long lasting. Poverty reduction that UBI would I fear undermine. Kids who get nutritional support were less likely to be obese, to have heart disease, to drop out of high school compared to kids who didn't. The Medicaid expansion was also -- kids who benefited from the Medicaid expansion were less likely to drop out and more likely to finish college. A dollar spent on early childhood education results in roughly $8.60 of benefits to society, about half of which comes from increased earnings for children when they grow up. 00:29:02 Now, those who know my work, and I hope some of you do, know that I spend a lot more time thinking about ways to improve this system I'm describing to you than I do touting and defending it. After all, even with all of the poverty reduction I've described, poverty rates are far too high. So, my work typically focuses on expanding the earned income tax credit and nutritional support. I’d seriously boost these upward mobility enhancers like quality preschool for little kids and college access for big kids. I'd make sure that unemployment insurance helps people longer, especially in places that get especially hard hit in recessions. I wouldn't guarantee everybody a basic income. I'd guarantee low and moderate income people a job. But if we instead choose to use our resources on people who don't need them, we won't be able to build on the progress we've made. Again, I understand and appreciate the usefulness of constraining political reality for this debate. 00:30:04 But let me end my initial comments by relaxing that constraint, because there's little point in totally abstracting from reality. You know, Bob Greenstein, a poverty expert with whom I work, said any possibility of overcoming the obstacles to UBI will require a left-right coalition that has significant conservative support, and conservative support for UBI rests on an approach that will increase poverty rather than reduce it. I just don’t see how you implement the program, some aspects of which I like, that our opponents are touting without seriously hurting the poor. There’s no way to add a program closer to Andy’s, as he recognizes, without seriously raising taxes. And I’ve been in D.C. for almost 30 years and not only have I seen total unified resistance to tax increases among Republicans, I’ve seen too many Democrats buy into that as well. Unless our nation’s politics radically change, I’m sure the answer is the worst-case scenario. 00:31:00 A UBI may well hurt the people who need help the most. Thank you. [applause] John Donvan: Thank you, Jared Bernstein. And that concludes round one of this Intelligence Squared U.S. debate, where our motion is, “The Universal Basic Income is the Safety Net of the Future.” And now we move onto round two, and in round two the debaters address one another directly as they answer questions from me and from you, our live audience in New York. The motion is this, “The Universal Basic Income is the Safety Net of the Future.” The team arguing for the motion, Andy Stern and Charles Murray, have argued that the working class and, extensively, the middle class is in trouble, that jobs are dying, incomes are dying, and that with the predictive future for artificial intelligence, work itself may become obsolete, throwing potentially tens of millions of people out of work in the lifetimes of people who are here with us now. They argue that the universal basic income is a floor that would work as a hedge against -- not only as a hedge against poverty, but would also allow for the dignity of people who are otherwise suffocating for oxygen to survive financially. 00:32:04 They make the further argument that there’s a social good. That the UBI would augment options, that it would augment independence, that it would remove excuses for irresponsible behavior. But their bottom line is: options, options, options would come with the UBI. The team arguing for the motion, Jason Furman and Jared Bernstein, first of all, they make clear that they are not defending the status quo. They don’t think everything’s perfect as it is. They do think that reforms are needed. However, they are simply not as pessimistic as their opponents, either about the future of jobs or about the performance of anti-poverty programs already in place. They say that the prediction of a doomsday scenario for obsolete labor is way oversold. Surrender is being made prematurely to the notion of giving up on helping people find jobs by paying them not to work, or paying them because they can’t work, to be more precise. They do not want to rally around the idea of helping people get by without trying to help them continue to find work. 00:33:02 And bottom line, they say that their opponents’ plan just doesn’t work because the math does not add up. There’s a lot here, and I want to separate some of this into different parts, and I want to ask the debaters, as we go forward, I’d like to enforce conversations around different aspects of this so not to bleed into the other points you want to make, because I will attempt to get to them. But the first one I want to get is just the basic presumption that the team arguing for the motion is making -- the assumption that at a very accelerated rate jobs are dying, that work is changing, that as I said, human labor will become obsolete, possibly in the lifetimes of people who are alive with us today. So, I think we’re talking 20 to 30 years from now at the outside. And I want to go to your opponents to respond to that first -- and you did somewhat in your opening statement -- why challenge so vociferously, Jason Furman, this notion that things really, really are changing quickly, that this time it is different? 00:34:03 Jason Furman: Somebody wrote a book, a guy, Martin Ford called “Rise of the Robots” that made this prediction. The Wall Street Journal, in 1960, had an article with the headline “The Robots Rise” that made exactly the same prediction 55 years ago. People have been predicting this for a really long time. There is no evidence for it in the data. The fraction of the population that works varies a lot across countries and across times, but it depends on economic circumstances and what you’re doing to help prepare people for jobs and succeed in jobs, not on the number of robots you have. So, rather than treating this as inevitable and declaring -- surrendering to the robots, we should be figuring out how people can succeed, thrive and work in an era when, yes, we hopefully will have more robots doing more of the things that they’re better at than humans. 00:35:06 Freeing us up for other, even better jobs. John Donvan: Okay. Andy Stern, your opponent just used the word "inevitable," saying it's not inevitable. But you're almost on the pretty darn sure it's inevitable side of the argument. Andrew Stern: I'm certainly at the point that to ignore the possibility and not plan for it would be a critical mistake for our country. You know, the problem with economists are, they try to predict the future by looking at data from the past. And I think we just had an election where people used a lot of data from the past and kind of missed the point -- because things actually do change in this world. And there was a headline one time that Donald Trump would be president, you know, and everybody laughed at that as well, and now we have him as the President of the United States. So, let's not say because the data once happened or -- it will never happen again. Let's look at this. Elon Musk, Bill Gates, Stephen Hawking -- people that are creating the future, all will tell you this is an event that will occur within the next 20 years. 00:36:03 Not obsolescence. And it's not just robots. It's software that's enabled globalization. It's autonomous vehicles that allow for self-driving trucks. It's the Amazon new checkout which is like EZ-Pass, where you walk out the door and all the things are accounted for. The studies by Boston Consulting, the World Bank, the ILO, you know, The European Union all say there will be a massive disruption in jobs. I don't know why -- the data may not show it, but everybody else in America does. And didn't we just learn -- John Donvan: But it -- Andrew Stern: -- the lesson of ignoring that? John Donvan: Andy, part of Jason's argument is that we've heard this again, and again, and again -- Andrew Stern: Oh. John Donvan: And you're saying this time it's different. Andrew Stern: I do think this time is different, because I think the facts are entirely different. John Donvan: Let me bring in Jared Bernstein. Jared Bernstein: Well, look. It's -- I don't think it's legitimate to argue that, you know, you shouldn't make predictions, and then make predictions -- because we don't know what's coming around the corner. And you're right about that, Andy. 00:37:00 And Jason's right that when people have said this has been coming around the corner, it hasn't been. What I would say is, I'd encourage the audience to think in a commonsensical way about this. Look around. Do you really see -- I happened to walk up here from Penn Station today. There's a lot of work going on in New York, let me tell you. Do you -- look around. And not just in New York, but throughout the country. Do you really see the end of work? I see a lot of work that needs to be done, in transportation, in infrastructure, in childcare -- where people, not robots, are so important -- in teaching -- where people, not robots, must do the work -- in elder care. Same thing. And if we're smart, in areas like renewable energy, where I believe there is serious and deep employment possibilities. And that's precisely the kind of dynamic that has happened throughout history -- new opportunities, new sectors, new places for us to do things that need to be done. John Donvan: Okay. Charles Murray. Charles Murray: Yeah. For a long time, artificial intelligence was way overhyped, oversold, underperformed. 00:38:00 And I think the way to look at the curve we're on right now -- it's been going like this, and we're about -- we've just started the steep incline. Whereby artificial intelligence is enabling software to do things that would be considered 10 years away just a year ago, such as, for example, becoming the best Go player in the world because the software taught itself how to play Go. I think something I want to add onto Andy's point is it's not just the working-class jobs that are going to get displaced. The really great hollowing out of jobs is going to be in white collar jobs -- in accountancy, in all sorts of legal -- paralegal work, in all sorts of things where you used to make a good salary because you had to be pretty bright to do it. You had to make judgments. And guess what? At this point, the judgments made by the software, in many cases, are better than the judgments made by the employees. It's going to be a huge displacement. John Donvan: Jason Furman. Jason Furman: Just to respond directly to two things you both said. 00:39:00 Absolutely, we're going to have a lot of disruption and a lot of change. We had a lot of disruption and a lot of change when we went from agriculture to manufacturing, from manufacturing to services. The question is, what do we do to help people cope with and deal with that change, and land unemployment? But I wanted to, Charles, take your example of lawyers. The New York Times had a good write-up of a study, I think, from McKinsey, recently. There's all this talk that AI can do all the discovery for us, so that's going to replace lawyers. Well, lawyers also appear in courtrooms. Lawyers talk to their clients. Lawyers negotiate things. AI can't do any of those activities. And when people have looked at it carefully in that study, they found that these AI’s are replacing about 2 percent of what lawyers do per year, which means 98 percent it's not replacing. And by the way, that 2 percent, that's about the average productivity growth we've had for the last 60 years. That's what we’ve been dealing with. Charles Murray: Paralegal, not lawyer. John Donvan: All right. Jason Furman: Just like stock traders, and stock analysts -- all of which is now the Potemkin Village down on Wall Street, because there used to be people doing those jobs, and now algorithms do them. 00:40:07 Charles Murray: How many of us use travel agents now? Jason Furman: The unemployment rate is still below 5 percent. Jared Bernstein: I see a lot of people working down there. John Donvan: All right. So, to a degree we simply have an impasse on this question of what the future holds, but that doesn't mean that we can't keep going forward because I want to take to the side arguing for the motion something that your opponents say is that what they say is most, I think, wrong-headed from their point of view about your argument is its emphasis on surrender to the reality that these jobs won't exist against the other option of working more creatively and harder at trying to match people to the jobs for the future. And that's their main critique is, “Don't give up. You're giving up too early. Let's continue to do some sort of creative -- work on creative programs, education, et cetera, job matching.” Andy Stern, what about that? Andrew Stern: So, I'm not giving up, but I think we should raise the minimum wage. I think we should do many of the things they say, but we would be irresponsible to not take into effect an incredible amount of belief that something big is going to happen that's going to affect people's lives. 00:41:09 People are already insecure. This could be a supplement. It doesn't have to be a replacement just like the EITC is a supplement to work. There will be work, it's just not going to be enough of it and I think what we need to do is have a policy that's flexible enough and we should understand that when the agricultural to the industrial revolution, the industrial revolution to now went on it was miserable for several decades as the head of the Bank of England said. And what are we going to do, just let people suffer? John Donvan: So -- Andrew Stern: Or are we going to have a policy that's flexible enough to help make that transition? John Donvan: So, bottom line, without a UBI being part of the process, you're saying that their hopes for some sort of solution are in vain? Andrew Stern: They're as good as they are right now, which is pretty bad. John Donvan: Jason Furman. I'm sorry. Jared Bernstein. Jared. Jared Bernstein: So, I actually am -- don't think that's our main argument. I think it's a key part of our argument, this argument about employment not disappearing and going up in smoke. 00:42:03 There's still a lot of work for people to do, but I think to me our core argument is the following. I said it. Jason said it. The way I said it was, “A dollar going to someone who doesn't really need it is a dollar that isn't going to someone who really does,” okay? That is the problem with the U -- the universal of universal basic income. I mean, their plan gives $12,000 a year to Bill Gates, to Warren Buffett, and they don't need it. And, in fact, Andy talked about the EITC. That's a really important wage subsidy for low-income people, lifts 10 million people out of poverty every year. He takes the EITC and he takes food stamps and he puts that into the UBI and dilutes that anti-poverty effectiveness, and that to me is the core problem here, because it's not just that the UBI is going to people who don't need it, it's that you're undermining some poverty reduction -- John Donvan: Okay. Jared Bernstein: -- effects that are working today. 00:43:00 John Donvan: I want to let Charles Murray respond to that. They are saying that your plan would be burning some anti-poverty programs that actually do good and do work. Charles Murray: Okay. Now, we could go into a variety of ways in which at income levels you start to claw back part of the grant and all of this. I don't think I want to spend a whole lot of time talking about that, because I don't think that Jason and Jared have gotten our core point, which is, you don't want to give money to people who don't need it so we'll have means-tested programs, which is what we have now, and you end up with this bureaucratic -- no, it's not that it's so expensive, that's not the problem with bureaucracy. The people in this audience probably mostly have to deal with the government in terms of doing the DMV and when the IRS tells you you owe them an X addition $855 and it is irritating and problematic to do it. Imagine that you are living your life supplicating bureaucrats. Okay, I get bits and pieces of this and that and the other thing and you can have a life where you actually have cash that you can decide how to use on your own. 00:44:03 At the basis of the universal basic income for the future, I think that both Andy and I are saying that it's time to free the serfs, that the serfs are getting all sorts of benefits. We want to make them into independent people with the resources. John Donvan: Charles, I want to -- [applause] -- I want to come in on that point. I want to come in and explore that point, but I still feel that your opponent has made a point that you haven't responded to and maybe Andy wants to, that anti-poverty programs that are in place are effective and your UBI proposal threatens to undo something that is working for significant numbers of people. Andrew Stern: One fact. John Donvan: So, there's a cost there. Andrew Stern: One fact. Forty-three million people, according to the federal government are at the federal poverty level, that's about $12,000 a year, $12,000 a year ends poverty for the first time in America. John Donvan: Jason Furman. Jason Furman: And $50,000 a year would be even better than $10,000 a year. 00:45:03 In fact, our side is going to support a million dollars a year and ask you to vote for us and against our opponents. There’s nothing more tedious and boring than arithmetic. I used to do it in meetings in the White House. It was not visionary. It’s not exciting. It’s really boring. But it’s really important, because it’s something we can’t change. But the arithmetic -- you get rid of every income support program, outside of Social Security, that is enough for a UBI of $1,500 a person. So, now, that family we heard about before working so hard at the minimum wage, instead of making $28,000 a year, they’re making $31,000 a year. Does that sound as exciting to you? Actually, it’s a bit worse than that, because at $28,000 a year, they’re actually getting a decent amount now in terms of nutritional assistance, housing vouchers and the like. 00:46:01 They would lose that, with the money saved from losing that going to pay someone at 50,000, 100,000, a million, $10 million a year. John Donvan: Okay, we -- Jason Furman: If we got additional revenue, there’s a lot of places to invest it. I would start with pre-school, continue through college and training. Those have higher returns than you can get in the stock market. They can help us prepare for a future where jobs are being dislocated, get a high rate of return and are a more fair and efficient way to do it. John Donvan: Okay, Andy Stern, an argument -- Andy Stern, an -- Andrew Stern: I was going to say, for someone who didn’t want to defend the status quo, boy, I’ve heard that argument for about 30 years now. It’s a great argument. It never has worked. And the basic math -- this isn’t phony math. It’s not making up numbers. There are 43 million people in poverty. A thousand dollars a month takes them all out of poverty and gives them choice. Jason Furman: The question is whether your plan makes it better or worse for them. 00:47:01 If you are giving more money to somebody at $80,000 a year, you are giving less money to a poor person. Andrew Stern: We’re not. We’re giving them $12,000 a year. We’re not -- that is not less than they are getting now. Jason Furman: Where is the money coming from? Andrew Stern: Well, that’s a different question. If you’re going to argue the cost, argue the cost. If you’re going to argue, are people better off, they’re better off. John Donvan: And we were arguing at this point because this was the point you brought up, Jared, that they’re better off without the UBI. They’re saying they’re better with the UBI. [Cross talk] Jared Bernstein: It sounds like phony math to me, because it sounds to me like what you’re doing is you’re taking away what they have -- which you plan does get rid of the Earned Income Credit -- right? -- it gets rid of food stamps, it gets rid of housing vouchers. Doesn’t get rid of Social Security, which Charles does but you don’t. And then you’re giving it back to them in some way, shape or form. What we’re talking about now -- Andrew Stern: And more. Jared Bernstein: What’s that? Andrew Stern: And more. Jared Bernstein: So, what we’re talking about now is that the folks that were -- and I used this in my opening comments -- the people who were lifted out of poverty -- and there were 40 million of them. 00:48:09 40 million people lifted out of poverty, were lifted out of poverty because all those programs that I just mentioned are taking -- once you take them away, they’re poor. So, I just don’t understand the arithmetic that you’re talking about. And secondly, the programs that I mentioned -- the benefits from nutritional support, the benefits from medical support, the benefits from Head Start, the benefits from Pell -- these are long-lasting benefits. If you take that away and you give people a few thousand bucks, in the long run, I’m afraid they’d be worse off. So, I don’t understand how you pile more money -- Andrew Stern: Twelve thousand bucks, not a few thousand bucks. Charles Murray: We’ve got two -- we have two different things we’re conflating. One is, can we afford the program, and the second one was, will people at low-income levels be better off. The people who get the most money in terms of the size of the benefits are single women with children. 00:49:00 And under the additional $12,000, which Medicaid is still being provided under Andy’s plan -- the numbers add up to about the same. They are not winners or losers in this calculation. But in terms of all the other low-income people, the ones who are making 15,000, $20,000 a year, particularly a couple, an additional $24,000 onto their income, they are way better off. So, if you want to say we can’t afford it, let’s engage in that debate. I’ll be glad to do it. But the idea that, oh, that they’re going to lose their food stamps, they’re going to lose their EITC, well, the $12,000 for most low-income Americans is way more than they are getting on those benefits. John Donvan: Jason. Jason Furman: So, first, two things. One is, that’s actually factually inaccurate and that in certain circumstances you actually are getting more benefits today, and the reason is because those bureaucrats making people jump through hoops we’ve seen denigrated so much, do things like on your tax form you will out the number of children you have and you get a larger EITC if you’re in a family with three or more children than a family with one children. 00:50:09 That's one of the things those bureaucrats do, and that, by the way, was partly my fault. We put that in during the Obama administration. Another thing those bureaucrats do is unemployment insurance. They make sure you're unemployed, and really importantly, they make sure you're looking for a job. The evidence is, that actually, when you put a bit more funding into the part where they screen you to check whether you're really looking for a job -- something conservatives have supported because it's a form of program integrity to keep people committing fraud off of it -- it actually helps more people look for jobs and find jobs. John Donvan: Let me -- Jason Furman: So, that's something where you get a bureaucrat involved. They do a bit of extra work. It's not so simple. It's not writing them a check, but it's for a good purpose with a good outcome. John Donvan: Andy Stern. Charles Murray: You worked in welfare bureaucracies. 00:51:01 Andrew Stern: Well, as I said, I have three binders in front of me to be so helpful, and now, I guess, if I'm a welfare worker, I also have to drug test the people who are on unemployment, because that's now what we're going to do. We're going to force the people on Medicaid to work. You know, this is not a very benign welfare system, and Martin Luther King had it right. You know, putting people's choices in their own hands is the greatest dignity you can give someone. And asking some bureaucrat to fill out their form, you know, is not the kind of dignity we need if we have another choice. Jared Bernstein: No, I think that that -- I think you make a good point, and that's why the thing that I kind of like about some of the things you've suggested is that -- Andrew Stern: Keep coming, baby. You're coming -- Jared Bernstein: Yeah. Andrew Stern: -- our way. Jared Bernstein: -- is that -- [laughter] -- if you -- if we -- if you take what we have and you build on top of it, and you provide low-income people with some extra resources, I would be for that and I think Jason would be for that as well. The problem is this income constraint that you're just not dealing with. 00:52:01 Your example before -- and it's easy to get tangled up in this -- really sounded like you're going to take everybody's benefits away because you're going to combine them into a UBI, and then you're going to give them back to them in the form of a UBI. So, they're no better off except for the fact -- and here you have a point -- that they have cash now instead of having to go through a set of programs. But -- recognize -- but -- no, hold on. This is key. Recognize that you can't do that if you're taking a big chunk of resources that you're now giving to low-income people, and giving it to high-income people. And the other side has not dealt with that problem yet. The only way to do that is to take it from low income people or raise a bunch more taxes. And at some point, you have to face that constraint. John Donvan: Okay. It -- Charles Murray: John, I'm bursting over here. John Donvan: Go ahead. Charles Murray: Okay. [laughter] John Donvan: Go ahead, Charles. Charles Murray: We have two -- John Donvan: The first time I've ever heard -- Charles Murray: We have two -- John Donvan: -- a debater say he was going to burst, and it frightens me. [laughter] Charles Murray: We have two profoundly different views of human beings. We have over there -- and this is going to sound invidious, and I like you guys, but I'm sorry; it sounds invidious, but we know better. 00:53:06 We know how to dole out the benefits just right. We know how to calibrate this and calibrate that, but we can't just give people money. That's too simple. And it's much better if we do all of these smart things that we know how to do. And you got Andy over here, and I, saying, "Give them the damn money and let them decide how they want to live their lives." And get out of their way. [applause] John Donvan: Okay. One moment. I do feel that each of you are making points that the others are not responding to. And your opponents have -- [laughter] -- your opponents have made the case a number of times that there's dignity involved with being able to make -- Charles Murray: I -- John Donvan: -- your own [inaudible]. I haven't heard you respond to it. Charles Murray: I responded -- John Donvan: And you weren't -- the other side has been telling you that you haven't told us what's going to -- why it works to take -- to give Bill Gates $12,000, and are you not taking that money away from somebody else. And I want to move on to the third topic that you raised, Charles, which is the whole social impact of this on the fabric and the texture of life. 00:54:02 But before we do that, I want to give your side 30 seconds to respond to their well-made point, I think, that you're talking about giving money to rich people as well, who may not need it. Andrew Stern: Okay. So, one-tenth of 1 percent -- which is $62 million -- pay the same tax rate as the people in the 20 percent bracket. 17 percent of the income is paid by the richest people that get 27 percent of the tax expenditures. Why don't -- they're getting money every single way. So, all of a sudden, we want to give money to poor people, and we can't do it, because somehow, we're giving too much money to rich people. We have a distribution problem. The tax system favors the wealthy, and we are going to have to do something about it. And putting this on the back of UBI’s -- Bill Gates' $12,000 is a pittance compared to what he's getting in every other tax expenditure that we should be talking about as well. John Donvan: Okay. That is responsive. Now, I don't want to -- I don't want to -- [applause] 00:55:03 -- I don't want to dig on that point anymore, because I want to hear you respond to the -- their point made a number of times, that requiring means testing for people to get benefits, requiring drug testing, requiring them to prove who they're married to or not married to is humiliating and their system injects dignity where it does not exist now. Andrew Stern: I very much believe in dignity. Your EITC is -- [laughter] -- incredibly easy thing to claim. You can spend that money on whatever you wanted on. Most of the hoops we've heard about, the drug testing, the limits on what you can do, have been put in place over the years by conservatives in the name of their notion of dignity. I think they've been misguided and I would reform those programs, simplify, and streamline them, that maybe even move towards cash. That's different, though, then universal. For universal, we have to talk about where the money is coming from and how we want to spend that amount of money, which hopefully we'll get to. 00:56:04 John Donvan: Charles, I want to now move on to the point -- [applause] -- I don't mean to keep stepping on the applause. There's a lag in the applause. [laughter] You need to be faster. [laughter] Charles, I want to give you 30 seconds and I'm going to time it on my watch. I want you to reiterate the point that you made in your opening statement to kick off this next section about the social -- the impact on the social fabric of UBI in terms of what you were talking about having options and I want -- I just want to do that so that your opponents can respond to it. Your 30 seconds starts now. Charles Murray: Really quickly, I'm saying that the kinds of human needs that we need to deal with are best dealt with by friends and relatives and that the UBI, one of its major effects, is to focus resources on the community. The key to understanding the UBI is not that I get $12,000, but everybody else is getting the $12,000 and everybody knows it. 00:57:01 And that triggers a cascade of feedback loops, which are precisely what American civil society has always been about dealing with human needs at the lowest possible level. John Donvan: Okay. It's the most ephemeral part of your argument, but also one of the most interesting. I want to take it to the other side. Jared Bernstein. Jared Bernstein: Yeah, I don't find it that interesting. [laughter] Charles Murray: But we agree on ephemeral. Jared Bernstein: I'm not sure what ephemeral means, but I don't like that either. [laughter] The -- so the thing -- well, the thing that we're trying to impart here is that not that what we have is great. What we have is problematic. Andy knows that. Jason knows that. You've heard a little bit about that. But that there are many ways in which I think you don't -- that people don't appreciate, Charles doesn't appreciate, in which these things are working. And yet, in its place we have what sounds to me like this kind of Charles Murray fantasy about civil society. Now I know Charles' work very well. I've read all of his books and many of them are erudite, some of them less so. 00:58:04 [laughter] But I will say that his version of civil society is not the same as mine and I suspect not the same as a lot of people's out there. And when he starts talking about friends and relatives will do that maybe he's right, but that's just a fantasy. What I'm telling you about is that in reality, there's a set of things that are working to help people right now. They're not perfect. We need to build upon them, but we can't throw them out because Charles has dreams of friends and relatives helping you in civil society. John Donvan: That's a femoral. Jared Bernstein: That's a femoral? John Donvan: Yes. [applause] Charles. Charles, and Andy, if you want to be a part of this response you can as well. Charles Murray: I think an awful lot of people in the audience live in the kind of civil society or did as children before they came to the upper west side, lived in the kind of society I'm talking about. It's not a fantasy. It's the way America has historically worked and still does. 00:59:00 [applause] John Donvan: All right. I want to go into audience questions at this point. Female Speaker: Hi. Julia Creighton with Futurism. So, for those opposed to UBI, we've heard a lot about how it's a bad idea because it would result in either cutting benefits or raising taxes, but without the reallocation of funds, for example, the United States spends more money on defense than the next how many nations combined? Is there no possibility of perhaps taking funds from that arena and reallocating them to maybe focus on our own citizens? [applause] Jason Furman: So, some of this is about -- but first of all, the taxes, by the way, just to do the magnitude of them, to pay for them is going to be $1.5 trillion per year. That would be nearly as much as we collect in income taxes today. For higher taxes, there’s a lot of things I’d do with higher taxes. No one is going to support doubling the income taxes people say today. 01:00:02 Certainly, not Charles’ friends who are all invested in human freedom, dignity and a tax increase one-tenth the magnitude that we’re talking about here describe it in apocalyptic terms as the end of America. On defense spending, to some degree I agree with you, that I could see arguments for lower defense spending. Then the question is, what do you think the best use of that money is? Is it a check for someone making $60,000 a year, or is it universal preschool? Universal pre-school, certainly it has more bureaucrats. It has requirements. For example, you need to go to school to benefit from universal preschool. I don’t mind that requirement. So, this just isn’t in the first claim on my money. Now, if it’s for people in poverty, sure, that’s great. But all this plan does, at best, seems to be to replace what those people are getting today. So, no, I wouldn’t get rid of defense to replace what people are getting from poverty programs today, give money to someone $80,000, and continue to be one of the worst countries in the OECD when it comes to the percentage of our population that goes to preschool. 01:01:08 John Donvan: The other side has the option to respond to that, if you’d like. Andrew Stern: I would just say, we’re giving 43 million people, we’re taking them out of poverty, to keep saying to give people what they have today is just wrong. Male Speaker: So, since it’s sort of going off the last question because it didn’t feel like it was totally answered to me, instead of looking at this in -- and this is for the opponent of it -- instead of looking at this from the perspective of, it can’t be done because it’s either raising taxes on the middle class to pay for it or it’s coming -- the money’s coming from other programs, let’s assume that you are tasked with putting this together. And I would like to -- I would like to challenge you to come up with some other ways you could maybe pay for it, like carbon taxes, reduced healthcare costs, raising flat taxes on every one of 10 percent, taxing unearned income at the full rate, taxing financial transactions -- 01:02:05 Jared Bernstein: I mean, I see where you’re coming from. Male Speaker: Like, what would you do as a solution? Jared Bernstein: Look, in my -- in my -- I support a lot of what you’re trying to say there, because in my work I’m often thinking about precisely those sorts of mechanisms to derive more revenue. And I also like the idea about taking a chunk of defense spending and using it for social benefits, for people’s well-being. What I don’t like is giving it to people who don’t need it. And so, you have to think about biggest bang for the buck. What you just described isn’t going to raise $1.8 trillion, so it’s not going to pay for what they’ve described. The numbers just don’t add up. So, you have to get the biggest bang for the buck, and the biggest bank for the buck comes from the kinds of things we’ve been talking about, not from wasting precious dollars on people who don’t need them. John Donvan: Charles, would you like to respond to that? I -- it’s implied -- Charles Murray: Well, I think that if we’re going to talk about budgets, we’d better look at trendlines, because I think the statement is the safety net of the future, and if you play out the trendlines for the cost of Social Security and welfare programs -- I’ll tell you what happened when I did the book, “In Our Hands” back in 2006. 01:03:14 I calculated the cost of my plan and the amount of money we were spending on transfers, and I said the lines would cross between the costs of the programs in 2011, which they did. The point is right now, that a basic income you can predict demographically pretty much exactly what it’s going to cost you, and it’s going to be a very shallow slope. What we’re looking at with the other entitlement programs are very steep rises. So, if you’re talking about the affordability of this today, you’ve got one set of issues. If you’re talking about the affordability of this in 2030, you’ve got a very different situation. John Donvan: Okay, another question. I’m going to be honest about why I’m hesitating. I’m kind of looking for some women to ask questions, because, you know -- and let’s bring some voices in here. 01:04:05 Where? Thank you. I couldn’t find you. Yeah, if you could stand up, thanks. Female Speaker: So, I have a question for the for side. You talked about positive social pressures from people knowing that you have that money. How would you avoid having negative social pressures, with companies trying to suppress paying a livable wage? Andrew Stern: Well, I think the good thing about having $12,000 is you basically have your own strike fund. You know, right now, if you're desperate for work, if you only have $400 -- don't have $400 for unexpected expense, and someone offers you a job, you have not much choice but to take it. But to have walk-away money, to have an ability to say "No," you know, gives you a series of choices -- to start a business, to do things that people can't even dream of doing to now, I think, you know, gives people agency, gives them freedom, gives them choice, gives them the same rights that the rich kids do who live in garages in Silicon Valley because someone is giving them a parental basic income. 01:05:04 It gives everybody a basic income to do what they need to do. John Donvan: What is the parental basic income? Andrew Stern: The parental basic income is -- listen. How many of you in this audience are like me -- [applause] -- who help your kid go on vacation, who help your kid -- [laughter] -- you know, pay their auto insurance, or help them put a down payment on a home? People do that. That's what families do. Rich people have a basic income called their parents -- or middle-class people -- [laughter] -- called their parents. Why doesn't everyone have the same basic income? [applause] Jared Bernstein: So, I -- John Donvan: Jared. Jared Bernstein: I have children and have myself a fairly robust parental income. Andrew Stern: [laughs] Jared Bernstein: I know of what you speak, Andy. Look, 12,000 -- the problem is $12,000 is a strike fund for, you know, a month. And that's an annual salary. Andy's thing is a thousand dollars a month. That's not enough of a strike fund. 01:06:00 That's why -- take the resources from, you know, a financial transaction like the carbon tax, defense fund. Put them not into a guaranteed income for everybody -- so you end up with the waste problem we've described -- but into a guaranteed job. Boy, that's way more than a strike fund. That's actually a job, and I would insist that this is a job that pays a living wage, because I believe there's lots of work to be done, and I described it. I'm happy to describe it again. That's where I would go with this -- a guaranteed job for low-income people. Anyone who's able-bodied, wants to work, can work -- and that we could pay for on the kinds of numbers that we're throwing around now. That doesn't cost the same amount as a UBI, because it doesn't waste its resources on people who don't need it. John Donvan: I want to remind you that we are -- [applause] -- I want to remind you that we are in the question and answer section of this Intelligence Squared U.S. debate. I'm John Donvan, your moderator and host. We have four debaters, two teams of two debating this motion, “The Universal Basic Income is The Safety Net of the Future.” 01:07:01 Okay. Right down in front. Could you just give us a name -- or a first name? Male Speaker: Oh, yeah. Bob. Hello. John Donvan: Hi, Bob. [laughter] Andrew Stern: Yeah, we believe that. [laughter] Male Speaker: Yeah. So, my question is that sometimes we -- this can be sort of spoken about in the abstract. And I'm curious to know, how much time have any of you directly spent with people in poverty or the truck driver who may lose their job, and how has that informed your opinion as you talk about this subject? John Donvan: I think that's a fair and good question. Who -- [applause] Charles Murray: Is it okay to count people that aren't in the United States? I spent six years in Thailand, mostly in subsistence level villages, so I spent all of my time with poor people there. During the 1970s, I worked on programs -- social programs, evaluation of them, where I spent a lot of time in South Side Chicago, inner city Atlanta, et cetera. 01:08:01 John Donvan: Anybody else want to -- Andrew Stern: Yeah. You know, I spent my entire life with janitors, child care, home care, food service, security workers, and welfare workers, in fact. And so, my whole life is somewhat informed. And the reason I came to UBI was because I see it as the answer for those people, compared to the welfare system and the low wages that they currently have. Jared Bernstein: So, my first job as a -- John Donvan: Jared Bernstein. Jared Bernstein: -- grown-up was about 40 blocks north of here, in east Harlem, where I was a social worker for many years. And I remember, on the very first day of the job, I helped somebody get Medicaid. Now, a lot of people probably like to disparage Medicaid and say that that's some sort of terrible throwaway program to poor people. I can't tell you how much this meant to her. It was like a gold card. Same thing with helping her -- when I helped her get her kid into a preschool program. Same thing when I helped -- when she eventually got a job, and I helped her get an earned income credit. 01:09:01 I'm not saying I did anything good. I'm advertising for these pieces that were on the table. If I had instead given her a thousand dollars a month, she never would've been started on a ladder of upward mobility where at least this person I'm thinking of eventually ended up. Jason Furman:And I'm not going to try to compete because I was spending too much time doing math. [laughter] John Donvan: So, I just want to say, that's normally a question I would not take because it doesn't actually -- their experience doesn't actually relate to their ability to present an argument, but in this case I felt that you were making a case about their credibility and I found it really interesting. So, thanks for bringing that to the debate. Female Speaker: Hi. My name is Sarah. I'm also with Futurism. There -- someone stated earlier that there was an assumption that new jobs are exponential, that no disruption is ever coming, and my question is that, you know, 25 years go by and we see clearly that the job market cannot keep up with automation and employment reaches depression levels, would you then support UBI at that point and if not, what solution would you propose? 01:10:02 John Donvan: Okay. Let's take that question to the side who are going against the motion., who it's meant for. Jason Furman. Jason Furman: Yeah. To be clear, I'm not talking about the very far future, and I think if we're ever in the situation, I would be perfectly comfortable allowing the robots to design our UBI program -- [laughter] -- for us. If we're looking at the next couple decades, though, I'm much more concerned with what we can do to prepare people for those jobs rather than giving up and assuming -- John Donvan: You know, and I just want to say in terms of sort of an instruction to the jury, it's -- it was agreed by the debaters that we're not talking about a hundred years from now future. We're really talking about -- and the side arguing for the motion really was presenting a case about something coming at us rather quickly. So, this -- future isn't, you know, the year 5000 for these guys. They don't have to defend that. Female Speaker: Hi. My name's Steph. My question is, do you have any concerns that if you do give $1,000 a month to people that inflation would just end up affecting it in the end so it'll be worth less? 01:11:03 Andrew Stern: Do I -- I certainly have a concern -- John Donvan: Andrew Stern. Andrew Stern: -- but, you know, all the work that's been done to date has not proven that to be happening. You know, the Alaska dividend where they do get $1,300 a month, you know, has improved to be a big inflationary -- John Donvan: I'm not sure everybody knows about that. Andrew Stern: Okay. In Alaska, instead of giving everybody a new welfare program that Jason and Jared would redesign, you know, they decided just to give people $1,300 -- they give people money from the oil reserves directly to people and they have a trust and every month -- every year, I'm sorry, people get something between $1,000 and $2,000 in a year. John Donvan: And in 2008, they got $3,289 per person. No matter how many people in the family, everybody got it so some families of five came away with $16,000. Andrew Stern: So, that was a different way to -- you know, to give people money and there and the other experiments -- we did five experiments in the United States about universal basic income during Richard Nixon's time. 01:12:03 We're now doing it in Finland and Ontario and we'll learn more, but so far, there's not evidence. Jason Furman: If I could just -- John Donvan: Sure, definitely. Jason Furman: Not an inherent problem to UBI. It's a fully salvable one. You can take the benefit and index it and have it grow over time. That being said, if you look at many of the UBI proposals they don't have that feature. So, for example, they index to inflation, but they get rid of health care. You're supposed to buy it out of your UBI. The cost of health care rises faster than inflation. That's precisely what we see the Republicans doing right now with their vote tomorrow in Congress. They take Medicaid and replace it with something that grows over time, but it grows at a smaller rate. You have to look at the details of these things and I worry that a lot of them by taking away natural ways, you know, going up -- food stamps go up with the cost of food. The cost of food goes up, they go up automatically. Anything and this is going to automatically go up with the cost of food. I think that's unlikely that that's how it would end up being designed and that makes me worried. 01:13:03 John Donvan: All right. Center back. If you would stand up. Thanks. It's coming on your right-hand side. If you could tell us your name again, please. Female Speaker: Thank you. My name is D.C. and I have a question for the for motion. You keep on talking about 43 million people being raised out of poverty, but yet you're for universal basic income rather than for basic income for people who are poor. Could you explain why you would want to extend it to the whole population rather than to specific subset of the population? John Donvan: Andrew Stern. Andrew Stern: Because I think that the record of the United States -- I mean, you're watching it right in real life in front of your eyes is that people always want to cut things for people who don't have much and want to give more to people who have a lot. And so, I think from a political point of view the reason we failed over and over and over again to improve the welfare programs is because we divide the population into the people that deserve it and the people that don’t, even though the -- you know, you can argue that till the day is long, but that’s exactly reverse. 01:14:04 So, I would say to build the political calculus -- as we’ve done with Social Security and Medicare -- that makes this an enduring program is not to make one group of people stand out and be vulnerable to be cut, but to give it to everyone and use the tax system, which is how we claw back money from people who have money rather than trying to do this all through a welfare system, which has not worked up to now. John Donvan: Jared Bernstein? Jason Furman: Two things. One, a point Jared just made to me and he would have made better, is that for the first time in this debate we’re hearing our opponents talk about political realism. We’ve asked us to suspend it for the rest of their argument. I don’t even think it’s a correct reading of political realism, though. Social Security benefits go to all of us. It’s an incredibly popular program. Since the early 1970s, we’ve passed legislation twice to cut Social Security benefits, zero times to raise it. 01:15:01 The Earned Income Tax Credit just goes to poor people. We established that in the early 1970s. Since then, we’ve voted eight times to increase the Earned Income Tax Credit, zero times to decrease it. It’s had more political support than any program I can think of, and that’s I think in part because it’s tied to work and it’s a reward and encouragement to work -- something that has proven appealing from Richard Nixon through Ronald Reagan to the present. John Donvan: I want to remind you we are in the question and answer section of this Intelligence Squared U.S. debate. I’m John Donvan, your host. We have four debaters, two teams of two debating this motion, “The Universal Basic Income is the Safety Net of the Future.” Right on the -- almost the aisle. Yeah, thanks. Male Speaker: Hi. My name’s Josh. I appreciate the simplicity of the proposal of universal basic income. I’m curious how those who support it will ensure that this isn’t used as a Trojan horse to undermine our -- the social safety net, essentially to defund these programs, say you’re going to fund a UBI, but then essentially not be able to raise the taxes or the revenue to do so. 01:16:13 John Donvan: Andy Stern. Andrew Stern: Yeah, I mean, I would never do this unless it was all done in one single package. It’s kind of like repeal and replace, you know? I’m not doing the repeal without the replace. And I think this true here. You have to have, as we did with the Obamacare, you have to have a full package. And we know that nothing is perfect and people will argue around the edges, but in the end, we did increase healthcare for 20 million people. In the end, UBI will relieve poverty for 43 million people. John Donvan: Another question? Sir, blue plaid shirt, if you could stand up. I know you had to check your shirt. I don’t know what color my tie is. Now I do. Male Speaker: It’s red. Hi, Danny. I’ve heard a lot of anecdotes and theories from the for side. I’m just curious, do you have any hard numbers or actual facts from existing uses of the UBI that show that it has worked in other countries, or small samples at least? 01:17:06 John Donvan: Charles. Charles Murray: Well, the problem with experiments is that a great deal of the effect of the UBI depends on the knowledge it will be permanent and you can think ahead. If you know that you’re in a five-year experiment, your whole calculus changes, and so that’s why I really don’t -- I don’t think that there is a good set of conclusions we can draw from even an ideal experiment that we set up. If you know that for the rest of your life you are going to have this resource available to you on the first of every month, it’s not just your own decisions that have changed. It is also your interactions with the people around you that have changed. So, have not got any hard numbers on that, have not got any hard data on that. John Donvan: Just talked to somebody with a trust fund. There’s some information in that. There’s some information in that. Charles Murray: Well, that’s an interesting observation. 01:18:01 John Donvan: Yeah, I can take more questions. Right down the center here. Third row, thanks, and then coming in from the right. If you could tell us your name, too. Male Speaker: Hi, my name is Dan, and I’m currently going to school at Columbia University for computer science on my universal basic income, the post-9/11 GI bill. So, I have that to depend on every month. So, my question is, as a future software engineer, and in considering the responsibility that a lot of tech companies actually have for the automation and the software that’s replacing these jobs, who do you believe -- either side -- should bear the brunt of paying the taxes to either implement a UBI or to raise the funds to support the people who are being displaced by automation? John Donvan: That's an excellent question. Let's take it to the side going against first. Jared Bernstein. Jared Bernstein: So, first of all, I wouldn't be here if it weren't for the GI bill. So, that's an interesting observation and admonition, on my part. 01:19:03 But it also was a pretty concentrated piece of work. Most of the people who benefited from the GI bill -- just having to do with the structure of -- this is -- my father was in the war, World War II -- were people from low income areas. So, it kind of actually fits closer to our model of getting the water to the fire versus getting the water to where it's not needed. Look, I'm -- as I think I've suggested in some other answers, I would raise the funds needed to do the kinds of improvements that we think are so necessary for more progressive taxation. I like the idea of looking more deeply into spending on defense. It's the next seven nations. We spend more on defense than the next seven nations combined. So, I like looking for where there -- I'd like to look for where there's some -- maybe some wiggle room in the spending side of the budget. But primarily, we're -- we are -- and Andy said this earlier. We're collecting a share of their income -- far less revenue from the very wealthy than we have throughout the history of our country. 01:20:05 It's this inequality problem -- and it's compounded by the fact that the wealthy are able to kind of buy, through money and politics, a kind of tax policy that protects them, that insulates them from more progressive changes. So, that's how I would collect those funds. John Donvan: Sir, did your question have any flavor of the people who are doing technology? The big companies that are going to influence these changes would have a greater responsibility to fund it? Were you getting at that in any way? Male Speaker: Yes. John Donvan: You were? Okay. I just want to keep that in the -- you -- part of the conversation as the other side responds to it. Andrew Stern: Yeah. I mean, I -- John Donvan: Andrew Stern. Andrew Stern: Yeah. I think this is a crisis for our country. I think when 47 percent of people can't find $400 and driverless trucks are on their way -- and I think what's been great about the country is when we've had a crisis, we responded. We found $4 trillion in QE. We found a trillion dollars for stimulus. We find money when the savings and loans -- let's find some money for people who are really hurting now and probably find a way to supplement their incomes and pride [spelled phonetically], security going forward, and potentially then go to a full universal basic income when the time comes. 01:21:10 But it is -- some of the things we've talk about -- it's -- it -- maybe it's a robot tax that Bill Gates talks about, but there's a VAT tax, the carbon tax, an asset tax, a border tax. There's been a financial transaction tax in this country for 50 years. We [inaudible] -- John Donvan: But I think the question sort of encompasses [inaudible] -- Andrew Stern: -- but it should go to everyone; not just be focused on particular companies. John Donvan: Right. Okay. That's what I wanted to get at. And the other side, did you get that sense of the question? Was it sort of -- should there be a Silicon Valley tax? Jason Furman: I think technology has disproportionately benefited the most advantaged in our society, and they can and should afford to pay more in taxes. That's a separate issue from what we're debating here, though, which is what use that revenue would go to. John Donvan: Thank you. And that concludes Round 2 of this Intelligence Squared U.S. debate, where our motion is, “The Universal Basic Income is the Safety Net of the Future.: [applause] 01:22:01 And now we move on to Round 3. Round 3 will be closing statements by each debater in turn. They will be two minutes each. Immediately after that, you will be asked to vote again, and we will declare our winner. Our motion is, “The Universal Basic Income is the Safety Net of the Future.” Here making his closing statement in support of the motion, Andrew Stern, author of "Raising the Floor: How Universal Basic Income Can Renew our Economy and Rebuild the American Dream." Andrew Stern: So, Bill Gates once said, “We always overestimate the change that will occur in the next two years and underestimate the change that's going to occur in the next 10.” Don't let yourself be lulled into inaction. The fact is that we can't afford to tinker much longer because change is happening on an accelerated basis. A safety net that was built when I was a case worker in the 21st century is not the right fit for the 21 century. Not in a world where Uber -- the largest taxi company -- owns no vehicles. 01:23:01 Facebook, the largest media company, has no creation, other than by its participants. Amazon, the most valuable retailer, owns no inventory. And although I wish I can go back and change what happened when Martin Luther King and Richard Nixon all were for a guaranteed income, I can't, but we can go forward in a way that gives people the dignity and the choice, that gives the warehouse workers at Amazon, or gives the truck drivers, or the insurance agency accountants some sense that their future will be secure. Our choice, according to the thousand experts at Pew Research, is this, either we're going to do something or we're going to see vast increases in inequality, masses who are effectively unemployable, and breakdowns in the social order. That's not the America we want. A universal basic income is flexible. It's humane. It ends poverty. It offers choices and stability now and as we transition to a new economy. 01:24:00 It's the one comprehensive policy that has support from both the left and right. UBI has issues. I admit it. No single policy is going to ever solve every single problem, but I remember what Winston Churchill once said about democracy. "It's the worst form of government except for all others." And I would like to say UBI as a policy, is exactly the same. It is far superior for all the other choices we have. Our future, our family's futures, is not a matter of chance. It's a matter of choice and the right choice for the future safety net for this country is a universal basic income and I urge you to vote yes. John Donvan: Thank you, Andrew Stern. [applause] Making his closing statement against the motion, Jason Furman. He is the senior fellow at the Peterson Institute for International Economics. Jason Furman: I certainly can't predict the future. If I'd been around 50 years ago, I wouldn't have known that we'd have lots of people employed as software engineers and app developers and all the other things that we have in our economy today. 01:25:06 I can't tell you exactly what the jobs will be 50 years from now, but I can tell you Americans are more likely to get those jobs and succeed in those jobs if they have a good education, everywhere from preschool through college. That's something we're dramatically under-investing in today. I wish there was a single magical bullet that would solve all our problems. I think actually if there was one it probably would be -- education would be the closest thing. But the world is a messy place. I think it probably makes sense to give you more support when you're unemployed than when you're not unemployed. If you have a larger family than a smaller family. If you want to move to a neighborhood with more mobility, something that's been proven to raise your earnings by 30 percent rather than wanting to stay put. We're not going to get those programs exactly right. 01:26:02 We may not even get them close to right, but rather than saying let's get rid of all of them, let's talk about the things we're doing wrong, try to make them better, because getting rid of all of them runs into this problem that I've harped on again and again, which is arithmetic. If you support giving everyone, you know, the million dollars a year that I talked about before sounds even better to you than the ideas you've heard, ask yourself where that money will come from. Eliminating the Defense Department would not be enough to pay for this proposal. A carbon tax would pay for 10 percent of this proposal. We have a limited set of resources in our country. We need to use them in a smart, effective, targeted way for the people who need them most for the areas that will have the highest returns. Which is why I would urge you to vote against this motion which would drain money from all of them, thank you. 01:27:01 John Donvan: Thank you, Jason Furman. [applause] The motion again, “The Universal Basic Income is the Safety Net of the Future.” Here making his closing statement in support of the motion, Charles Murray, author of "In Our Hands: A Plan to Replace the Welfare State." Charles Murray: Jared and Jason have talked a lot about the people who are being most helped by the current welfare system while Andy and I have focused a lot on a much broader swath of the population, but let me go to those people who we refer to as living off welfare, and I'll try to put myself in that position. Let's say I'm 20 years old. I've gotten a terrible education. I don’t have any job skills. I don't have a job. I live in a neighborhood where most of the other people are in the same fix as I am and then I hear people saying that I'm a slacker and that I ought to take advantage of my opportunities and I say opportunities? What opportunities? There is no realistic route for me. 01:28:01 Yes, I will get my welfare benefits from the current system. It's humiliating and it ties me to where I am, can't afford to move. In that context, you have the UBI come in. The UBI does not exhort me to go out and get a job. It doesn't stage manage my life in any way. It doesn't give me guidance. What it does is say to me this one thing and I've never had a reason to believe it before, “Your future is in your hands.” That simple message, “Your future is in your hands,” is what we in this room most want for ourselves and what we most want for our children. Please join me in endorsing a plan that will make it true for all of our fellow citizens as well. [applause] John Donvan: Thank you, Charles Murray. And the motion again, “The Universal Basic Income is the Safety Net of the Future.” 01:29:02 And here making his closing against the motion, Jared Bernstein, a senior fellow at the Center on Budget and Policy Priorities. Jared Bernstein: Of course, we want you to support our position and vote no on the question, but frankly, I care a lot more about what you take home with you from this debate. I’ve been a social scientist now for over three decades, and the thing that motivated me in my 20s burns just as bright in my 60s, and that’s this: People must be able to realize their potential -- their economic potential, their educational potential, their spiritual potential. I get that it’s easier to write a check for everyone, including those who don’t need the money, than to do the heavy policy lifting that can break down the barriers that so many people face today. I wish I could do that with a UBI check, with a thousand dollars a month to buy the dreams that Charles talked about, but they’re more expensive than that. By providing everyone with that kind of income, you‘re not going to come anywhere close to ensuring secure housing, adequate nutrition, access to quality childcare, educational opportunities from pre-school to grade school to college and beyond, and decent job that pays a living wage. 01:30:09 What’s more, we’ve made real progress against every one of those barriers -- not enough by a long shot -- and the next four years -- please God make them just four years -- will be pure defense, pure defense trying to protect the progress that we’ve made. In that climate, I see no reason to help conservatives prove their prophecy -- a demonstrably false one thus far -- that antipoverty programs will self-destruct. Like I said, I started my career as a social worker a few blocks north of here. Every single day bar none, I saw clients that were people just like me except for they weren’t white and where doors were flung open for me, they were slammed shut for them. If Andy wants to provide those folks with some extra resources, fine. Good idea. But let’s not kid ourselves that we’ve helped them to overcome the barriers to realizing their potential. 01:31:00 That work is much harder, much longer-lasting in the lives of those who’ve been left behind, and thus much more important than UBI. Thank you. John Donvan: Thank you, Jared Bernstein. [applause] And that concludes round three of this Intelligence Squared U.S. debate, where the motion is, “The Universal Basic Income is the Safety Net of the Future.” And now, it’s time to learn which side you feel has argued most persuasively. We’re going to ask you again to go the keypads at your seat and vote a second time. The motion, “The Universal Basic Income is the Safety Net of the Future.” Push number one if you are with this motion now. Push number two if you are against this motion now. Push number three if you became or remain undecided. I said at the beginning of the evening that our goal is to have a tough debate in a spirit of civility and light, and I think we got that. All of these gentlemen in the green room ahead of time, they obviously liked and respected each other, and it was a pleasure to see that come to the stage tonight. So, I want to thank them for what they do. [applause] 01:32:00 I was -- I was personally stunned to learn that Jared Bernstein is in his 60s tonight -- as shocked as when Charles told me he was 29. [laughter] But you all brought great spirit to this. I also want to say something else about the questions. I don’t think I threw out a question tonight, and that’s rare. And as I said, I was very taken by the question you brought that normally I would have thrown out. I think it moved things forward, and I learned a lesson from that. So, thank you. I want to make this other point. Those of you who are not regulars have not heard me say this before. Those who have, please bear with me. We are a philanthropy. Intelligence Squared pays -- the tickets that you buy don’t come close to paying the cost of putting this production on. We rely on donations and support and private support as well. And we have a number of very important supporters, but we also have an army of smaller supporters, and we would love to have you join that group. 01:33:05 We’ve just developed a way for you to support us by using your phone. I’m going to give you a number to text to, and if you text the word “debate,” then you’ll be getting a link that you can then use to make a contribution, and we would greatly appreciate it. The number is 797979. I’ll repeat it, 797979. And if you text that word debate, you can help us keep this going and help us growing, which is our goal. I want to let you know about our next debate coming up here, on April 6th -- but first I want to say a word about Wal-Mart. [laughter] Wal-Mart was built on the foundation of Sam Walton's strategy, the lowest prices anywhere, anytime. And it works. And it started in the 1960s. It's grown to be the world's largest retailer. In the U.S. alone, it employs 1.5 million people in 5,000 stores across the country. But our debate centers on whether Wal-Mart has been good for America. On April 6, we are debating this motion, "Long Live Wal-Mart." 01:34:03 I think it's going to be fascinating. It's going to be a very, very interesting way to look at -- first of all, not only a business, but a cultural phenomenon, one that we are -- well, not so much if you're living in Manhattan, but otherwise -- [laughter] -- almost anywhere else. I just think it's a very, very interesting way we've chosen to shed light on an economic question. So, we would love to invite you to have -- to join us for that. Later on, this spring, we'll be producing debates on whether video games make us smarter. In June, we're going to be in San Francisco, doing a debate looking at tech companies and government demands for their customer data. Tickets for all of those are available through our website. And for those of you who can't join our live audience, there are a lot of other ways to catch these debates. Those of you who are watching the livestream right now know that. You can visit our website at IQ2US.org. Also, to vote on our debates -- to watch them, to listen to our podcasts. A lot more. You can also read, on our site, the writings of all of these debaters on the topic that you just saw. So, you can learn more about what they think and how they came to their conclusions. 01:35:02 Membership to our site is free, so you can set up an account and start tracking your favorite debates, and you can play along with our game, if you -- the longer you spend and the smarter your comments, the higher your IQ2 score goes our site. [laughter] And it's fun. I got gifted a 200 IQ2 score, but it's sort of one of those things I would never get into the college I got into. And if I had to apply now, I would never have a 200 IQ2 score if I didn't just get it right away. You can watch all of our debates on demand on Roku and Apple TV apps, and listen, as I said at the beginning, on public radio stations across the country. Repeating, “The Universal Basic Income is the Safety Net of the Future,” is our motion. As I explained, the team whose numbers changed most in the upward direction between the first and the second vote will be our winner. In the first vote, 35 percent agreed with the motion, 20 percent were against.
def __cpu_arch(self): if hpccm.config.g_cpu_arch == cpu_arch.AARCH64: self.__arch_directory = 'Linux_aarch64' if StrictVersion(self.__version) < StrictVersion('20.11'): self.__cuda_multi = False elif hpccm.config.g_cpu_arch == cpu_arch.PPC64LE: self.__arch_directory = 'Linux_ppc64le' elif hpccm.config.g_cpu_arch == cpu_arch.X86_64: self.__arch_directory = 'Linux_x86_64' else: raise RuntimeError('Unknown CPU architecture')
/* * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <float.h> #include "libavutil/opt.h" #include "avfilter.h" #include "audio.h" #include "formats.h" #include "hermite.h" typedef struct AudioDynamicEqualizerContext { const AVClass *class; double threshold; double dfrequency; double dqfactor; double tfrequency; double tqfactor; double ratio; double range; double makeup; double knee; double slew; double attack; double release; double attack_coef; double release_coef; int mode; AVFrame *state; } AudioDynamicEqualizerContext; static int config_input(AVFilterLink *inlink) { AVFilterContext *ctx = inlink->dst; AudioDynamicEqualizerContext *s = ctx->priv; s->state = ff_get_audio_buffer(inlink, 8); if (!s->state) return AVERROR(ENOMEM); return 0; } static double get_svf(double in, double *m, double *a, double *b) { const double v0 = in; const double v3 = v0 - b[1]; const double v1 = a[0] * b[0] + a[1] * v3; const double v2 = b[1] + a[1] * b[0] + a[2] * v3; b[0] = 2. * v1 - b[0]; b[1] = 2. * v2 - b[1]; return m[0] * v0 + m[1] * v1 + m[2] * v2; } static inline double from_dB(double x) { return exp(0.05 * x * M_LN10); } static inline double to_dB(double x) { return 20. * log10(x); } static inline double sqr(double x) { return x * x; } static double get_gain(double in, double srate, double makeup, double aattack, double iratio, double knee, double range, double thresdb, double slewfactor, double *state, double attack_coeff, double release_coeff, double nc) { double width = (6. * knee) + 0.01; double cdb = 0.; double Lgain = 1.; double Lxg, Lxl, Lyg, Lyl, Ly1; double checkwidth = 0.; double slewwidth = 1.8; int attslew = 0; Lyg = 0.; Lxg = to_dB(fabs(in) + DBL_EPSILON); Lyg = Lxg + (iratio - 1.) * sqr(Lxg - thresdb + width * .5) / (2. * width); checkwidth = 2. * fabs(Lxg - thresdb); if (2. * (Lxg - thresdb) < -width) { Lyg = Lxg; } else if (checkwidth <= width) { Lyg = thresdb + (Lxg - thresdb) * iratio; if (checkwidth <= slewwidth) { if (Lyg >= state[2]) attslew = 1; } } else if (2. * (Lxg-thresdb) > width) { Lyg = thresdb + (Lxg - thresdb) * iratio; } attack_coeff = attslew ? aattack : attack_coeff; Lxl = Lxg - Lyg; Ly1 = fmaxf(Lxl, release_coeff * state[1] +(1. - release_coeff) * Lxl); Lyl = attack_coeff * state[0] + (1. - attack_coeff) * Ly1; cdb = -Lyl; Lgain = from_dB(nc * fmin(cdb - makeup, range)); state[0] = Lyl; state[1] = Ly1; state[2] = Lyg; return Lgain; } typedef struct ThreadData { AVFrame *in, *out; } ThreadData; static int filter_channels(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs) { AudioDynamicEqualizerContext *s = ctx->priv; ThreadData *td = arg; AVFrame *in = td->in; AVFrame *out = td->out; const double sample_rate = in->sample_rate; const double makeup = s->makeup; const double iratio = 1. / s->ratio; const double range = s->range; const double dfrequency = fmin(s->dfrequency, sample_rate * 0.5); const double tfrequency = fmin(s->tfrequency, sample_rate * 0.5); const double threshold = log(s->threshold + DBL_EPSILON); const double release = s->release_coef; const double attack = s->attack_coef; const double dqfactor = s->dqfactor; const double tqfactor = s->tqfactor; const double fg = tan(M_PI * tfrequency / sample_rate); const double dg = tan(M_PI * dfrequency / sample_rate); const int start = (in->channels * jobnr) / nb_jobs; const int end = (in->channels * (jobnr+1)) / nb_jobs; const int mode = s->mode; const double knee = s->knee; const double slew = s->slew; const double aattack = exp(-1000. / ((s->attack + 2.0 * (slew - 1.)) * sample_rate)); const double nc = mode == 0 ? 1. : -1.; double da[3], dm[3]; { double k = 1. / dqfactor; da[0] = 1. / (1. + dg * (dg + k)); da[1] = dg * da[0]; da[2] = dg * da[1]; dm[0] = 0.; dm[1] = 1.; dm[2] = 0.; } for (int ch = start; ch < end; ch++) { const double *src = (const double *)in->extended_data[ch]; double *dst = (double *)out->extended_data[ch]; double *state = (double *)s->state->extended_data[ch]; for (int n = 0; n < out->nb_samples; n++) { double detect, gain, v, listen; double fa[3], fm[3]; detect = listen = get_svf(src[n], dm, da, state); detect = fabs(detect); gain = get_gain(detect, sample_rate, makeup, aattack, iratio, knee, range, threshold, slew, &state[4], attack, release, nc); { double k = 1. / (tqfactor * gain); fa[0] = 1. / (1. + fg * (fg + k)); fa[1] = fg * fa[0]; fa[2] = fg * fa[1]; fm[0] = 1.; fm[1] = k * (gain * gain - 1.); fm[2] = 0.; } v = get_svf(src[n], fm, fa, &state[2]); v = mode == -1 ? listen : v; dst[n] = ctx->is_disabled ? src[n] : v; } } return 0; } static double get_coef(double x, double sr) { return exp(-1000. / (x * sr)); } static int filter_frame(AVFilterLink *inlink, AVFrame *in) { AVFilterContext *ctx = inlink->dst; AVFilterLink *outlink = ctx->outputs[0]; AudioDynamicEqualizerContext *s = ctx->priv; ThreadData td; AVFrame *out; if (av_frame_is_writable(in)) { out = in; } else { out = ff_get_audio_buffer(outlink, in->nb_samples); if (!out) { av_frame_free(&in); return AVERROR(ENOMEM); } av_frame_copy_props(out, in); } s->attack_coef = get_coef(s->attack, in->sample_rate); s->release_coef = get_coef(s->release, in->sample_rate); td.in = in; td.out = out; ff_filter_execute(ctx, filter_channels, &td, NULL, FFMIN(outlink->channels, ff_filter_get_nb_threads(ctx))); if (out != in) av_frame_free(&in); return ff_filter_frame(outlink, out); } static av_cold void uninit(AVFilterContext *ctx) { AudioDynamicEqualizerContext *s = ctx->priv; av_frame_free(&s->state); } #define OFFSET(x) offsetof(AudioDynamicEqualizerContext, x) #define FLAGS AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_RUNTIME_PARAM static const AVOption adynamicequalizer_options[] = { { "threshold", "set detection threshold", OFFSET(threshold), AV_OPT_TYPE_DOUBLE, {.dbl=0}, 0, 100, FLAGS }, { "dfrequency", "set detection frequency", OFFSET(dfrequency), AV_OPT_TYPE_DOUBLE, {.dbl=1000}, 2, 1000000, FLAGS }, { "dqfactor", "set detection Q factor", OFFSET(dqfactor), AV_OPT_TYPE_DOUBLE, {.dbl=1}, 0.001, 1000, FLAGS }, { "tfrequency", "set target frequency", OFFSET(tfrequency), AV_OPT_TYPE_DOUBLE, {.dbl=1000}, 2, 1000000, FLAGS }, { "tqfactor", "set target Q factor", OFFSET(tqfactor), AV_OPT_TYPE_DOUBLE, {.dbl=1}, 0.001, 1000, FLAGS }, { "attack", "set attack duration", OFFSET(attack), AV_OPT_TYPE_DOUBLE, {.dbl=20}, 1, 2000, FLAGS }, { "release", "set release duration", OFFSET(release), AV_OPT_TYPE_DOUBLE, {.dbl=200}, 1, 2000, FLAGS }, { "knee", "set knee factor", OFFSET(knee), AV_OPT_TYPE_DOUBLE, {.dbl=1}, 0, 8, FLAGS }, { "ratio", "set ratio factor", OFFSET(ratio), AV_OPT_TYPE_DOUBLE, {.dbl=1}, 1, 20, FLAGS }, { "makeup", "set makeup gain", OFFSET(makeup), AV_OPT_TYPE_DOUBLE, {.dbl=0}, 0, 30, FLAGS }, { "range", "set max gain", OFFSET(range), AV_OPT_TYPE_DOUBLE, {.dbl=0}, 0, 200, FLAGS }, { "slew", "set slew factor", OFFSET(slew), AV_OPT_TYPE_DOUBLE, {.dbl=1}, 1, 200, FLAGS }, { "mode", "set mode", OFFSET(mode), AV_OPT_TYPE_INT, {.i64=0}, -1, 1, FLAGS, "mode" }, { "listen", 0, 0, AV_OPT_TYPE_CONST, {.i64=-1}, 0, 0, FLAGS, "mode" }, { "cut", 0, 0, AV_OPT_TYPE_CONST, {.i64=0}, 0, 0, FLAGS, "mode" }, { "boost", 0, 0, AV_OPT_TYPE_CONST, {.i64=1}, 0, 0, FLAGS, "mode" }, { NULL } }; AVFILTER_DEFINE_CLASS(adynamicequalizer); static const AVFilterPad inputs[] = { { .name = "default", .type = AVMEDIA_TYPE_AUDIO, .filter_frame = filter_frame, .config_props = config_input, }, }; static const AVFilterPad outputs[] = { { .name = "default", .type = AVMEDIA_TYPE_AUDIO, }, }; const AVFilter ff_af_adynamicequalizer = { .name = "adynamicequalizer", .description = NULL_IF_CONFIG_SMALL("Apply Dynamic Equalization of input audio."), .priv_size = sizeof(AudioDynamicEqualizerContext), .priv_class = &adynamicequalizer_class, .uninit = uninit, FILTER_INPUTS(inputs), FILTER_OUTPUTS(outputs), FILTER_SINGLE_SAMPLEFMT(AV_SAMPLE_FMT_DBLP), .flags = AVFILTER_FLAG_SUPPORT_TIMELINE_INTERNAL | AVFILTER_FLAG_SLICE_THREADS, .process_command = ff_filter_process_command, };
<gh_stars>1-10 use crate::{ actor::{Actor, ActorContainer}, bot::{Bot, BotKind}, control_scheme::ControlScheme, effects, item::{Item, ItemContainer, ItemKind}, jump_pad::{JumpPad, JumpPadContainer}, leader_board::LeaderBoard, message::Message, player::Player, projectile::{Projectile, ProjectileContainer, ProjectileKind}, weapon::{Weapon, WeaponContainer, WeaponKind}, GameEngine, GameTime, MatchOptions, }; use rand::Rng; use rg3d::{ core::{ algebra::{Matrix3, Vector3}, color::Color, math::{aabb::AxisAlignedBoundingBox, ray::Ray, PositionProvider, Vector3Ext}, pool::Handle, visitor::{Visit, VisitResult, Visitor}, }, event::Event, physics::{ geometry::{ContactEvent, InteractionGroups, ProximityEvent}, pipeline::ChannelEventCollector, }, scene::{ self, base::BaseBuilder, camera::CameraBuilder, node::Node, physics::RayCastOptions, Scene, }, sound::context::Context, utils::navmesh::Navmesh, }; use std::{ cell::RefCell, path::Path, path::PathBuf, rc::Rc, sync::{mpsc::Sender, Arc, Mutex}, }; pub const RESPAWN_TIME: f32 = 4.0; pub struct Level { map_root: Handle<Node>, pub scene: Handle<Scene>, player: Handle<Actor>, projectiles: ProjectileContainer, pub actors: ActorContainer, weapons: WeaponContainer, jump_pads: JumpPadContainer, items: ItemContainer, spawn_points: Vec<SpawnPoint>, sender: Option<Sender<Message>>, pub navmesh: Option<Navmesh>, pub control_scheme: Option<Rc<RefCell<ControlScheme>>>, death_zones: Vec<DeathZone>, pub options: MatchOptions, time: f32, pub leader_board: LeaderBoard, respawn_list: Vec<RespawnEntry>, spectator_camera: Handle<Node>, target_spectator_position: Vector3<f32>, proximity_events_receiver: Option<crossbeam::channel::Receiver<ProximityEvent>>, contact_events_receiver: Option<crossbeam::channel::Receiver<ContactEvent>>, } impl Default for Level { fn default() -> Self { Self { map_root: Default::default(), projectiles: ProjectileContainer::new(), actors: ActorContainer::new(), scene: Handle::NONE, player: Handle::NONE, weapons: WeaponContainer::new(), jump_pads: JumpPadContainer::new(), items: ItemContainer::new(), spawn_points: Default::default(), sender: None, navmesh: Default::default(), control_scheme: None, death_zones: Default::default(), options: Default::default(), time: 0.0, leader_board: Default::default(), respawn_list: Default::default(), spectator_camera: Default::default(), target_spectator_position: Default::default(), proximity_events_receiver: None, contact_events_receiver: None, } } } impl Visit for Level { fn visit(&mut self, name: &str, visitor: &mut Visitor) -> VisitResult { visitor.enter_region(name)?; self.scene.visit("Scene", visitor)?; self.map_root.visit("MapRoot", visitor)?; self.player.visit("Player", visitor)?; self.actors.visit("Actors", visitor)?; self.projectiles.visit("Projectiles", visitor)?; self.weapons.visit("Weapons", visitor)?; self.jump_pads.visit("JumpPads", visitor)?; self.spawn_points.visit("SpawnPoints", visitor)?; self.death_zones.visit("DeathZones", visitor)?; self.options.visit("Options", visitor)?; self.time.visit("Time", visitor)?; self.leader_board.visit("LeaderBoard", visitor)?; self.respawn_list.visit("RespawnList", visitor)?; self.spectator_camera.visit("SpectatorCamera", visitor)?; self.target_spectator_position .visit("TargetSpectatorPosition", visitor)?; visitor.leave_region() } } pub struct DeathZone { bounds: AxisAlignedBoundingBox, } impl Visit for DeathZone { fn visit(&mut self, name: &str, visitor: &mut Visitor) -> VisitResult { visitor.enter_region(name)?; self.bounds.visit("Bounds", visitor)?; visitor.leave_region() } } impl Default for DeathZone { fn default() -> Self { Self { bounds: Default::default(), } } } pub struct UpdateContext<'a> { pub time: GameTime, pub scene: &'a mut Scene, pub sound_context: Arc<Mutex<Context>>, pub items: &'a ItemContainer, pub jump_pads: &'a JumpPadContainer, pub navmesh: Option<&'a mut Navmesh>, pub weapons: &'a WeaponContainer, } struct PlayerRespawnEntry { time_left: f32, } impl Default for PlayerRespawnEntry { fn default() -> Self { Self { time_left: 0.0 } } } impl Visit for PlayerRespawnEntry { fn visit(&mut self, name: &str, visitor: &mut Visitor) -> VisitResult { visitor.enter_region(name)?; self.time_left.visit("TimeLeft", visitor)?; visitor.leave_region() } } struct BotRespawnEntry { name: String, kind: BotKind, time_left: f32, } impl Default for BotRespawnEntry { fn default() -> Self { Self { name: "".to_string(), kind: BotKind::Mutant, time_left: 0.0, } } } impl Visit for BotRespawnEntry { fn visit(&mut self, name: &str, visitor: &mut Visitor) -> VisitResult { visitor.enter_region(name)?; self.name.visit("Name", visitor)?; self.time_left.visit("TimeLeft", visitor)?; let mut kind_id = self.kind.id(); kind_id.visit("Kind", visitor)?; self.kind = BotKind::from_id(kind_id)?; visitor.leave_region() } } enum RespawnEntry { Bot(BotRespawnEntry), Player(PlayerRespawnEntry), } impl Default for RespawnEntry { fn default() -> Self { RespawnEntry::Player(PlayerRespawnEntry::default()) } } impl RespawnEntry { fn id(&self) -> u32 { match self { RespawnEntry::Bot { .. } => 0, RespawnEntry::Player { .. } => 1, } } fn from_id(id: u32) -> Result<Self, String> { match id { 0 => Ok(RespawnEntry::Bot(Default::default())), 1 => Ok(RespawnEntry::Player(Default::default())), _ => Err(format!("Invalid RespawnEntry type {}", id)), } } } impl Visit for RespawnEntry { fn visit(&mut self, name: &str, visitor: &mut Visitor) -> VisitResult { visitor.enter_region(name)?; let mut id = self.id(); id.visit("Id", visitor)?; if visitor.is_reading() { *self = Self::from_id(id)?; } match self { RespawnEntry::Bot(v) => v.visit("Data", visitor)?, RespawnEntry::Player(v) => v.visit("Data", visitor)?, } visitor.leave_region() } } impl Level { pub async fn new( engine: &mut GameEngine, control_scheme: Rc<RefCell<ControlScheme>>, sender: Sender<Message>, options: MatchOptions, ) -> Level { let mut scene = Scene::new(); let (proximity_events_sender, proximity_events_receiver) = crossbeam::channel::unbounded(); let (contact_events_sender, contact_events_receiver) = crossbeam::channel::unbounded(); scene.physics.event_handler = Box::new(ChannelEventCollector::new( proximity_events_sender.clone(), contact_events_sender.clone(), )); // Spectator camera is used when there is no player on level. // This includes situation when player is dead - all dead actors are removed // from level. let spectator_camera = scene.graph.add_node(Node::Camera( CameraBuilder::new(BaseBuilder::new()) .enabled(false) .build(), )); let map_model = engine .resource_manager .request_model(Path::new("data/models/dm6.fbx")) .await .unwrap(); // Instantiate map let map_root = map_model.instantiate_geometry(&mut scene); // Create collision geometry let polygon_handle = scene.graph.find_by_name(map_root, "Polygon"); if polygon_handle.is_some() { let collider = scene .physics .mesh_to_trimesh(scene.graph[polygon_handle].as_mesh()); scene.physics_binder.bind(polygon_handle, collider); } else { println!("Unable to find Polygon node to build collision shape for level!"); } let mut level = Level { scene: engine.scenes.add(scene), sender: Some(sender), control_scheme: Some(control_scheme), map_root, options, spectator_camera, contact_events_receiver: Some(contact_events_receiver), proximity_events_receiver: Some(proximity_events_receiver), ..Default::default() }; level.build_navmesh(engine); level.analyze(engine).await; level.spawn_player(engine).await; level .spawn_bot(engine, BotKind::Maw, Some("Maw".to_owned())) .await; level .spawn_bot(engine, BotKind::Mutant, Some("Mutant".to_owned())) .await; level .spawn_bot(engine, BotKind::Parasite, Some("Parasite".to_owned())) .await; level } pub fn build_navmesh(&mut self, engine: &mut GameEngine) { if self.navmesh.is_none() { let scene = &mut engine.scenes[self.scene]; let navmesh_handle = scene.graph.find_by_name(self.map_root, "Navmesh"); if navmesh_handle.is_some() { let navmesh_node = &mut scene.graph[navmesh_handle]; navmesh_node.set_visibility(false); self.navmesh = Some(Navmesh::from_mesh(navmesh_node.as_mesh())); } else { println!("Unable to find Navmesh node to build navmesh!") } } } pub async fn analyze(&mut self, engine: &mut GameEngine) { let mut items = Vec::new(); let mut spawn_points = Vec::new(); let mut death_zones = Vec::new(); let scene = &mut engine.scenes[self.scene]; for (handle, node) in scene.graph.pair_iter() { let position = node.global_position(); let name = node.name(); if name.starts_with("JumpPad") { let begin = scene .graph .find_by_name_from_root(format!("{}_Begin", name).as_str()); let end = scene .graph .find_by_name_from_root(format!("{}_End", name).as_str()); if begin.is_some() && end.is_some() { let begin = scene.graph[begin].global_position(); let end = scene.graph[end].global_position(); let d = end - begin; let len = d.norm(); let force = d.try_normalize(std::f32::EPSILON); let force = force.unwrap_or(Vector3::y()).scale(len * 3.0); let shape = scene.physics.mesh_to_trimesh(node.as_mesh()); scene.physics_binder.bind(handle, shape); self.jump_pads.add(JumpPad::new(shape, force)); }; } else if name.starts_with("Medkit") { items.push((ItemKind::Medkit, position)); } else if name.starts_with("Ammo_Ak47") { items.push((ItemKind::Ak47Ammo, position)); } else if name.starts_with("Ammo_M4") { items.push((ItemKind::M4Ammo, position)); } else if name.starts_with("Ammo_Plasma") { items.push((ItemKind::Plasma, position)); } else if name.starts_with("SpawnPoint") { spawn_points.push(node.global_position()) } else if name.starts_with("DeathZone") { if let Node::Mesh(_) = node { death_zones.push(handle); } } } for (kind, position) in items { self.items.add( Item::new( kind, position, scene, engine.resource_manager.clone(), self.sender.as_ref().unwrap().clone(), ) .await, ); } for handle in death_zones { let node = &mut scene.graph[handle]; node.set_visibility(false); self.death_zones.push(DeathZone { bounds: node.as_mesh().world_bounding_box(), }); } self.spawn_points = spawn_points .into_iter() .map(|p| SpawnPoint { position: p }) .collect(); } pub fn destroy(&mut self, engine: &mut GameEngine) { engine.scenes.remove(self.scene); } pub fn get_player(&self) -> Handle<Actor> { self.player } pub fn process_input_event(&mut self, event: &Event<()>) -> bool { if self.player.is_some() { if let Actor::Player(player) = self.actors.get_mut(self.player) { return player.process_input_event(event); } } false } pub fn actors(&self) -> &ActorContainer { &self.actors } pub fn actors_mut(&mut self) -> &mut ActorContainer { &mut self.actors } pub fn weapons(&self) -> &WeaponContainer { &self.weapons } fn pick(&self, engine: &mut GameEngine, from: Vector3<f32>, to: Vector3<f32>) -> Vector3<f32> { let scene = &mut engine.scenes[self.scene]; if let Some(ray) = Ray::from_two_points(&from, &to) { let options = RayCastOptions { ray, max_len: std::f32::MAX, groups: InteractionGroups::all(), sort_results: true, }; let mut query_buffer = Vec::default(); scene.physics.cast_ray(options, &mut query_buffer); if let Some(pt) = query_buffer.first() { pt.position.coords } else { from } } else { from } } fn remove_weapon(&mut self, engine: &mut GameEngine, weapon: Handle<Weapon>) { for projectile in self.projectiles.iter_mut() { if projectile.owner == weapon { // Reset owner because handle to weapon will be invalid after weapon freed. projectile.owner = Handle::NONE; } } self.weapons[weapon].clean_up(&mut engine.scenes[self.scene]); self.weapons.free(weapon); } async fn give_new_weapon( &mut self, engine: &mut GameEngine, actor: Handle<Actor>, kind: WeaponKind, ) { if self.actors.contains(actor) { let scene = &mut engine.scenes[self.scene]; let mut weapon = Weapon::new( kind, engine.resource_manager.clone(), scene, self.sender.as_ref().unwrap().clone(), ) .await; weapon.set_owner(actor); let weapon_model = weapon.get_model(); let actor = self.actors.get_mut(actor); let weapon_handle = self.weapons.add(weapon); actor.add_weapon(weapon_handle); scene.graph.link_nodes(weapon_model, actor.weapon_pivot()); self.sender .as_ref() .unwrap() .send(Message::AddNotification { text: format!("Actor picked up weapon {:?}", kind), }) .unwrap(); } } async fn add_bot( &mut self, engine: &mut GameEngine, kind: BotKind, position: Vector3<f32>, name: Option<String>, ) -> Handle<Actor> { let scene = &mut engine.scenes[self.scene]; let bot = Bot::new( kind, engine.resource_manager.clone(), scene, position, self.sender.as_ref().unwrap().clone(), ) .await; let name = name.unwrap_or_else(|| format!("Bot {:?} {}", kind, self.actors.count())); self.leader_board.get_or_add_actor(&name); let bot = self.actors.add(Actor::Bot(bot)); self.give_new_weapon(engine, bot, WeaponKind::Ak47).await; bot } async fn remove_actor(&mut self, engine: &mut GameEngine, actor: Handle<Actor>) { if self.actors.contains(actor) { let scene = &mut engine.scenes[self.scene]; let character = self.actors.get(actor); // Make sure to remove weapons and drop appropriate items (items will be temporary). let drop_position = character.position(&scene.physics); let weapons = character .weapons() .iter() .copied() .collect::<Vec<Handle<Weapon>>>(); for weapon in weapons { let item_kind = match self.weapons[weapon].get_kind() { WeaponKind::M4 => ItemKind::M4, WeaponKind::Ak47 => ItemKind::Ak47, WeaponKind::PlasmaRifle => ItemKind::PlasmaGun, WeaponKind::RocketLauncher => ItemKind::RocketLauncher, }; self.spawn_item(engine, item_kind, drop_position, true, Some(20.0)) .await; self.remove_weapon(engine, weapon); } let scene = &mut engine.scenes[self.scene]; self.actors.get_mut(actor).clean_up(scene); self.actors.free(actor); if self.player == actor { self.player = Handle::NONE; } } } async fn spawn_player(&mut self, engine: &mut GameEngine) -> Handle<Actor> { let index = self.find_suitable_spawn_point(engine); let spawn_position = self .spawn_points .get(index) .map_or(Vector3::default(), |pt| { pt.position + Vector3::new(0.0, 1.5, 0.0) }); let scene = &mut engine.scenes[self.scene]; if let Node::Camera(spectator_camera) = &mut scene.graph[self.spectator_camera] { spectator_camera.set_enabled(false); } let mut player = Player::new(scene, self.sender.as_ref().unwrap().clone()); if let Some(control_scheme) = self.control_scheme.as_ref() { player.set_control_scheme(control_scheme.clone()); } self.player = self.actors.add(Actor::Player(player)); self.actors .get_mut(self.player) .set_position(&mut scene.physics, spawn_position); self.give_new_weapon(engine, self.player, WeaponKind::M4) .await; self.give_new_weapon(engine, self.player, WeaponKind::Ak47) .await; self.give_new_weapon(engine, self.player, WeaponKind::PlasmaRifle) .await; self.give_new_weapon(engine, self.player, WeaponKind::RocketLauncher) .await; self.player } async fn give_item(&mut self, engine: &mut GameEngine, actor: Handle<Actor>, kind: ItemKind) { if self.actors.contains(actor) { let character = self.actors.get_mut(actor); match kind { ItemKind::Medkit => character.heal(20.0), ItemKind::Ak47 | ItemKind::PlasmaGun | ItemKind::M4 | ItemKind::RocketLauncher => { let weapon_kind = match kind { ItemKind::Ak47 => WeaponKind::Ak47, ItemKind::PlasmaGun => WeaponKind::PlasmaRifle, ItemKind::M4 => WeaponKind::M4, ItemKind::RocketLauncher => WeaponKind::RocketLauncher, _ => unreachable!(), }; let mut found = false; for weapon_handle in character.weapons() { let weapon = &mut self.weapons[*weapon_handle]; // If actor already has weapon of given kind, then just add ammo to it. if weapon.get_kind() == weapon_kind { found = true; weapon.add_ammo(200); break; } } // Finally if actor does not have such weapon, give new one to him. if !found { self.give_new_weapon(engine, actor, weapon_kind).await; } } ItemKind::Plasma | ItemKind::Ak47Ammo | ItemKind::M4Ammo => { for weapon in character.weapons() { let weapon = &mut self.weapons[*weapon]; let (weapon_kind, ammo) = match kind { ItemKind::Plasma => (WeaponKind::PlasmaRifle, 200), ItemKind::Ak47Ammo => (WeaponKind::Ak47, 200), ItemKind::M4Ammo => (WeaponKind::M4, 200), _ => continue, }; if weapon.get_kind() == weapon_kind { weapon.add_ammo(ammo); break; } } } } } } async fn pickup_item( &mut self, engine: &mut GameEngine, actor: Handle<Actor>, item: Handle<Item>, ) { if self.actors.contains(actor) && self.items.contains(item) { let item = self.items.get_mut(item); self.sender .as_ref() .unwrap() .send(Message::AddNotification { text: format!("Actor picked up item {:?}", item.get_kind()), }) .unwrap(); let scene = &mut engine.scenes[self.scene]; let position = item.position(&scene.graph); item.pick_up(); let kind = item.get_kind(); self.sender .as_ref() .unwrap() .send(Message::PlaySound { path: PathBuf::from("data/sounds/item_pickup.ogg"), position, gain: 1.0, rolloff_factor: 3.0, radius: 2.0, }) .unwrap(); self.give_item(engine, actor, kind).await; } } async fn create_projectile( &mut self, engine: &mut GameEngine, kind: ProjectileKind, position: Vector3<f32>, direction: Vector3<f32>, initial_velocity: Vector3<f32>, owner: Handle<Weapon>, basis: Matrix3<f32>, ) { let scene = &mut engine.scenes[self.scene]; let projectile = Projectile::new( kind, engine.resource_manager.clone(), scene, direction, position, owner, initial_velocity, self.sender.as_ref().unwrap().clone(), basis, ) .await; self.projectiles.add(projectile); } async fn shoot_weapon( &mut self, engine: &mut GameEngine, weapon_handle: Handle<Weapon>, initial_velocity: Vector3<f32>, time: GameTime, direction: Option<Vector3<f32>>, ) { if self.weapons.contains(weapon_handle) { let scene = &mut engine.scenes[self.scene]; let weapon = &mut self.weapons[weapon_handle]; if weapon.try_shoot(scene, time) { let kind = weapon.definition.projectile; let position = weapon.get_shot_position(&scene.graph); let direction = direction .unwrap_or_else(|| weapon.get_shot_direction(&scene.graph)) .try_normalize(std::f32::EPSILON) .unwrap_or_else(|| Vector3::z()); let basis = weapon.world_basis(&scene.graph); self.create_projectile( engine, kind, position, direction, initial_velocity, weapon_handle, basis, ) .await; } } } fn show_weapon(&mut self, engine: &mut GameEngine, weapon_handle: Handle<Weapon>, state: bool) { self.weapons[weapon_handle].set_visibility(state, &mut engine.scenes[self.scene].graph) } fn find_suitable_spawn_point(&self, engine: &mut GameEngine) -> usize { // Find spawn point with least amount of enemies nearby. let scene = &mut engine.scenes[self.scene]; let mut index = rand::thread_rng().gen_range(0, self.spawn_points.len()); let mut max_distance = -std::f32::MAX; for (i, pt) in self.spawn_points.iter().enumerate() { let mut sum_distance = 0.0; for actor in self.actors.iter() { let position = actor.position(&scene.physics); sum_distance += pt.position.metric_distance(&position); } if sum_distance > max_distance { max_distance = sum_distance; index = i; } } index } async fn spawn_bot( &mut self, engine: &mut GameEngine, kind: BotKind, name: Option<String>, ) -> Handle<Actor> { let index = self.find_suitable_spawn_point(engine); let spawn_position = self .spawn_points .get(index) .map_or(Vector3::default(), |pt| pt.position); let bot = self.add_bot(engine, kind, spawn_position, name).await; self.sender .as_ref() .unwrap() .send(Message::AddNotification { text: format!("Bot {} spawned!", self.actors.get(bot).name), }) .unwrap(); bot } fn damage_actor( &mut self, engine: &GameEngine, actor: Handle<Actor>, who: Handle<Actor>, amount: f32, time: GameTime, ) { if self.actors.contains(actor) && (who.is_none() || who.is_some() && self.actors.contains(who)) { let mut who_name = Default::default(); let message = if who.is_some() { who_name = self.actors.get(who).name.clone(); format!( "{} dealt {} damage to {}!", who_name, amount, self.actors.get(actor).name ) } else { format!("{} took {} damage!", self.actors.get(actor).name, amount) }; self.sender .as_ref() .unwrap() .send(Message::AddNotification { text: message }) .unwrap(); let who_position = if who.is_some() { let scene = &engine.scenes[self.scene]; Some(self.actors.get(who).position(&scene.physics)) } else { None }; let actor = self.actors.get_mut(actor); if let Actor::Bot(bot) = actor { if let Some(who_position) = who_position { bot.set_point_of_interest(who_position, time); } } let was_dead = actor.is_dead(); actor.damage(amount); if !was_dead && actor.is_dead() && who.is_some() { self.leader_board.add_frag(who_name) } } } async fn spawn_item( &mut self, engine: &mut GameEngine, kind: ItemKind, position: Vector3<f32>, adjust_height: bool, lifetime: Option<f32>, ) { let position = if adjust_height { self.pick(engine, position, position - Vector3::new(0.0, 1000.0, 0.0)) } else { position }; let scene = &mut engine.scenes[self.scene]; let mut item = Item::new( kind, position, scene, engine.resource_manager.clone(), self.sender.as_ref().unwrap().clone(), ) .await; item.set_lifetime(lifetime); self.items.add(item); } pub fn time(&self) -> f32 { self.time } fn update_respawn(&mut self, time: GameTime) { // Respawn is done in deferred manner: we just gather all info needed // for respawn, wait some time and then re-create actor. Actor is spawned // by sending a message: this is needed because there are some other // systems that catches such messages and updates their own state. for respawn_entry in self.respawn_list.iter_mut() { match respawn_entry { RespawnEntry::Bot(v) => { v.time_left -= time.delta; if v.time_left <= 0.0 { self.sender .as_mut() .unwrap() .send(Message::SpawnBot { kind: v.kind, name: v.name.clone(), }) .unwrap(); } } RespawnEntry::Player(v) => { v.time_left -= time.delta; if v.time_left <= 0.0 { self.sender .as_mut() .unwrap() .send(Message::SpawnPlayer) .unwrap(); } } } } self.respawn_list.retain(|entry| match entry { RespawnEntry::Bot(v) => v.time_left >= 0.0, RespawnEntry::Player(v) => v.time_left >= 0.0, }); } fn update_spectator_camera(&mut self, scene: &mut Scene) { if let Node::Camera(spectator_camera) = &mut scene.graph[self.spectator_camera] { let mut position = spectator_camera.global_position(); position.follow(&self.target_spectator_position, 0.1); spectator_camera .local_transform_mut() .set_position(position); } } fn update_death_zones(&mut self, scene: &Scene) { for (handle, actor) in self.actors.pair_iter_mut() { for death_zone in self.death_zones.iter() { if death_zone .bounds .is_contains_point(actor.position(&scene.physics)) { self.sender .as_ref() .unwrap() .send(Message::RespawnActor { actor: handle }) .unwrap(); } } } } fn update_game_ending(&self) { if self.leader_board.is_match_over(&self.options) { self.sender .as_ref() .unwrap() .send(Message::EndMatch) .unwrap(); } } pub fn update(&mut self, engine: &mut GameEngine, time: GameTime) { self.time += time.delta; self.update_respawn(time); let scene = &mut engine.scenes[self.scene]; while let Ok(proximity_event) = self.proximity_events_receiver.as_ref().unwrap().try_recv() { for proj in self.projectiles.iter_mut() { proj.handle_proximity(&proximity_event, scene, &self.actors, &self.weapons); } } self.update_spectator_camera(scene); self.update_death_zones(scene); self.weapons.update(scene, &self.actors); self.projectiles .update(scene, &self.actors, &self.weapons, time); self.items.update(scene, time); let mut ctx = UpdateContext { time, scene, sound_context: engine.sound_context.clone(), items: &self.items, jump_pads: &self.jump_pads, navmesh: self.navmesh.as_mut(), weapons: &self.weapons, }; self.actors.update(&mut ctx); while let Ok(contact_event) = self.contact_events_receiver.as_ref().unwrap().try_recv() { self.actors.handle_event(&contact_event, &mut ctx); } self.update_game_ending(); } pub async fn respawn_actor(&mut self, engine: &mut GameEngine, actor: Handle<Actor>) { if self.actors.contains(actor) { let name = self.actors.get(actor).name.clone(); self.leader_board.add_death(&name); let entry = match self.actors.get(actor) { Actor::Bot(bot) => RespawnEntry::Bot(BotRespawnEntry { name, kind: bot.definition.kind, time_left: RESPAWN_TIME, }), Actor::Player(player) => { // Turn on spectator camera and prepare its target position. Spectator // camera will be used to render world until player is despawned. let scene = &mut engine.scenes[self.scene]; let position = scene.graph[player.camera()].global_position(); if let Node::Camera(spectator_camera) = &mut scene.graph[self.spectator_camera] { spectator_camera .set_enabled(true) .local_transform_mut() .set_position(position); } // Use ray casting to get target position for spectator camera, it is used to // create "dropping head" effect. let ray = Ray::from_two_points( &position, &(position - Vector3::new(0.0, 1000.0, 0.0)), ) .unwrap(); let options = RayCastOptions { ray, max_len: std::f32::MAX, groups: InteractionGroups::all(), sort_results: true, }; let mut query_buffer = Vec::default(); scene.physics.cast_ray(options, &mut query_buffer); if let Some(hit) = query_buffer.first() { self.target_spectator_position = hit.position.coords; // Prevent see-thru-floor self.target_spectator_position.y += 0.1; } else { self.target_spectator_position = position; } RespawnEntry::Player(PlayerRespawnEntry { time_left: RESPAWN_TIME, }) } }; self.remove_actor(engine, actor).await; self.respawn_list.push(entry); } } pub async fn handle_message( &mut self, engine: &mut GameEngine, message: &Message, time: GameTime, ) { match message { &Message::GiveNewWeapon { actor, kind } => { self.give_new_weapon(engine, actor, kind).await; } Message::AddBot { kind, position, name, } => { self.add_bot(engine, *kind, *position, name.clone()).await; } &Message::RemoveActor { actor } => self.remove_actor(engine, actor).await, &Message::GiveItem { actor, kind } => { self.give_item(engine, actor, kind).await; } &Message::PickUpItem { actor, item } => { self.pickup_item(engine, actor, item).await; } &Message::ShootWeapon { weapon, initial_velocity, direction, } => { self.shoot_weapon(engine, weapon, initial_velocity, time, direction) .await } &Message::CreateProjectile { kind, position, direction, initial_velocity, owner, basis, } => { self.create_projectile( engine, kind, position, direction, initial_velocity, owner, basis, ) .await } &Message::ShowWeapon { weapon, state } => self.show_weapon(engine, weapon, state), Message::SpawnBot { kind, name } => { self.spawn_bot(engine, *kind, Some(name.clone())).await; } &Message::DamageActor { actor, who, amount } => { self.damage_actor(engine, actor, who, amount, time); } &Message::CreateEffect { kind, position } => effects::create( kind, &mut engine.scenes[self.scene].graph, engine.resource_manager.clone(), position, ), Message::SpawnPlayer => { self.spawn_player(engine).await; } &Message::SpawnItem { kind, position, adjust_height, lifetime, } => { self.spawn_item(engine, kind, position, adjust_height, lifetime) .await } &Message::RespawnActor { actor } => self.respawn_actor(engine, actor).await, _ => (), } } pub fn set_message_sender(&mut self, sender: Sender<Message>, engine: &mut GameEngine) { self.sender = Some(sender.clone()); // Attach new sender to all event sources. for actor in self.actors.iter_mut() { actor.sender = Some(sender.clone()); } for weapon in self.weapons.iter_mut() { weapon.sender = Some(sender.clone()); } for projectile in self.projectiles.iter_mut() { projectile.sender = Some(sender.clone()); } let (proximity_events_sender, proximity_events_receiver) = crossbeam::channel::unbounded(); let (contact_events_sender, contact_events_receiver) = crossbeam::channel::unbounded(); self.proximity_events_receiver = Some(proximity_events_receiver); self.contact_events_receiver = Some(contact_events_receiver); engine.scenes[self.scene].physics.event_handler = Box::new(ChannelEventCollector::new( proximity_events_sender.clone(), contact_events_sender.clone(), )); } pub fn debug_draw(&self, engine: &mut GameEngine) { let drawing_context = &mut engine.scenes[self.scene].drawing_context; drawing_context.clear_lines(); if let Some(navmesh) = self.navmesh.as_ref() { for pt in navmesh.vertices() { for neighbour in pt.neighbours() { drawing_context.add_line(scene::Line { begin: pt.position(), end: navmesh.vertices()[*neighbour].position(), color: Default::default(), }); } } for actor in self.actors.iter() { if let Actor::Bot(bot) = actor { bot.debug_draw(drawing_context); } } } for death_zone in self.death_zones.iter() { drawing_context.draw_aabb(&death_zone.bounds, Color::opaque(0, 0, 200)); } } } pub struct SpawnPoint { position: Vector3<f32>, } impl Default for SpawnPoint { fn default() -> Self { Self { position: Default::default(), } } } impl Visit for SpawnPoint { fn visit(&mut self, name: &str, visitor: &mut Visitor) -> VisitResult { visitor.enter_region(name)?; self.position.visit("Position", visitor)?; visitor.leave_region() } }
/** * Convenience class for exception when loading Bitmaps. */ private static class BitmapLoadException extends Exception { public BitmapLoadException(String msg) { super(msg); } }
Differences in peripheral nerve degeneration/regeneration between wild‐type and neuronal nitric oxide synthase knockout mice Nitric oxide (NO), a unique biological messenger molecule, is synthesized by three isoforms of the enzyme NO synthase (NOS) and diffuses from the site of production across cellular membranes. A postulated role for NO in degeneration and regeneration of peripheral nerves has been explored in a sciatic nerve model comparing wild‐type mice and mice lacking neuronal NOS after transection and microsurgical repair. In NOS knockout mice, regenerative delay was observed, preceded by a decelerated Wallerian degeneration (WD). In the regenerated nerve, pruning of uncontrolled sprouts was disturbed, leading to an enhanced number of axons, whereas remyelination seemed to be less affected. Delayed regeneration was associated with a delayed recovery of sensor and motor function. In such a context, possible NO targets are neurofilaments and myelin sheaths of the interrupted axon, filopodia of the growth cone, newly formed neuromuscular endplates, and Schwann cells in the distal nerve stump. The results presented suggest that 1) local release of NO following peripheral nerve injury is a crucial factor in degeneration/regeneration, 2) success of fiber regeneration in the peripheral nervous system depends on a regular WD, and 3) manipulation of NO supply may offer interesting therapeutic options for treatment of peripheral nerve lesions. © 2002 Wiley‐Liss, Inc.
package repository import ( "context" "fmt" "testing" "github.com/calmato/gran-book/api/server/user/internal/domain/user" "github.com/calmato/gran-book/api/server/user/pkg/database" "github.com/calmato/gran-book/api/server/user/pkg/test" "github.com/golang/mock/gomock" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestUserRepository_List(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() ctrl := gomock.NewController(t) defer ctrl.Finish() mocks, err := test.NewDBMock(ctrl) require.NoError(t, err) err = mocks.DeleteAll() require.NoError(t, err) users := make([]*user.User, 3) users[0] = testUser("00000000-0000-0000-0000-000000000000") users[1] = testUser("11111111-1111-1111-1111-111111111111") users[2] = testUser("22222222-2222-2222-2222-222222222222") err = mocks.UserDB.DB.Table(userTable).Create(&users).Error require.NoError(t, err) type args struct { query *database.ListQuery } type want struct { users user.Users isErr bool } tests := []struct { name string args args want want }{ { name: "success", args: args{ query: &database.ListQuery{ Limit: 20, Offset: 0, Conditions: []*database.ConditionQuery{}, }, }, want: want{ users: users, isErr: false, }, }, } for _, tt := range tests { tt := tt t.Run(tt.name, func(t *testing.T) { t.Parallel() target := NewUserRepository(mocks.UserDB, nil) us, err := target.List(ctx, tt.args.query) assert.Equal(t, tt.want.isErr, err != nil, err) for i := range tt.want.users { assert.Contains(t, us, tt.want.users[i]) } }) } } func TestUserRepository_ListFollow(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() ctrl := gomock.NewController(t) defer ctrl.Finish() mocks, err := test.NewDBMock(ctrl) require.NoError(t, err) err = mocks.DeleteAll() require.NoError(t, err) users := make([]*user.User, 3) users[0] = testUser("00000000-0000-0000-0000-000000000000") users[0].Username = "テストユーザー1" users[1] = testUser("11111111-1111-1111-1111-111111111111") users[1].Username = "テストユーザー2" users[2] = testUser("22222222-2222-2222-2222-222222222222") users[2].Username = "テストユーザー3" err = mocks.UserDB.DB.Table(userTable).Create(&users).Error require.NoError(t, err) relationships := make([]*user.Relationship, 2) relationships[0] = testRelationship(1, users[1].ID, users[0].ID) relationships[1] = testRelationship(2, users[2].ID, users[0].ID) err = mocks.UserDB.DB.Table(relationshipTable).Create(&relationships).Error require.NoError(t, err) type args struct { query *database.ListQuery } type want struct { follows user.Follows isErr bool } tests := []struct { name string args args want want }{ { name: "success", args: args{ query: &database.ListQuery{ Limit: 20, Offset: 0, Conditions: []*database.ConditionQuery{ { Field: "follower_id", Operator: "==", Value: "00000000-0000-0000-0000-000000000000", }, }, }, }, want: want{ follows: []*user.Follow{ { FollowID: "11111111-1111-1111-1111-111111111111", Username: "テストユーザー2", ThumbnailURL: "https://go.dev/images/gophers/ladder.svg", SelfIntroduction: "テストコードです。", }, { FollowID: "22222222-2222-2222-2222-222222222222", Username: "テストユーザー3", ThumbnailURL: "https://go.dev/images/gophers/ladder.svg", SelfIntroduction: "テストコードです。", }, }, isErr: false, }, }, } for _, tt := range tests { tt := tt t.Run(tt.name, func(t *testing.T) { t.Parallel() target := NewUserRepository(mocks.UserDB, nil) fs, err := target.ListFollow(ctx, tt.args.query) assert.Equal(t, tt.want.isErr, err != nil, err) for i := range tt.want.follows { assert.Contains(t, fs, tt.want.follows[i]) } }) } } func TestUserRepository_ListFollower(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() ctrl := gomock.NewController(t) defer ctrl.Finish() mocks, err := test.NewDBMock(ctrl) require.NoError(t, err) err = mocks.DeleteAll() require.NoError(t, err) users := make([]*user.User, 3) users[0] = testUser("00000000-0000-0000-0000-000000000000") users[0].Username = "テストユーザー1" users[1] = testUser("11111111-1111-1111-1111-111111111111") users[1].Username = "テストユーザー2" users[2] = testUser("22222222-2222-2222-2222-222222222222") users[2].Username = "テストユーザー3" err = mocks.UserDB.DB.Table(userTable).Create(&users).Error require.NoError(t, err) relationships := make([]*user.Relationship, 2) relationships[0] = testRelationship(1, users[0].ID, users[1].ID) relationships[1] = testRelationship(2, users[0].ID, users[2].ID) err = mocks.UserDB.DB.Table(relationshipTable).Create(&relationships).Error require.NoError(t, err) type args struct { query *database.ListQuery } type want struct { followers user.Followers isErr bool } tests := []struct { name string args args want want }{ { name: "success", args: args{ query: &database.ListQuery{ Limit: 20, Offset: 0, Conditions: []*database.ConditionQuery{ { Field: "follow_id", Operator: "==", Value: "00000000-0000-0000-0000-000000000000", }, }, }, }, want: want{ followers: []*user.Follower{ { FollowerID: "11111111-1111-1111-1111-111111111111", Username: "テストユーザー2", ThumbnailURL: "https://go.dev/images/gophers/ladder.svg", SelfIntroduction: "テストコードです。", }, { FollowerID: "22222222-2222-2222-2222-222222222222", Username: "テストユーザー3", ThumbnailURL: "https://go.dev/images/gophers/ladder.svg", SelfIntroduction: "テストコードです。", }, }, isErr: false, }, }, } for _, tt := range tests { tt := tt t.Run(tt.name, func(t *testing.T) { t.Parallel() target := NewUserRepository(mocks.UserDB, nil) fs, err := target.ListFollower(ctx, tt.args.query) assert.Equal(t, tt.want.isErr, err != nil, err) for i := range tt.want.followers { assert.Contains(t, fs, tt.want.followers[i]) } }) } } func TestUserRepository_ListInstanceID(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() ctrl := gomock.NewController(t) defer ctrl.Finish() mocks, err := test.NewDBMock(ctrl) require.NoError(t, err) err = mocks.DeleteAll() require.NoError(t, err) users := make([]*user.User, 3) users[0] = testUser("00000000-0000-0000-0000-000000000000") users[0].InstanceID = "ExponentPushToken[qw<PASSWORD>uiop]" users[1] = testUser("11111111-1111-1111-1111-111111111111") users[1].InstanceID = "ExponentPushToken[<PASSWORD>]" users[2] = testUser("22222222-2222-2222-2222-222222222222") users[2].InstanceID = "ExponentPushToken[zxcvbnm]" err = mocks.UserDB.DB.Table(userTable).Create(&users).Error require.NoError(t, err) type args struct { query *database.ListQuery } type want struct { instanceIDs []string isErr bool } tests := []struct { name string args args want want }{ { name: "success", args: args{ query: &database.ListQuery{ Limit: 20, Offset: 0, Conditions: []*database.ConditionQuery{}, }, }, want: want{ instanceIDs: []string{ "ExponentPushToken[qwertyuiop]", "ExponentPushToken[<PASSWORD>]", "ExponentPushToken[zxcvbnm]", }, isErr: false, }, }, } for _, tt := range tests { tt := tt t.Run(tt.name, func(t *testing.T) { t.Parallel() target := NewUserRepository(mocks.UserDB, nil) us, err := target.ListInstanceID(ctx, tt.args.query) assert.Equal(t, tt.want.isErr, err != nil, err) for i := range tt.want.instanceIDs { assert.Contains(t, us, tt.want.instanceIDs[i]) } }) } } func TestUserRepository_ListFollowID(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() ctrl := gomock.NewController(t) defer ctrl.Finish() mocks, err := test.NewDBMock(ctrl) require.NoError(t, err) err = mocks.DeleteAll() require.NoError(t, err) users := make([]*user.User, 3) users[0] = testUser("00000000-0000-0000-0000-000000000000") users[0].Username = "テストユーザー1" users[1] = testUser("11111111-1111-1111-1111-111111111111") users[1].Username = "テストユーザー2" users[2] = testUser("22222222-2222-2222-2222-222222222222") users[2].Username = "テストユーザー3" err = mocks.UserDB.DB.Table(userTable).Create(&users).Error require.NoError(t, err) relationships := make([]*user.Relationship, 2) relationships[0] = testRelationship(1, users[1].ID, users[0].ID) relationships[1] = testRelationship(2, users[2].ID, users[0].ID) err = mocks.UserDB.DB.Table(relationshipTable).Create(&relationships).Error require.NoError(t, err) type args struct { followerID string followIDs []string } type want struct { followIDs []string isErr bool } tests := []struct { name string args args want want }{ { name: "success", args: args{ followerID: "00000000-0000-0000-0000-000000000000", followIDs: []string{}, }, want: want{ followIDs: []string{ "11111111-1111-1111-1111-111111111111", "22222222-2222-2222-2222-222222222222", }, isErr: false, }, }, { name: "success: filter followIDs", args: args{ followerID: "00000000-0000-0000-0000-000000000000", followIDs: []string{ "11111111-1111-1111-1111-111111111111", }, }, want: want{ followIDs: []string{ "11111111-1111-1111-1111-111111111111", }, isErr: false, }, }, } for _, tt := range tests { tt := tt t.Run(tt.name, func(t *testing.T) { t.Parallel() target := NewUserRepository(mocks.UserDB, nil) followIDs, err := target.ListFollowID(ctx, tt.args.followerID, tt.args.followIDs...) assert.Equal(t, tt.want.isErr, err != nil, err) for i := range tt.want.followIDs { assert.Contains(t, followIDs, tt.want.followIDs[i]) } }) } } func TestUserRepository_ListFollowerID(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() ctrl := gomock.NewController(t) defer ctrl.Finish() mocks, err := test.NewDBMock(ctrl) require.NoError(t, err) err = mocks.DeleteAll() require.NoError(t, err) users := make([]*user.User, 3) users[0] = testUser("00000000-0000-0000-0000-000000000000") users[0].Username = "テストユーザー1" users[1] = testUser("11111111-1111-1111-1111-111111111111") users[1].Username = "テストユーザー2" users[2] = testUser("22222222-2222-2222-2222-222222222222") users[2].Username = "テストユーザー3" err = mocks.UserDB.DB.Table(userTable).Create(&users).Error require.NoError(t, err) relationships := make([]*user.Relationship, 2) relationships[0] = testRelationship(1, users[0].ID, users[1].ID) relationships[1] = testRelationship(2, users[0].ID, users[2].ID) err = mocks.UserDB.DB.Table(relationshipTable).Create(&relationships).Error require.NoError(t, err) type args struct { followID string followerIDs []string } type want struct { followerIDs []string isErr bool } tests := []struct { name string args args want want }{ { name: "success", args: args{ followID: "00000000-0000-0000-0000-000000000000", followerIDs: []string{}, }, want: want{ followerIDs: []string{ "11111111-1111-1111-1111-111111111111", "22222222-2222-2222-2222-222222222222", }, isErr: false, }, }, { name: "success: filter followerIDs", args: args{ followID: "00000000-0000-0000-0000-000000000000", followerIDs: []string{ "11111111-1111-1111-1111-111111111111", }, }, want: want{ followerIDs: []string{ "11111111-1111-1111-1111-111111111111", }, isErr: false, }, }, } for _, tt := range tests { tt := tt t.Run(tt.name, func(t *testing.T) { t.Parallel() target := NewUserRepository(mocks.UserDB, nil) followerIDs, err := target.ListFollowerID(ctx, tt.args.followID, tt.args.followerIDs...) assert.Equal(t, tt.want.isErr, err != nil, err) for i := range tt.want.followerIDs { assert.Contains(t, followerIDs, tt.want.followerIDs[i]) } }) } } func TestUserRepository_Count(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() ctrl := gomock.NewController(t) defer ctrl.Finish() mocks, err := test.NewDBMock(ctrl) require.NoError(t, err) err = mocks.DeleteAll() require.NoError(t, err) users := make([]*user.User, 3) users[0] = testUser("00000000-0000-0000-0000-000000000000") users[1] = testUser("11111111-1111-1111-1111-111111111111") users[2] = testUser("22222222-2222-2222-2222-222222222222") err = mocks.UserDB.DB.Table(userTable).Create(&users).Error require.NoError(t, err) type args struct { query *database.ListQuery } type want struct { count int isErr bool } tests := []struct { name string args args want want }{ { name: "success", args: args{ query: &database.ListQuery{ Limit: 20, Offset: 0, Conditions: []*database.ConditionQuery{}, }, }, want: want{ count: 3, isErr: false, }, }, } for _, tt := range tests { tt := tt t.Run(tt.name, func(t *testing.T) { t.Parallel() target := NewUserRepository(mocks.UserDB, nil) count, err := target.Count(ctx, tt.args.query) assert.Equal(t, tt.want.isErr, err != nil, err) assert.Equal(t, tt.want.count, count) }) } } func TestUserRepository_CountRelationship(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() ctrl := gomock.NewController(t) defer ctrl.Finish() mocks, err := test.NewDBMock(ctrl) require.NoError(t, err) err = mocks.DeleteAll() require.NoError(t, err) users := make([]*user.User, 3) users[0] = testUser("00000000-0000-0000-0000-000000000000") users[0].Username = "テストユーザー1" users[1] = testUser("11111111-1111-1111-1111-111111111111") users[1].Username = "テストユーザー2" users[2] = testUser("22222222-2222-2222-2222-222222222222") users[2].Username = "テストユーザー3" err = mocks.UserDB.DB.Table(userTable).Create(&users).Error require.NoError(t, err) relationships := make([]*user.Relationship, 2) relationships[0] = testRelationship(1, users[1].ID, users[0].ID) relationships[1] = testRelationship(2, users[2].ID, users[0].ID) err = mocks.UserDB.DB.Table(relationshipTable).Create(&relationships).Error require.NoError(t, err) type args struct { query *database.ListQuery } type want struct { count int isErr bool } tests := []struct { name string args args want want }{ { name: "success", args: args{ query: &database.ListQuery{ Limit: 20, Offset: 0, Conditions: []*database.ConditionQuery{ { Field: "follower_id", Operator: "==", Value: "00000000-0000-0000-0000-000000000000", }, }, }, }, want: want{ count: 2, isErr: false, }, }, } for _, tt := range tests { tt := tt t.Run(tt.name, func(t *testing.T) { t.Parallel() target := NewUserRepository(mocks.UserDB, nil) count, err := target.CountRelationship(ctx, tt.args.query) assert.Equal(t, tt.want.isErr, err != nil, err) assert.Equal(t, tt.want.count, count) }) } } func TestUserRepository_MultiGet(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() ctrl := gomock.NewController(t) defer ctrl.Finish() mocks, err := test.NewDBMock(ctrl) require.NoError(t, err) err = mocks.DeleteAll() require.NoError(t, err) users := make([]*user.User, 3) users[0] = testUser("00000000-0000-0000-0000-000000000000") users[1] = testUser("11111111-1111-1111-1111-111111111111") users[2] = testUser("22222222-2222-2222-2222-222222222222") err = mocks.UserDB.DB.Table(userTable).Create(&users).Error require.NoError(t, err) type args struct { userIDs []string } type want struct { users user.Users isErr bool } tests := []struct { name string args args want want }{ { name: "success", args: args{ userIDs: []string{ "00000000-0000-0000-0000-000000000000", "11111111-1111-1111-1111-111111111111", "22222222-2222-2222-2222-222222222222", }, }, want: want{ users: users, isErr: false, }, }, } for _, tt := range tests { tt := tt t.Run(tt.name, func(t *testing.T) { t.Parallel() target := NewUserRepository(mocks.UserDB, nil) us, err := target.MultiGet(ctx, tt.args.userIDs) assert.Equal(t, tt.want.isErr, err != nil, err) for i := range tt.want.users { assert.Contains(t, us, tt.want.users[i]) } }) } } func TestUserRepository_Get(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() ctrl := gomock.NewController(t) defer ctrl.Finish() mocks, err := test.NewDBMock(ctrl) require.NoError(t, err) err = mocks.DeleteAll() require.NoError(t, err) u := testUser("00000000-0000-0000-0000-000000000000") err = mocks.UserDB.DB.Table(userTable).Create(u).Error require.NoError(t, err) type args struct { userID string } type want struct { user *user.User isErr bool } tests := []struct { name string args args want want }{ { name: "success", args: args{ userID: "00000000-0000-0000-0000-000000000000", }, want: want{ user: u, isErr: false, }, }, { name: "failed: not found", args: args{ userID: "", }, want: want{ user: &user.User{}, isErr: true, }, }, } for _, tt := range tests { tt := tt t.Run(tt.name, func(t *testing.T) { t.Parallel() target := NewUserRepository(mocks.UserDB, nil) u, err := target.Get(ctx, tt.args.userID) assert.Equal(t, tt.want.isErr, err != nil, err) assert.Equal(t, tt.want.user, u) }) } } func TestUserRepository_GetAdmin(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() ctrl := gomock.NewController(t) defer ctrl.Finish() mocks, err := test.NewDBMock(ctrl) require.NoError(t, err) err = mocks.DeleteAll() require.NoError(t, err) users := make([]*user.User, 2) users[0] = testUser("00000000-0000-0000-0000-000000000000") users[1] = testAdmin("11111111-1111-1111-1111-111111111111") err = mocks.UserDB.DB.Table(userTable).Create(&users).Error require.NoError(t, err) type args struct { userID string } type want struct { user *user.User isErr bool } tests := []struct { name string args args want want }{ { name: "success", args: args{ userID: "11111111-1111-1111-1111-111111111111", }, want: want{ user: users[1], isErr: false, }, }, { name: "failed: not found", args: args{ userID: "", }, want: want{ user: &user.User{}, isErr: true, }, }, { name: "failed: not found when role is user role", args: args{ userID: "00000000-0000-0000-0000-000000000000", }, want: want{ user: &user.User{}, isErr: true, }, }, } for _, tt := range tests { tt := tt t.Run(tt.name, func(t *testing.T) { t.Parallel() target := NewUserRepository(mocks.UserDB, nil) u, err := target.GetAdmin(ctx, tt.args.userID) assert.Equal(t, tt.want.isErr, err != nil, err) assert.Equal(t, tt.want.user, u) }) } } func TestUserRepository_GetRelationship(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() ctrl := gomock.NewController(t) defer ctrl.Finish() mocks, err := test.NewDBMock(ctrl) require.NoError(t, err) err = mocks.DeleteAll() require.NoError(t, err) users := make([]*user.User, 2) users[0] = testUser("00000000-0000-0000-0000-000000000000") users[0].Username = "テストユーザー1" users[1] = testUser("11111111-1111-1111-1111-111111111111") users[1].Username = "テストユーザー2" err = mocks.UserDB.DB.Table(userTable).Create(&users).Error require.NoError(t, err) relationship := testRelationship(1, users[1].ID, users[0].ID) err = mocks.UserDB.DB.Table(relationshipTable).Create(relationship).Error require.NoError(t, err) type args struct { followID string followerID string } type want struct { relationship *user.Relationship isErr bool } tests := []struct { name string args args want want }{ { name: "success", args: args{ followID: "11111111-1111-1111-1111-111111111111", followerID: "00000000-0000-0000-0000-000000000000", }, want: want{ relationship: relationship, isErr: false, }, }, } for _, tt := range tests { tt := tt t.Run(tt.name, func(t *testing.T) { t.Parallel() target := NewUserRepository(mocks.UserDB, nil) r, err := target.GetRelationship(ctx, tt.args.followID, tt.args.followerID) assert.Equal(t, tt.want.isErr, err != nil, err) assert.Equal(t, tt.want.relationship, r) }) } } func TestUserRepository_GetRelationshipIDByUserID(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() ctrl := gomock.NewController(t) defer ctrl.Finish() mocks, err := test.NewDBMock(ctrl) require.NoError(t, err) err = mocks.DeleteAll() require.NoError(t, err) users := make([]*user.User, 2) users[0] = testUser("00000000-0000-0000-0000-000000000000") users[0].Username = "テストユーザー1" users[1] = testUser("11111111-1111-1111-1111-111111111111") users[1].Username = "テストユーザー2" err = mocks.UserDB.DB.Table(userTable).Create(&users).Error require.NoError(t, err) relationship := testRelationship(1, users[1].ID, users[0].ID) err = mocks.UserDB.DB.Table(relationshipTable).Create(relationship).Error require.NoError(t, err) type args struct { followID string followerID string } type want struct { relationshipID int isErr bool } tests := []struct { name string args args want want }{ { name: "success", args: args{ followID: "11111111-1111-1111-1111-111111111111", followerID: "00000000-0000-0000-0000-000000000000", }, want: want{ relationshipID: relationship.ID, isErr: false, }, }, } for _, tt := range tests { tt := tt t.Run(tt.name, func(t *testing.T) { t.Parallel() target := NewUserRepository(mocks.UserDB, nil) id, err := target.GetRelationshipIDByUserID(ctx, tt.args.followID, tt.args.followerID) assert.Equal(t, tt.want.isErr, err != nil, err) assert.Equal(t, tt.want.relationshipID, id) }) } } func TestUserRepository_CreateRelationship(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() ctrl := gomock.NewController(t) defer ctrl.Finish() mocks, err := test.NewDBMock(ctrl) require.NoError(t, err) err = mocks.DeleteAll() require.NoError(t, err) type args struct { relationship *user.Relationship } type want struct { isErr bool } tests := []struct { name string setup func(t *testing.T, mocks *test.DBMocks) args args want want }{ { name: "success", setup: func(t *testing.T, mocks *test.DBMocks) { users := make([]*user.User, 2) users[0] = testUser("00000000-0000-0000-0000-000000000000") users[0].Username = "テストユーザー1" users[1] = testUser("11111111-1111-1111-1111-111111111111") users[1].Username = "テストユーザー2" err = mocks.UserDB.DB.Table(userTable).Create(&users).Error require.NoError(t, err) }, args: args{ relationship: &user.Relationship{ FollowID: "00000000-0000-0000-0000-000000000000", FollowerID: "11111111-1111-1111-1111-111111111111", CreatedAt: test.TimeMock, UpdatedAt: test.TimeMock, }, }, want: want{ isErr: false, }, }, { name: "failed: internal error", setup: func(t *testing.T, mocks *test.DBMocks) {}, args: args{ relationship: &user.Relationship{}, }, want: want{ isErr: true, }, }, } for _, tt := range tests { tt := tt t.Run(tt.name, func(t *testing.T) { err := mocks.Delete(mocks.UserDB, relationshipTable, userTable) require.NoError(t, err) tt.setup(t, mocks) target := NewUserRepository(mocks.UserDB, nil) err = target.CreateRelationship(ctx, tt.args.relationship) assert.Equal(t, tt.want.isErr, err != nil, err) }) } } func TestUserRepository_DeleteRelationship(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() ctrl := gomock.NewController(t) defer ctrl.Finish() mocks, err := test.NewDBMock(ctrl) require.NoError(t, err) err = mocks.DeleteAll() require.NoError(t, err) type args struct { relationshipID int } type want struct { isErr bool } tests := []struct { name string setup func(t *testing.T, mocks *test.DBMocks) args args want want }{ { name: "success", setup: func(t *testing.T, mocks *test.DBMocks) { users := make([]*user.User, 2) users[0] = testUser("00000000-0000-0000-0000-000000000000") users[0].Username = "テストユーザー1" users[1] = testUser("11111111-1111-1111-1111-111111111111") users[1].Username = "テストユーザー2" err = mocks.UserDB.DB.Table(userTable).Create(&users).Error require.NoError(t, err) relationship := testRelationship(1, users[1].ID, users[0].ID) err = mocks.UserDB.DB.Table(relationshipTable).Create(relationship).Error require.NoError(t, err) }, args: args{ relationshipID: 1, }, want: want{ isErr: false, }, }, } for _, tt := range tests { tt := tt t.Run(tt.name, func(t *testing.T) { err = mocks.Delete(mocks.UserDB, relationshipTable) require.NoError(t, err) tt.setup(t, mocks) target := NewUserRepository(mocks.UserDB, nil) err = target.DeleteRelationship(ctx, tt.args.relationshipID) assert.Equal(t, tt.want.isErr, err != nil, err) }) } } func testUser(id string) *user.User { return &user.User{ ID: id, Username: "テストユーザー", Gender: user.MaleGender, Email: fmt.Sprintf("%<EMAIL>", id), PhoneNumber: "000-0000-0000", Role: user.UserRole, ThumbnailURL: "https://go.dev/images/gophers/ladder.svg", SelfIntroduction: "テストコードです。", LastName: "テスト", FirstName: "ユーザー", LastNameKana: "てすと", FirstNameKana: "ゆーざー", PostalCode: "000-0000", Prefecture: "東京都", City: "小金井市", AddressLine1: "貫井北町4-1-1", AddressLine2: "", InstanceID: "ExponentPushToken[!Qaz2wsx3edc4rfv5tgb6y]", CreatedAt: test.TimeMock, UpdatedAt: test.TimeMock, } } func testAdmin(id string) *user.User { return &user.User{ ID: id, Username: "テストユーザー", Gender: user.MaleGender, Email: fmt.Sprintf("<EMAIL>", id), PhoneNumber: "000-0000-0000", Role: user.DeveloperRole, ThumbnailURL: "https://go.dev/images/gophers/ladder.svg", SelfIntroduction: "テストコードです。", LastName: "テスト", FirstName: "ユーザー", LastNameKana: "てすと", FirstNameKana: "ゆーざー", PostalCode: "", Prefecture: "", City: "", AddressLine1: "", AddressLine2: "", InstanceID: "ExponentPushToken[!Q<PASSWORD>edc<PASSWORD>gb6y]", CreatedAt: test.TimeMock, UpdatedAt: test.TimeMock, } } func testRelationship(id int, followID, followerID string) *user.Relationship { return &user.Relationship{ ID: id, FollowID: followID, FollowerID: followerID, CreatedAt: test.TimeMock, UpdatedAt: test.TimeMock, } }
<reponame>jackiehanyang/anomaly-detection /* * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to * this file be licensed under the Apache-2.0 license or a * compatible open source license. * * Modifications Copyright OpenSearch Contributors. See * GitHub history for details. */ package org.opensearch.ad.cluster; import static org.opensearch.ad.constant.CommonName.AD_PLUGIN_VERSION_FOR_TEST; import org.opensearch.Version; public class ADVersionUtil { public static final int VERSION_SEGMENTS = 3; public static Version fromString(String adVersion) { if (AD_PLUGIN_VERSION_FOR_TEST.equals(adVersion)) { return Version.CURRENT; } return Version.fromString(normalizeVersion(adVersion)); } public static String normalizeVersion(String adVersion) { if (adVersion == null) { throw new IllegalArgumentException("AD version is null"); } String[] versions = adVersion.split("\\."); if (versions.length < VERSION_SEGMENTS) { throw new IllegalArgumentException("Wrong AD version " + adVersion); } StringBuilder normalizedVersion = new StringBuilder(); normalizedVersion.append(versions[0]); for (int i = 1; i < VERSION_SEGMENTS; i++) { normalizedVersion.append("."); normalizedVersion.append(versions[i]); } return normalizedVersion.toString(); } public static boolean compatibleWithVersionOnOrAfter1_1(Version adVersion) { return adVersion != null && adVersion.onOrAfter(Version.V_1_1_0); } }
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.cognitiveservices.knowledge.qnamaker; import com.microsoft.azure.cognitiveservices.knowledge.qnamaker.models.ErrorResponseException; import com.microsoft.azure.cognitiveservices.knowledge.qnamaker.models.Operation; import com.microsoft.azure.cognitiveservices.knowledge.qnamaker.models.OperationsGetDetailsHeaders; import java.io.IOException; import rx.Observable; /** * An instance of this class provides access to all the operations defined * in Operations. */ public interface Operations { /** * Gets details of a specific long running operation. * * @param operationId Operation id. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws ErrorResponseException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the Operation object if successful. */ Operation getDetails(String operationId); /** * Gets details of a specific long running operation. * * @param operationId Operation id. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the Operation object */ Observable<Operation> getDetailsAsync(String operationId); }
import { Component, OnInit, Input, Output, EventEmitter, ViewChild } from '@angular/core'; import { StringValidation } from '../../../../resources/stringValidation'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { UtilitiesDate } from '../../../../models/utilities/utilitiesDate'; @Component({ selector: 'app-event-form', templateUrl: './event-form.component.html' }) export class EventFormComponent implements OnInit { /****************************VARIABLE GLOBALE********** */ public TAM_MAX_FILE: number = 10240; /*************************STRINGS APP********************* */ stringValidation: StringValidation; /***********************VARIABLES LOCALES**************** */ @Input() resetForm: {resetForm: string}; @Input() titleForm: {titleForm: string}; @Input() subtitleForm: {subtitleForm: string}; @Input() buttonAction: {buttonAction: string}; @ViewChild('categoryEvent') cbx_categoryEvent: any; optionEventType: Array<string>; city: string; contry: string; max_date: string; showErrorDateFinish: boolean; msjErrorDateFinish: string; showErrorDateStart: boolean; msjErrorDatePublication: string; showErrorPresentation: boolean; msjErrorPresentation: string; placeholderPresentation: string; showErrorCertificate: boolean; msjErrorCertificate: string; placeholderCertificate: string; msjErroBook: string; showErrorLocalization: boolean; msjErrorLocalization: string; /************************VARIABLES DE INSTANCIA********** */ @Output() getDataEvent = new EventEmitter<{doi: string, issn: string, typEvent: string, city: string, country: string titlePresentation: string,nameEvent: string,dateStart: string,dateFinish: string,filePresentation: File, fileCertificate: File}>(); fieldsForm: FormGroup; fileToCertificate: null; fileToPresentation: null; utilitiesDate: UtilitiesDate; constructor(private formBuilder: FormBuilder) { this.stringValidation = new StringValidation(); this.utilitiesDate = new UtilitiesDate(); this.optionEventType = ['Congreso','Seminario','Simposio']; this.placeholderPresentation = 'Archivo PDF que contenga la ponencia'; this.placeholderCertificate = 'Archivo PDF, PNG o JPG que contenga el certificado del evento'; this.showErrorLocalization = false; this.city = ''; this.contry = ''; this.showErrorDateFinish = false; this.showErrorDateStart = false; this.max_date = this.utilitiesDate.getMaxDate(); } ngOnInit() { this.fieldsForm = this.formBuilder.group( { doiEvent: ['', [Validators.required, Validators.maxLength(this.stringValidation.MAX_LONG_DOI), Validators.minLength(this.stringValidation.MIN_LONG_TEX) ] ], dateStartEvent: ['',[Validators.required]], dateEndEvent: ['',[Validators.required]], issnEvent: ['',[Validators.required, Validators.maxLength(this.stringValidation.MAX_LONG_ISSN), Validators.minLength(this.stringValidation.MIN_LONG_TEX), Validators.pattern('^([0-9]{4})+([-]{1})+([0-9]{3})+([0-9X]{1})$'), ] ], tittlePresentation: ['',[Validators.required, Validators.maxLength(this.stringValidation.MAX_LONG_TITLE_PRESENTATION), Validators.minLength(this.stringValidation.MIN_LONG_TEX) ] ], nameEvent: ['',[Validators.required, Validators.maxLength(this.stringValidation.MAX_LONG_NAME_EVENT), Validators.minLength(this.stringValidation.MIN_LONG_TEX) ] ], }); } handleFileInputPresentation(event: any) { const tam_file = event.target.files[0].size / 1024; const type_file = event.target.files[0].type.split('/'); if(type_file[1] == 'pdf') { if(tam_file > this.TAM_MAX_FILE) { this.msjErroBook = 'El archivo supera el limite de 10 MB'; this.showErrorPresentation = true; } else{ this.fileToPresentation = event.target.files[0]; this.placeholderPresentation = event.target.files[0].name; this.showErrorPresentation = false; } } else{ this.msjErroBook = 'Solo se permiten archivos PDF'; this.showErrorPresentation = true; } } handleFileInputCertificate(event: any) { const tam_file = event.target.files[0].size / 1024; const type_file = event.target.files[0].type.split('/'); if(type_file[1] == 'png' || type_file[1] == 'jpeg' || type_file[1] == 'pdf') { if(tam_file > this.TAM_MAX_FILE) { this.msjErrorCertificate= 'El archivo supera el limite de 10 MB'; this.showErrorCertificate = true; } else{ this.fileToCertificate = event.target.files[0]; this.placeholderCertificate = event.target.files[0].name; this.showErrorCertificate = false; } } else{ this.msjErrorCertificate = 'Solo se permiten archivos PNG, JPG o PDF'; this.showErrorCertificate = true; } } handleDateFinish(event: any) { const dateEndEv = this.fieldsForm.get('dateEndEvent').value; const dateStartEv = this.fieldsForm.get('dateStartEvent').value; if (dateEndEv < dateStartEv) { this.showErrorDateFinish = true; this.msjErrorDateFinish = 'La fecha de finalizacion no puede ser menor que la fecha de inicio'; } else if(dateEndEv == dateStartEv) { this.showErrorDateFinish = true; this.msjErrorDateFinish = 'La fecha de finalizacion no puede ser igual que la fecha de inicio'; } else{ this.showErrorDateFinish = false; this.showErrorDateStart = false; } } onSubmit() { if(this.city.length == 0 || this.contry.length == 0) { this.showErrorLocalization = true; this.msjErrorLocalization = 'Debe de seleccionar una ciudad'; } else if(this.verifySelectDates()) { if(this.fileToPresentation == null) { this.showErrorPresentation = true; this.msjErrorPresentation = 'Debe cargar un PDF, PNG o JPG que muestre la ponencia'; } else if(this.fileToCertificate == null) { this.showErrorCertificate = true; this.msjErrorCertificate = 'Debe cargar un PDF, PNG o JPG que muestre el certificado del evento'; } else{ this.getDataaEvent(); } } } verifySelectDates() { if((this.fieldsForm.get('dateStartEvent').value.length == 0) || this.showErrorDateStart) { if(this.showErrorDateStart) { this.showErrorDateFinish = true; this.msjErrorDatePublication = 'Este campo es obligatorio y presenta un error'; } else{ this.showErrorDateStart = true; this.msjErrorDatePublication = 'Este campo es obligatorio'; } return false; } else if((this.fieldsForm.get('dateEndEvent').value.length == 0) || this.showErrorDateFinish) { if( this.showErrorDateFinish) { this.showErrorDateFinish = true; this.msjErrorDateFinish = 'Este campo es obligatorio y presenta un error'; }else{ this.showErrorDateFinish = true; this.msjErrorDateFinish = 'Este campo es obligatorio'; } return false; } else{ this.showErrorDateFinish = false; this.showErrorDateStart = false; return true; } } getLocalization(localization: {city: string, country: string}) { this.city = localization.city; this.contry = localization.country; } getDataaEvent() { this.getDataEvent.emit( { issn: this.fieldsForm.get('issnEvent').value, doi: this.fieldsForm.get('doiEvent').value, typEvent: this.cbx_categoryEvent.nativeElement.value, city: this.city, country: this.contry, titlePresentation: this.fieldsForm.get('tittlePresentation').value, nameEvent: this.fieldsForm.get('nameEvent').value, dateStart: this.fieldsForm.get('dateStartEvent').value, dateFinish: this.fieldsForm.get('dateEndEvent').value, filePresentation: this.fileToPresentation, fileCertificate: this.fileToCertificate, } ); } }
<gh_stars>0 package com.xu.myapplication; import android.graphics.Bitmap; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.util.LruCache; import android.view.View; import android.widget.Button; import android.widget.ImageView; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private static final String Tag = MainActivity.class.getSimpleName(); private String url; private RequestQueue queue; private StringRequest stringRequest; private Button sendButton, cancelButton; private LruCache<String, Bitmap> cache; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); url = "https://www.baidu.com/"; setContentView(R.layout.activity_main); sendButton = (Button) findViewById(R.id.send); cancelButton = (Button) findViewById(R.id.cancel); sendButton.setOnClickListener(this); cancelButton.setOnClickListener(this); queue = Volley.newRequestQueue(this); Test test = new Test(); //test.testImageLoad(this, (ImageView) findViewById(R.id.image_loader)); test.testNetworkImageView(this); int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024); Log.d("TAG", "Max memory is " + maxMemory + "KB"); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.send: sendRequest(); break; case R.id.cancel: cancelRequest(); break; } } private void cancelRequest() { queue.cancelAll(this); } public int count = 1; private void sendRequest() { stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.d(Tag, "ok"); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.d(Tag, "error"); } }); queue.add(stringRequest); } }
import pprint as pp import floodsystem.geo as geo import floodsystem.stationdata as sd stations = sd.build_station_list() cam_centre_pos = (52.2053, 0.1218) if __name__ == "__main__": print("\n*** Task 1B: CUED Part IA Flood Warning System ***\n") stations_by_dist = \ list(map(lambda r: (r[0].name, r[0].town, r[1]), geo.stations_by_distance(stations, cam_centre_pos))) print("10 Closest stations:") pp.pprint(stations_by_dist[:10]) print("\n10 Farthest stations:") pp.pprint(stations_by_dist[-10:])
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-team', templateUrl: './team.component.html', styleUrls: ['./team.component.css'] }) export class TeamComponent implements OnInit { public teams: any[]; constructor() { this.teams = new Array<Object>(); for (let i = 0; i < 3; i++) { this.teams.push({ image: 'assets/img/team_picture.png', name: '<NAME>', position: 'Developer', desc: 'Some quick example text to build on the card title and make up the bulk of the card\'s content.' }); } } ngOnInit() { } }
<gh_stars>10-100 #ifndef CHIPMUNK_BODY_H #define CHIPMUNK_BODY_H #include <chipmunk/chipmunk.h> #include <memory> #include <functional> namespace cp { class Shape; class Space; class Arbiter; class Body { public: static const struct StaticTag {} Static; static const struct KinematicTag {} Kinematic; Body(cpFloat mass, cpFloat inertia); Body(StaticTag); Body(KinematicTag); Body(Body&&); explicit Body(cpBody* body); ~Body(); operator cpBody*() const; /// Wake up a sleeping or idle body. inline void activate() { cpBodyActivate(_body); }; /// Wake up any sleeping or idle bodies touching a static body. inline void activateStatic(std::shared_ptr<Shape> filter); /// Force a body to fall asleep immediately. inline void sleep() { cpBodySleep(_body); }; /// Force a body to fall asleep immediately along with other bodies in a group. inline void sleepWithGroup(std::shared_ptr<Body> group) { cpBodySleepWithGroup(_body, *group); }; /// Returns true if the body is sleeping. inline cpBool isSleeping() { return cpBodyIsSleeping(_body); }; /// Get the type of the body. inline cpBodyType getBodyType() const { return cpBodyGetType(_body); }; /// Set the type of the body. inline void setBodyType(cpBodyType type) { cpBodySetType(_body, type); } /// Get the mass of the body. inline cpFloat getMass() const { return cpBodyGetMass(_body); }; /// Set the mass of the body. inline void setMass(cpFloat mass) { cpBodySetMass(_body, mass); }; /// Get the moment of inertia of the body. inline cpFloat getMoment() const { return cpBodyGetMoment(_body); }; /// Set the moment of inertia of the body. inline void setMoment(cpFloat moment) { cpBodySetMoment(_body, moment); }; /// Set the position of a body. inline cpVect getPosition() const { return cpBodyGetPosition(_body); }; /// Set the position of the body. inline void setPosition(cpVect position) { cpBodySetPosition(_body, position); }; /// Get the offset of the center of gravity in body local coordinates. inline cpVect getCenterOfGravity() { return cpBodyGetCenterOfGravity(_body); }; /// Set the offset of the center of gravity in body local coordinates. inline void setCenterOfGravity(cpVect cog) { cpBodySetCenterOfGravity(_body, cog); }; /// Get the velocity of the body. inline cpVect getVelocity() const { return cpBodyGetVelocity(_body); }; /// Set the velocity of the body. inline void setVelocity(cpVect velocity) { cpBodySetVelocity(_body, velocity); }; /// Get the force applied to the body for the next time step. inline cpVect getForce() const { return cpBodyGetForce(_body); }; /// Set the force applied to the body for the next time step. inline void setAngle(cpVect force) { cpBodySetForce(_body, force); }; /// Get the angle of the body. inline cpFloat getAngle() const { return cpBodyGetAngle(_body); }; /// Set the angle of a body. inline void setAngle(cpFloat angle) { cpBodySetAngle(_body, angle); }; /// Get the angular velocity of the body. inline cpFloat getAngularVelocity() const { return cpBodyGetAngularVelocity(_body); }; /// Set the angular velocity of the body. inline void setAngularVelocity(cpFloat velocity) { cpBodySetAngularVelocity(_body, velocity); }; /// Get the torque applied to the body for the next time step. inline cpFloat getTorque() const { return cpBodyGetTorque(_body); }; /// Set the torque applied to the body for the next time step. inline void setTorque(cpFloat torque) { cpBodySetTorque(_body, torque); }; /// Get the rotation vector of the body. (The x basis vector of it's transform.) inline cpVect getRotation() const { return cpBodyGetRotation(_body); }; /// Get the user data pointer assigned to the body. inline cpDataPointer getUserData() const { return cpBodyGetUserData(_body); } /// Set the user data pointer assigned to the body. inline void setUserData(cpDataPointer data) { cpBodySetUserData(_body, data); } /// Default velocity integration function.. void updateVelocity(cpVect gravity, cpFloat damping, cpFloat dt) { cpBodyUpdateVelocity(_body, gravity, damping, dt); }; /// Default position integration function. void updatePosition(cpFloat dt) { cpBodyUpdatePosition(_body, dt); }; /// Convert body relative/local coordinates to absolute/world coordinates. inline cpVect localToWorld(cpVect point) const { return cpBodyLocalToWorld(_body, point); }; /// Convert body absolute/world coordinates to relative/local coordinates. inline cpVect worldToLocal(cpVect point) const { return cpBodyWorldToLocal(_body, point); }; /// Apply a force to a body. Both the force and point are expressed in world coordinates. void applyForceAtWorldPoint(cpVect force, cpVect point) { cpBodyApplyForceAtWorldPoint(_body, force, point); }; /// Apply a force to a body. Both the force and point are expressed in body local coordinates. void applyForceAtLocalPoint(cpVect force, cpVect point) { cpBodyApplyForceAtWorldPoint(_body, force, point); }; /// Apply an impulse to a body. Both the impulse and point are expressed in world coordinates. void applyImpulseAtWorldPoint(cpVect impulse, cpVect point) { cpBodyApplyImpulseAtWorldPoint(_body, impulse, point); }; /// Apply an impulse to a body. Both the impulse and point are expressed in body local coordinates. void applyImpulseAtLocalPoint(cpVect impulse, cpVect point) { cpBodyApplyImpulseAtLocalPoint(_body, impulse, point); }; /// Get the velocity on a body (in world units) at a point on the body in world coordinates. inline cpVect getVelocityAtWorldPoint(cpVect point) const { return cpBodyGetVelocityAtWorldPoint(_body, point); }; /// Get the velocity on a body (in world units) at a point on the body in local coordinates. inline cpVect getVelocityAtLocalPoint(cpVect point) const { return cpBodyGetVelocityAtLocalPoint(_body, point); }; /// Get the amount of kinetic energy contained by the body. inline cpFloat kineticEnergy() { return cpBodyKineticEnergy(_body); }; /// Iterate through all arbiters void eachArbiter(std::function<void(Arbiter)> func); protected: cpBody* _body; bool _dirty; private: Body(const Body&); const Body& operator=(const Body&); friend class Space; }; } #endif /* Body_hpp */
class SegmentCollection: """ Class managing a collection of segments """ # paths save_dir = "../sav/" if EXEC_FROM_SOURCE else "sav/" backup_dir = "../sav/backup/" if EXEC_FROM_SOURCE else "sav/backup/" taxo_dir = "../tax/" if EXEC_FROM_SOURCE else "tax/" csv_dir = "../csv/" if EXEC_FROM_SOURCE else "csv/" custom_taxo_dir = "../tax/custom" if EXEC_FROM_SOURCE else "tax/" out_dir = "../out/" if EXEC_FROM_SOURCE else "out/" temp_dir = "{}/diannotator/".format(tempfile.gettempdir()) def __init__(self): """ Initialization of the segment collection """ self.save_file = os.path.abspath("{}tmp.pic".format(SegmentCollection.save_dir)) self.full_collection = [] # full collection of segments self.collection = self.full_collection.copy() # current collection used self.display_range = 0, 0 # current range of display self.annotations = {} # list of annotations self.taxonomy = None # taxonomy name self.labels = {} # label tagsets self.qualifiers = {} # label qualifier tagsets self.colors = {} # layer colors self.links = {} # link types self.i = 0 # collection index self.layer = None # active layer self.default_layer = None # default layer self.filter = False # active filter ###################### # NAVIGATION METHODS # ###################### def next(self, n=1): """ Sets the index to the next segment """ n = n if self.i + n < len(self.collection) else len(self.collection) - self.i - 1 self.i = self.i + n first, last = self.display_range if self.i > last: last = min(self.i, len(self.collection)) first = max(self.i - 50, 0) self.display_range = first, last def previous(self, n=1): """ Sets the index to the previous segment """ n = n if self.i - n >= 0 else self.i self.i = self.i - n first, last = self.display_range if self.i < first: first = max(0, self.i) last = min(first + 50, len(self.collection) - 1) self.display_range = first, last ################## # ACCESS METHODS # ################## def get_active(self): """ Returns the active segment """ return self.collection[self.i] def get_active_label(self): """ Returns the active segment's label """ segment = self.get_active() if segment.has(self.layer): return segment.get(self.layer) return False def get_active_qualifier(self): """ Returns the active segment's qualifier """ segment = self.get_active() if segment.has(self.layer, qualifier=True): return segment.get(self.layer, qualifier=True) return False def get_segment_indexes(self, segment): """ Return a tuple of segment indexes """ cs = None for s in self.collection: if s.id == segment.id: cs = s break fcs = None for s in self.full_collection: if s.id == segment.id: fcs = s break return (self.collection.index(cs), self.full_collection.index(fcs)) ######################## # MODIFICATION METHODS # ######################## def remove(self, segment): """ Removes a segment """ ci, fi = self.get_segment_indexes(segment) del self.collection[ci] del self.full_collection[fi] def insert(self, i, fi, insert): """ Inserts a segment at a specific index """ # insert into full collection self.full_collection.insert(i, insert) # insert into active collection self.collection.insert(fi, insert) def insert_after_active(self, insert): """ Inserts a segment after the active one """ # insert into full collection self.full_collection.insert(self.full_collection.index(self.get_active()) + 1, insert) # insert into active collection self.collection.insert(self.i + 1, insert) def legacy_to_annotations(self): """ Creates a normal annotation for each legacy annotations """ for segment in self.full_collection: for layer in segment.legacy: if layer in self.labels.keys(): # setting labels if segment.has(layer, legacy=True): annotation = segment.get(layer, legacy=True) if layer in self.labels and annotation in self.labels[layer]: segment.set(layer, annotation) # setting qualifiers if segment.has(layer, legacy=True, qualifier=True): annotation = segment.get(layer, legacy=True, qualifier=True) if layer in self.qualifiers and annotation in self.qualifiers[layer]: segment.set(layer, annotation, qualifier=True) # setting legacy links for ls, lt in segment.legacy_links: if lt in self.links: segment.create_link(ls, lt) def has_valid_legacy(self): """ Checks if the collection has valid legacy annotations """ for segment in self.full_collection: for layer in segment.legacy: if layer in self.labels.keys() or layer in self.qualifiers.keys(): if layer in self.labels and segment.get(layer, legacy=True) in self.labels[layer]: return True if layer in self.qualifiers and segment.get(layer, legacy=True, qualifier=True) in self.qualifiers[layer]: return True # setting legacy links for ls, lt in segment.legacy_links: if lt in self.links.keys(): return True return False ################################# # TAXONOMY MODIFICATION METHODS # ################################# def change_layer(self, layer, new_layer): """ Renames a layer """ if new_layer in self.labels.keys(): return False if layer == self.default_layer: self.default_layer = new_layer if layer == self.layer: self.layer = new_layer self.labels[new_layer] = self.labels[layer] del self.labels[layer] if layer in self.qualifiers: self.qualifiers[new_layer] = self.qualifiers[layer] del self.qualifiers[layer] if layer in self.colors: self.colors[new_layer] = self.colors[layer] del self.colors[layer] for segment in self.full_collection: if layer in segment.annotations: segment.annotations[new_layer] = segment.annotations[layer] del segment.annotations[layer] return True def change_label(self, layer, label, new_label): """ Renames a label """ index = self.labels[layer].index(label) self.labels[layer].remove(label) if new_label not in self.labels[layer]: self.labels[layer].insert(index, new_label) for segment in self.full_collection: if segment.has(layer, annotation=label): segment.set(layer, new_label) def change_qualifier(self, layer, qualifier, new_qualifier): """ Renames a qualifier """ index = self.qualifiers[layer].index(qualifier) self.qualifiers[layer].remove(qualifier) if new_qualifier not in self.qualifiers[layer]: self.qualifiers[layer].insert(index, new_qualifier) for segment in self.full_collection: if segment.has(layer, annotation=qualifier, qualifier=True): segment.set(layer, new_qualifier, qualifier=True) def change_link_type(self, link_type, new_link_type): """ Renames a link type """ # insert new link type, with prior color if new_link_type not in self.links: self.links[new_link_type] = self.links[link_type] # remove old link type del self.links[link_type] # replace in links and linked for all segment for segment in self.full_collection: for ls, lt in segment.links: if lt == link_type: segment.links.remove((ls, lt)) segment.links.append((ls, new_link_type)) for ls, lt in segment.linked: if lt == link_type: segment.linked.remove((ls, lt)) segment.linked.append((ls, new_link_type)) def add_layer(self, layer): """ Adds a new layer to the tagset """ self.labels[layer] = [] def add_label(self, layer, label): """ Adds a new label to the tagset """ if label not in self.labels[layer]: self.labels[layer].append(label) def add_qualifier(self, layer, qualifier): """ Adds a new qualifier to the tagset """ if layer not in self.qualifiers: self.qualifiers[layer] = [] if qualifier not in self.qualifiers[layer]: self.qualifiers[layer].append(qualifier) def add_link_type(self, link_type): """ Adds a new link type to the tagset """ if link_type not in self.links: self.links[link_type] = None def delete_layer(self, layer): """ Deletes a layer """ # remove the layer from the taxonomy del self.labels[layer] # remove the layer from all annotations for segment in self.full_collection: if layer in segment.annotations: del segment.annotations[layer] # changes the default layer if needed if layer == self.default_layer: self.default_layer = list(self.labels.keys())[0] # changes the active layer self.layer = self.default_layer def delete_label(self, layer, label): """ Deletes a label """ self.labels[layer].remove(label) for segment in self.full_collection: if segment.has(layer, annotation=label): segment.rem(layer) def delete_qualifier(self, layer, qualifier): """ Deletes a qualifier """ self.qualifiers[layer].remove(qualifier) for segment in self.full_collection: if segment.has(layer, annotation=qualifier, qualifier=True): segment.rem(layer, qualifier=True) def delete_link_type(self, link_type): """ Deletes a link type """ # remove old link type del self.links[link_type] # replace in links and linked for all segment for segment in self.full_collection: for ls, lt in segment.links: if lt == link_type: segment.links.remove((ls, lt)) for ls, lt in segment.linked: if lt == link_type: segment.linked.remove((ls, lt)) ################################## # TAXONOMY IMPORT/EXPORT METHODS # ################################## def import_taxonomy(self, path): """ Imports the collection's taxonomy from a JSON file """ try: with codecs.open(path, encoding="utf-8") as f: taxonomy = json.loads(f.read()) self.taxonomy = taxonomy["name"] self.layer = self.default_layer = taxonomy["default"] self.labels = taxonomy["labels"] # label tagsets self.qualifiers = taxonomy["qualifiers"] # label qualifier tagsets self.colors = taxonomy["colors"] # layer colors self.links = taxonomy["links"] # link types except Exception: logging.exception("DialogueActCollection.import_taxonomy()") return False return True def export_taxonomy(self, path): """ Exports the collection's taxonomy to a JSON file """ taxonomy = { "name": self.taxonomy, "default": self.default_layer, "colors": self.colors, "labels": self.labels, "qualifiers": self.qualifiers, "links": self.links } try: with open(path, "w") as f: json.dump(taxonomy, f, indent=4, ensure_ascii=False) except Exception: logging.exception("DialogueActCollection.export_taxonomy()") return False return True #################################### # COLLECTION IMPORT/EXPORT METHODS # #################################### def import_collection(self, path): """ Imports a new collection """ # backup of the full collection collection = self.collection full_collection = self.full_collection try: if path.endswith("json"): self.full_collection = self.import_collection_from_json(path) else: self.full_collection = self.import_collection_from_csv(path) # syncs the current collection to the full collection self.collection = self.full_collection.copy() # resets the index self.i = 0 # writes save path to /tmp self.write_save_path_to_tmp() except Exception: self.collection = collection self.full_collection = full_collection logging.exception("DialogueActCollection.import_collection()") return False self.i = 0 self.display_range = 0, min(len(self.collection) - 1, 50) return True def import_collection_from_json(self, path): """ Imports a new collection from a JSON file """ # JSON data with codecs.open(path, encoding="utf-8") as f: data = json.loads(f.read()) collection = [] segments_by_id = {} for dic in data: # create segment segment = Segment( dic["segment"], dic["participant"], parser.parse(dic["datetime"]) ) segment.raw = dic["raw"] segment.id = dic["id"] segment.legacy = dic["annotations"] segment.note = dic["note"] for lt, ids in dic["links"].items(): for identifier in ids: segment.legacy_links.append((segments_by_id[identifier], lt)) segments_by_id[identifier].legacy_linked.append((lt, segment)) # makes sure all ids are unique if segment.id in segments_by_id: raise Exception segments_by_id[segment.id] = segment # adds the segment to the full collection collection.append(segment) return collection def import_collection_from_csv(self, path): """ Imports a new collection from a CSV file """ collection = [] with open(path) as f: rows = [{k: v for k, v in row.items()} for row in csv.DictReader(f, skipinitialspace=True, delimiter="\t", quoting=csv.QUOTE_NONE)] segments_by_id = {} previous_segment = None segment = None # quotes remover remove_start_quotes = lambda s: s[1:] if s.startswith("\"") else s remove_end_quotes = lambda s: s[:-1] if s.endswith("\"") else s remove_quotes = lambda s: remove_start_quotes(remove_end_quotes(s)) for row in rows: # remove start and end quotes row = {k: remove_quotes(v) for k, v in row.items()} span = row["segment"].strip() if row["raw"] is None or row["raw"].strip() == "": segment = Segment( previous_segment.raw, previous_segment.participant, previous_segment.datetime ) if "id" in row and row["id"] != "": segment.id = row["id"] segment.original_raw = previous_segment.original_raw tokenizer = WhitespaceTokenizer() # last token of the previous segment's segment end_of_previous_span = tokenizer.tokenize(previous_segment.span)[-1] # position of the last token of the previous segment's segment in the full raw index = previous_segment.raw.index(end_of_previous_span) + len(end_of_previous_span) # ajust the raw of the current segment segment.raw = previous_segment.raw[index:].strip() # adjust the raw of the previous segment previous_segment.raw = previous_segment.raw[:index].strip() # update tokens of the previous segment previous_segment.tokenize() else: dt = parser.parse(row["datetime"]) if row["datetime"] is not None and row["datetime"].strip() != "" else previous_segment.datetime raw = row["raw"].strip() participant = row["participant"].strip() if row["participant"].strip() != "\\" else segment.participant segment = Segment( raw, participant, dt ) if "id" in row and row["id"] != "": segment.id = row["id"] # update the current segment's segment segment.span = span # update the current segment's tokens segment.tokenize() # set the current segment as the previous segment (for the next iteration) previous_segment = segment # loading legacy annotations for key in row.keys(): if key not in ["segment", "raw", "datetime", "participant", "links", "note", "id"] and row[key] is not None and row[key].strip() != "": if key.endswith("-value") and row[key]: # getting layer name from column layer = key[:len(key) - len("-value")] # adding qualifier segment.set(layer, row[key], qualifier=True, legacy=True) else: # adding label segment.set(key, row[key], legacy=True) # link extraction if "links" in row and row["links"] != "": links = row["links"].split(",") for link in links: lt = link.split("-")[1] identifier = link.split("-")[0] segment.legacy_links.append((segments_by_id[identifier], lt)) segments_by_id[identifier].legacy_linked.append((lt, segment)) # set note segment.note = row["note"].strip() if "note" in row and row["note"].strip() else None # makes sure all ids are unique if segment.id in segments_by_id: raise Exception segments_by_id[segment.id] = segment # adds the segment to the full collection collection.append(segment) return collection def export_collection(self, path): """ Exports the collection to the filesystem """ try: if path.endswith(".json"): self.export_collection_as_json(path) elif path.endswith(".csv"): self.export_collection_as_csv(path) except Exception: logging.exception("DialogueActCollection.export_collection()") return False return True def export_collection_as_json(self, path): """ Exports the collection in JSON format """ data = [segment.to_json_dict() for segment in self.full_collection] try: with open(path, "w") as f: json.dump(data, f, indent=4, ensure_ascii=False) except Exception: logging.exception("") return False return True def export_collection_as_csv(self, path): """ Exports the collection in CSV format """ legacy_layers = [] for segment in self.full_collection: for layer in segment.legacy.keys(): if layer not in legacy_layers: legacy_layers.append(layer) with open(path, "w") as f: w = csv.DictWriter(f, self.full_collection[0].to_csv_dict(self.labels, legacy_layers).keys(), delimiter="\t") w.writeheader() previous_raw = None for segment in self.full_collection: row = segment.to_csv_dict(self.labels, legacy_layers) if row["raw"] == previous_raw: row["raw"] = "" # no consecutives raws, should be left empty w.writerow(row) previous_raw = row["raw"] ########################### # SAVE MANAGEMENT METHODS # ########################### def save(self, path=None, backup=False): """ Serializes the SegmentCollection and writes it to the filesystem """ if self.layer is None: return False try: with open(path if path is not None else self.save_file, "wb") as f: pickle.dump(self, f, pickle.HIGHEST_PROTOCOL) if path and not backup: self.save_file = os.path.abspath(path) self.write_save_path_to_tmp() except Exception: logging.exception("DialogueActCollection.save()") return False return True def write_save_path_to_tmp(self): """ Writes the path to the current save file to /tmp """ try: if not os.path.exists(SegmentCollection.temp_dir): os.makedirs(SegmentCollection.temp_dir) with open("{}last_save.tmp".format(SegmentCollection.temp_dir), "w") as tmp: tmp.write(self.save_file) except Exception: logging.exception("DialogueActCollection.write_save_path_to_tmp()") return False return True @staticmethod def read_save_path_from_tmp(): """ Reads the path to the previous save file from /tmp """ if not os.path.exists(SegmentCollection.temp_dir): os.makedirs(SegmentCollection.temp_dir) path = "{}last_save.tmp".format(SegmentCollection.temp_dir) # check if file doesn't exist if not os.path.exists(path): return False with open(path, "r") as tmp: tmp.seek(0) return tmp.read().strip() @staticmethod def delete_save_path_on_tmp(): """ Deletes the previous save file from /tmp """ if not os.path.exists(SegmentCollection.temp_dir): return path = "{}last_save.tmp".format(SegmentCollection.temp_dir) if not os.path.exists(path): return os.remove(path) @staticmethod def load(path): """ Loads a serialized SegmentCollection """ try: with open(path, "rb") as f: sc = pickle.load(f) sc.write_save_path_to_tmp() sc.display_range = sc.i, min(len(sc.collection) - 1, sc.i + 50) return sc except Exception: logging.exception("DialogueActCollection.load()") return False return False
/** * @author Ovidiu Feodorov <[email protected]> * @since 7/29/16 */ public class AsynchronousCsvLineWriterTest extends DataConsumerTest { // Constants ------------------------------------------------------------------------------------------------------- private static final Logger log = LoggerFactory.getLogger(AsynchronousCsvLineWriterTest.class); // Static ---------------------------------------------------------------------------------------------------------- // Attributes ------------------------------------------------------------------------------------------------------ private PrintStream originalOut; // Constructors ---------------------------------------------------------------------------------------------------- // Public ---------------------------------------------------------------------------------------------------------- @After public void setUp() { this.originalOut = System.out; } @After public void cleanUp() { System.setOut(originalOut); assertTrue(Files.rmdir(new File(System.getProperty("basedir"), "target/test-scratch"), false)); } // constructor ----------------------------------------------------------------------------------------------------- @Test public void constructor_NullFileName_Foreground() throws Exception { AsynchronousCsvLineWriter aw = new AsynchronousCsvLineWriter(null, null, null); assertEquals(System.out, aw.getPrintStream()); } @Test public void constructor_OutputFileDoesNotExist() throws Exception { File dir = new File(System.getProperty("basedir"), "target/test-scratch"); assertTrue(dir.isDirectory()); File file = new File(dir, "test.csv"); assertFalse(file.isFile()); AsynchronousCsvLineWriter w = new AsynchronousCsvLineWriter(file.getPath(), null, null); BlockingQueue<Event> eventQueue = new ArrayBlockingQueue<>(1); w.setEventQueue(eventQueue); w.start(); // // make sure the file is created // assertTrue(file.isFile()); // // the file must be empty // assertEquals("", Files.read(file)); w.getEventQueue().put(new ShutdownEvent()); // // busy wait until the event gets processed // long t0 = System.currentTimeMillis(); long timeout = 2000L; while(w.isStarted() && System.currentTimeMillis() - t0 < timeout) { Thread.sleep(100L); } // // make sure the file is still there // assertTrue(file.isFile()); // // the file must be empty // assertEquals("", Files.read(file)); } // lifecycle ------------------------------------------------------------------------------------------------------- @Test public void lifecycle() throws Exception { MockPrintStream pseudoOut = new MockPrintStream(); System.setOut(pseudoOut); BlockingQueue<Event> queue = new ArrayBlockingQueue<>(10); AsynchronousCsvLineWriter w = new AsynchronousCsvLineWriter(null, null, false); w.setEventQueue(queue); assertFalse(w.isStarted()); assertFalse(w.isHeaderOn()); w.start(); assertTrue(w.isStarted()); // // send a timed event to the queue, this will make the writer to eventually write a line containing a timestamp // long time = 1L; GenericTimedEvent te = new GenericTimedEvent(time); queue.put(te); // // busy wait until the event gets processed // String line = null; long timeout = 5000L; long t0 = System.currentTimeMillis(); while(line == null && System.currentTimeMillis() - t0 < timeout) { Thread.sleep(100L); line = pseudoOut.getLine(); } if (line == null) { fail("the asynchronous writer failed to process the event and send it to 'stdout' in " + timeout + " ms"); } String expected = new SimpleDateFormat(Constants.DEFAULT_TIMESTAMP_FORMAT_LITERAL).format(time); assertEquals(expected, line); // // send a shutdown event // ShutdownEvent se = new ShutdownEvent(); queue.put(se); // // busy wait until the event gets processed // timeout = 2000L; t0 = System.currentTimeMillis(); while(w.isStarted() && System.currentTimeMillis() - t0 < timeout) { Thread.sleep(100L); } if (w.isStarted()) { fail("the asynchronous writer failed to shutdown in " + timeout + " ms"); } } @Test public void lifecycle_InsureWeCloseThePrintStreamOnExit() throws Exception { BlockingQueue<Event> queue = new ArrayBlockingQueue<>(1); AsynchronousCsvLineWriter w = new AsynchronousCsvLineWriter(null, null, null); w.setEventQueue(queue); MockPrintStream mps = new MockPrintStream(); w.setPrintStream(mps); w.start(); assertFalse(mps.isClosed()); // // shutdown // queue.put(new ShutdownEvent()); // // busy wait until the event gets processed // long timeout = 2000L; long t0 = System.currentTimeMillis(); while(w.isStarted() && System.currentTimeMillis() - t0 < timeout) { Thread.sleep(100L); } // // make sure the print stream is closed // assertTrue(mps.isClosed()); } @Test public void lifecycle_AppendToFile() throws Exception { BlockingQueue<Event> queue = new ArrayBlockingQueue<>(1); File dir = new File(System.getProperty("basedir"), "target/test-scratch"); assertTrue(dir.isDirectory()); File file = new File(dir, "test.csv"); assertFalse(file.isFile()); // // create the file and add some content to it // assertTrue(Files.write(file, "test\n")); assertTrue(file.isFile()); assertEquals("test\n", Files.read(file)); // // do append to file // final boolean append = true; AsynchronousCsvLineWriter w = new AsynchronousCsvLineWriter(file.getPath(), append, false); w.setEventQueue(queue); w.start(); // // the file has content // assertEquals("test\n", Files.read(file)); // // write an event // w.getEventQueue().put(new MockTimedEvent()); // // shutdown // w.getEventQueue().put(new ShutdownEvent()); // // busy wait until the event gets processed // long timeout = 2000L; long t = System.currentTimeMillis(); while(w.isStarted() && System.currentTimeMillis() - t < timeout) { Thread.sleep(100L); } // // make sure the file is still there // assertTrue(file.isFile()); // // the file must contain the original content and the event representation // String content = Files.read(file); StringTokenizer st = new StringTokenizer(content, "\n"); String line = st.nextToken(); assertEquals("test", line); line = st.nextToken(); assertFalse(line.trim().isEmpty()); // must be a valid timestamp Date date = new SimpleDateFormat(Constants.DEFAULT_TIMESTAMP_FORMAT_LITERAL).parse(line); long time = date.getTime(); assertTrue(time > 0); } @Test public void lifecycle_OverwriteFile() throws Exception { BlockingQueue<Event> queue = new ArrayBlockingQueue<>(1); File dir = new File(System.getProperty("basedir"), "target/test-scratch"); assertTrue(dir.isDirectory()); File file = new File(dir, "test.csv"); assertFalse(file.isFile()); // // create the file // assertTrue(Files.write(file, "test\n")); assertEquals("test\n", Files.read(file)); assertTrue(file.isFile()); // // do not append to file // final boolean append = false; AsynchronousCsvLineWriter w = new AsynchronousCsvLineWriter(file.getPath(), append, false); w.setEventQueue(queue); w.start(); // // the file has been overwritten already // assertTrue(Files.read(file).isEmpty()); // // write an event // w.getEventQueue().put(new MockTimedEvent()); // // shutdown // w.getEventQueue().put(new ShutdownEvent()); // // busy wait until the event gets processed // long timeout = 2000L; long t0 = System.currentTimeMillis(); while(w.isStarted() && System.currentTimeMillis() - t0 < timeout) { Thread.sleep(100L); } // // make sure the file is still there // assertTrue(file.isFile()); // // the original content must be gone and the event representation must have overwritten it // String content = Files.read(file); StringTokenizer st = new StringTokenizer(content, "\n"); String line = st.nextToken(); assertNotEquals("test", line); } @Test public void lifecycle_AsynchronousStop() throws Exception { MockPrintStream pseudoOut = new MockPrintStream(); System.setOut(pseudoOut); BlockingQueue<Event> queue = new ArrayBlockingQueue<>(10); AsynchronousCsvLineWriter w = new AsynchronousCsvLineWriter(null, null, false); w.setEventQueue(queue); assertFalse(w.isStarted()); assertFalse(w.isHeaderOn()); w.start(); assertTrue(w.isStarted()); // // send a timed event to the queue, this will make the writer to eventually write a line containing a timestamp // long time = 1L; GenericTimedEvent te = new GenericTimedEvent(time); queue.put(te); // // busy wait until the event gets processed // String line = null; long timeout = 5000L; long t0 = System.currentTimeMillis(); while(line == null && System.currentTimeMillis() - t0 < timeout) { Thread.sleep(100L); line = pseudoOut.getLine(); } if (line == null) { fail("the asynchronous writer failed to process the event and send it to 'stdout' in " + timeout + " ms"); } String expected = new SimpleDateFormat(Constants.DEFAULT_TIMESTAMP_FORMAT_LITERAL).format(time); assertEquals(expected, line); // // stop the writer asynchronously // w.stop(); // // busy wait until the event gets processed // timeout = 2000L; t0 = System.currentTimeMillis(); while(w.isStarted() && System.currentTimeMillis() - t0 < timeout) { Thread.sleep(100L); } if (w.isStarted()) { fail("the asynchronous writer failed to shutdown in " + timeout + " ms"); } } // run() ----------------------------------------------------------------------------------------------------------- @Test public void run_notATimedEvent() throws Exception { BlockingQueue<Event> queue = new ArrayBlockingQueue<>(2); AsynchronousCsvLineWriter w = new AsynchronousCsvLineWriter(null, null, null); w.setEventQueue(queue); // add an un-timed event, run() must not fail. It'll warn and continue MockEvent e = new MockEvent(); queue.put(e); // // this will stop the test // queue.put(new ShutdownEvent()); w.run(); log.info("all good"); // // busy wait until stopped // long timeout = 2000L; long t0 = System.currentTimeMillis(); while(w.isStarted() && System.currentTimeMillis() - t0 < timeout) { Thread.sleep(100L); } } // write() --------------------------------------------------------------------------------------------------------- @Test public void write() throws Exception { PropertyFactory pf = new PropertyFactory(); AddressImpl sourceAddress = new AddressImpl("mock-host"); String metricDefinitionId = "Z"; String metricDefinitionId2 = "A"; MockMetricDefinition md = new MockMetricDefinition(pf, sourceAddress, metricDefinitionId); MockMetricDefinition md2 = new MockMetricDefinition(pf, sourceAddress, metricDefinitionId2); MockPrintStream mps = new MockPrintStream(); AsynchronousCsvLineWriter w = new AsynchronousCsvLineWriter(null, null, true); w.setFieldOrder(Arrays.asList(md, md2)); w.setPrintStream(mps); assertTrue(w.isHeaderOn()); MockProperty mp = new MockProperty(metricDefinitionId, "some value"); MockProperty mp2 = new MockProperty(metricDefinitionId2, "some other value"); MultiSourceReadingEvent e = new MultiSourceReadingEvent(); e.addSourceReading(sourceAddress, Arrays.asList(mp, mp2)); w.write(e); String header = mps.getLine(); assertEquals("# time, Mock Metric Z, Mock Metric A", header); String line = mps.getLine(); assertTrue(line.contains(", some value, some other value")); line = mps.getLine(); assertNull(line); } // Package protected ----------------------------------------------------------------------------------------------- // Protected ------------------------------------------------------------------------------------------------------- @Override protected DataConsumer getDataConsumerToTest(BlockingQueue<Event> events) throws Exception { AsynchronousCsvLineWriter w = new AsynchronousCsvLineWriter(null, null, null); if (events != null) { w.setEventQueue(events); } return w; } // Private --------------------------------------------------------------------------------------------------------- // Inner classes --------------------------------------------------------------------------------------------------- }
A proof of the fundamental theorem of curves in space and its applications We give a necessary and suficente condition for the existence of a space curve with curvature $\kappa$ and torsion $\tau$ finding a solution of a nonlinear differential equation of second order and some applications are given for the general helices and slant helices. The fundamental theorem. The curves parameterized in space are objects of great interest and with them we can model and analyze problems that appear in different fields of physics and other sciences. In the classical differential geometry of curves it is well known that there are two geometric invariants that are: curvature and torsion; which determine the behavior of the curve in space. The fundamental theorem of the local theory of curves in space states that if two differentiable κ = κ(s) and τ = τ (s) functions are given and positive κ = κ(s) shows that there is a curve whose curvature is κ = κ(s) and whose torsion is τ = τ (s) and any other curve that meets the conditions that its curvature is κ = κ(s) and its torsion is τ = τ (s) differs from the previous curve by a rigid movement. The demonstration of this result, which appears in most texts of differential geometry, is done considering a system of nine differential equations and using the existence and uniqueness theorem of ordinary differential equations. In this paper we show a new proof of the theorem of the local theory of curves in space . Considering a differential equation of non-linear second order: We shall prove the fundamental theorem in the form Theorem 1.1. Given differentiable function κ(s) > 0 and the continous function τ (s), s ∈ (a, b), there exists a regular parametrized curve α : J → R 3 such that s is the arc length, κ(s) is the curvature, and τ (s) is the torsion of α. Moreover, any other curve α, satisfying the same conditions, differs from α by a rigid motion; that is, there exists an orthogonal linear map ρ of R 3 , with positive determinant, and a vector c such that α = ρ • α + c. In books on elementary differential geometry (see for example , the condition for function τ is usually given differentiable. The new proof we give of this theorem is based on a theorem of existence and uniqueness for a nonlinear differential equation of second orden. 2.1 2. Proof of the fundamental theorem. Lemma 2.1. Let κ : → R be a function always positive of class C 1 , and τ : → R be a function of class C 0 .Then the second-order differential equation and introducing the dependent variable, v = w ′ . It follows that the equation can now be rewritten in the form Note that the vector field < 1} is a continous fuction and Lipschitziana with respect to (w, v) in a neighborhood D of (s 1 , w 1 , v 1 ) ∈ I. In fact, the function F is well defined, since w 2 + v 2 therefore F is continous and Lipschitziana with respect to (w, v) in a neighborhood D of (s 1 , w 1 , v 1 ) ∈ I. And this implies by the P icard−Lindelöf ′ s theorem that the problem has a unique solution on some interval open J ⊂ (c, d) containing s 1 . Theorem 2.2. Given differentiable function κ(s) > 0 and the continous function τ (s), s ∈ (a, b), there exists a regular parametrized curve α : J → R 3 such that s is the arc length, κ(s) is the curvature, and τ (s) is the torsion of α. Moreover, any other curve α, satisfying the same conditions, differs from α by a rigid motion; that is, there exists an orthogonal linear map ρ of R 3 , with positive determinant, and a vector c such that α = ρ • α + c. Proof. Let's find an α curve, parameterized by arc length s, such that its curvature κ α is equal to κ and its torsion τ α is equal to τ. Let's write its tangent vector t = t(s) in polar coordinates, t = (sin φ cos θ, sin φ sin θ, cos φ). Therefore, its normal vector n = n(s) and its binormal vector b = b(s) are given by It is known that its Frenet trihedron t, n, b forms an orthonormal basis of R 3 and satisfies Therefore, for w =< t, D >,where D is a fixed unit vector, we have. dw ds =< dt ds , D >=< κn, D >= κ < n, D >, Since for any curve α there exists an orthogonal linear function σ of R 3 , with positive determinant such that the binormal vector b of σ • α satisfies < b, (0, 0, 1) > 0 in an neighborhood of s 0 ∈ (a, b) and knowing that the curvature κ and the torsion τ are invariant given a rigid movement. We can assume from the beginning that D = (0, 0, 1) and the binormal vector b of α satisfies < b, (0, 0, 1) > 0 in an neighborhood of s 0 ∈ (a, b). Therefore, we can consider the initial value problem: Now, given that cos φ =< t, (0, 0, 1) > and θ ′ sin 2 φ κ =< b, (0, 0, 1) >, we have that there are functions φ and θ, such that φ = arccos < t, (0, 0, 1) > = arccos ξ, By replacing these functions in the tangent vector t, given in polar coordinates, we find an α curve, given by α(s) = (x(s), y(s), z(s)), where This curve is parameterized by arc length s, its curvature is κ α = κ and its torsion is τ α = τ . In effect, using the curvature formula and the torsion formula, we have Now, suppose that α = α(s) is a curve parametrized by arc lenth s, where κ = κ(s) is its curvature, τ = τ (s) is its torsion and consider the canonical basis Clearly, there exists an orthogonal linear map σ of R 3 , with positive determinant such that the scalar product < σ • b 0 , e i > is greater than zero, for all i = 1, 2, 3. To each value of the parameter s of the curve β = σ • α + c * , we have associated the Frenet trihedron at s: Thus Frenet trihedron forms an orthonormal basis of R 3 and satisfies: It is clear, because of the continuity of the β curve, that exists a neighborhood N of s 0 ∈ I such that the binormal vector b β = b β (s) of the β curve satisfies that its scalar product < b β , e i > is greater than zero, for all i = 1, 2, 3. Hence this is This implies that the components < t β , e i > of the tangent vector t β of the curve β satisfies the initial value problem (2.5) in some neighborhoods I i ⊂ N , of s 0 ∈ I, for i = 1, 2, 3, respectively. Now, suppose there is another α curve such that its curvature κ(s) is equal to κ(s) and its torsion τ (s) is equal to τ (s), where s ∈ I. Let t 0 , n 0 , b 0 be the Frenet trihedron at s = s 0 ∈ I of α. Then, there exists an orthogonal linear map π of R 3 , with positive determinant such that And consider the Frenet trihedron t γ , n γ , b γ of the curve γ = π • α + c. Therefore, there is a neighborhood M of s 0 ∈ I such that the binormal vector b γ = b γ (s) of the γ curve satisfies that its scalar product < b γ , e i > is greater than zero, for all i = 1, 2, 3. This implies that the components < t γ , e i > of the tangent vector t γ of the curve γ satisfies the initial value problem 2.3, in some neighborhoods J i ⊂ M , of s 0 ∈ I, for i = 1, 2, 3, respectively. Therefore, since the solution to the initial value problem is unique, we have to . Therefore there exists an orthogonal linear map ρ of R 3 , with positive determinant, and a vector c such that α(s Reciprocally, let α : I → R 3 be a curve parametrized by arc lenth s, where κ = κ(s) is its curvature and τ = τ (s) is its torsion and let t 0 , n 0 , b 0 be the Frenet trihedron at s = s 0 ∈ I of α and consider the canonical basis {e i | i = 1, 2, 3} of R 3 . Then, there exists an orthogonal linear map σ of R 3 , with positive determinant such that the components < t β (s), e i > of the tangent vector t β of the curve β = σ • α satisfies the initial value problem in some neighborhoods I i of s 0 ∈ I, for i = 1, 2, 3, respectively 3. Applications Theorem 3.2. Let α be a unit speed space curve with κ = κ(s) = 0 and torsion τ = τ (s). Then the following statements are equivalent: Any other curve, satisfying the same conditions, differs from α by a rigid movement. Proof. Assume property (1) holds, this is suppose that the curve α : I → R 3 , with curvature κ(s) = 0 and torsion τ (s) is an general helix and consider its Frenet trihedron t, n, b. Then the principal tangent lines of α make a constant angle with a fixed direction, this is there is a fixed unit vector U , such that < t, U >= δ (constant). We know if w =< t, D >, then therefore, taking D = U , we have to 1 − δ 2 Now assume property (2) holds, this is consider the equation τ κ (s) = m, (constant) Now replacing τ = mκ in the second order differential equation 2.2, we have Considering the definition of the general helix, let's find a solution of the form ξ(s) = δ, where δ is an constant and satisfies 1 − δ 2 > 0. Replacing in the equation above we find that This implies that δ = m √ 1+m 2 . Therefore, ξ(s) = m √ 1+m 2 , is a solution of the non-linear second-order differential equation. Let's calculate the position vector of α using the expression In effect, Therefore, the components of the position vector are: x(s) = 1 √ 1 + m 2 cos( 1 + m 2 κds)ds, Now assume property (3) holds, a direct calculation shows that its tangent vector t α satisfies this is the principal tangent lines of α make a constant angle with a fixed direction U = (0, 0, 1). Now, if there is another curve that differs from α by a rigid movement, then it's tangent vector is given by ρt α , where ρ is an orthogonal linear map of R 3 , with positive determinant. For this case we take as a fixed direction ρ(0, 0, 1.) Definition 3.3. A curve α with κ(s) = 0 is called a slant helix if the principal normal lines of α make a constant angle with a fixed direction. Theorem 3.4. Let α be a unit speed space curve with κ = κ(s) = 0 and torsion τ = τ (s). Then the following statements are equivalent: (1) α is a slant helix. (2) is a constant function. Proof. Assume property (1) holds, this is suppose that the curve α : I → R 3 , with curvature κ(s) = 0 and torsion τ (s) is an slant helix and consider its Frenet trihedron t, n, b. Then the principal normal lines of α make a constant angle with a fixed direction, this is there is a fixed unit vector U , such that < n, U >= δ (constant). We know if w =< t, D >, then therefore, taking D = U , we have to therefore w 2 is given by Deriving with respect to s and since w is equal to δ s 0 κ, we have to . Now assume property (2) holds, this is consider the equation The torsion τ can be expressed as: where A is an integration constant. Now replacing τ in the second order differential equation 2.2, we have Considering the definition of the slant helix, let's find a solution of the form 1 κ dξ ds = δ, this is ξ = δ s 0 κds, where δ is an constant and the ξ function satisfies: Replacing in the equation above we find that Therefore, ξ = m √ 1+m 2 s 0 κds, (m > 0) is a solution of the non-linear second-order differential equation. s 0 κds, (m < 0) is a solution of the non-linear second-order differential equation. Let's calculate the position vector of α using the expression In effect, this is the principal normal lines of α make a constant angle with a fixed direction U = (0, 0, 1). Conclusion. The differential equation
Resistance to Oncolytic Myxoma Virus Therapy in Nf1−/−/Trp53−/− Syngeneic Mouse Glioma Models Is Independent of Anti-Viral Type-I Interferon Despite promising preclinical studies, oncolytic viral therapy for malignant gliomas has resulted in variable, but underwhelming results in clinical evaluations. Of concern are the low levels of tumour infection and viral replication within the tumour. This discrepancy between the laboratory and the clinic could result from the disparity of xenograft versus syngeneic models in determining in vivo viral infection, replication and treatment efficacy. Here we describe a panel of primary mouse glioma lines derived from Nf1 +/− Trp53 +/− mice in the C57Bl/6J background for use in the preclinical testing of the oncolytic virus Myxoma (MYXV). These lines show a range of susceptibility to MYXV replication in vitro, but all succumb to viral-mediated cell death. Two of these lines orthotopically grafted produced aggressive gliomas. Intracranial injection of MYXV failed to result in sustained viral replication or treatment efficacy, with minimal tumour infection that was completely resolved by 7 days post-infection. We hypothesized that the stromal production of Type-I interferons (IFNα/β) could explain the resistance seen in these models; however, we found that neither the cell lines in vitro nor the tumours in vivo produce any IFNα/β in response to MYXV infection. To confirm IFNα/β did not play a role in this resistance, we ablated the ability of tumours to respond to IFNα/β via IRF9 knockdown, and generated identical results. Our studies demonstrate that these syngeneic cell lines are relevant preclinical models for testing experimental glioma treatments, and show that IFNα/β is not responsible for the MYXV treatment resistance seen in syngeneic glioma models. Introduction Malignant gliomas (MGs) are devastating diseases and, although relatively rare, are almost universally terminal. The most severe, Grade IV gliomas (glioblastoma multiforme), have a median survival of only 12-15 months , a prognosis which has seen little improvement over several decades . The obvious need for new therapies has fostered a number of experimental treatment options, including the use of oncolytic viruses. Oncolytic virus (OV) therapy entails the use of replication competent viruses that selectively infect and kill cancer cells, as well as potentially initiate anti-tumoural immune responses. One of the most appealing tenants of OV therapy is the treatment's selfpotentiation, which hinges on the infection, replication, and spread of the virus throughout the tumor. Several OVs have been evaluated in MG clinical trials , and although safe, only a handful of clinical responses have been observed and evidence of tumour infection and viral replication was limited to very few patients . A likely explanation for the poor and variable clinical outcome despite promising preclinical results is the extensive reliance on xenograft glioma models for OV preclinical evaluation. Xenografts possess two important, but potentially overlapping limitations that compromise their utility as preclinical OV models. Firstly, the immunocompromised nature of these models inevitably affects the profile of immune infiltrates within the tumour microenvironment. By changing the cellular components of the tumour stroma, the cytokine, chemokine, and growth factor networks, which may be vitally important in OV resistance mechanisms, are fundamentally changed. Secondly, the antiviral signalling networks that exist within the murine tumour stroma may not signal effectively to the human tumour due to interspecies receptor-ligand incompatibility. Xenografts thus ignore many potential interactions between the glioma and its microenvironment prior or during OV treatment. These interactions are potentially of great importance, especially when considering potential immune-glioma interactions that could occur when using a replication-competent virus. We have previously found differences between xenograft and syngeneic MG models using Myxoma virus (MYXV), where MYXV has robust viral replication and often cures immunocompromised mice bearing orthotopic brain-tumor xenografts , but does not have comparable replication or efficacy in syngeneic rodent MGs . This is in dramatic contrast to tumour models outside the brain, such as disseminated pancreatic cancer in the intraperitoneal cavity, where MYXV virotherapy is most effective in syngeneic models where the full spectrum of innate and acquired immune responses were intact . The OV treatment resistance we have seen for MG in immunocompetent models is worrisome, as the syngeneic tumours used strongly recapitulate human MGs and retain immune cell populations and stromal interactions that are expected in MG patients. In order to interrogate the immune contributions that may affect efficacy of OVs in MGs, relevant murine MG models in the C57Bl/6 background are ideal, as this background has numerous mutant and transgenic strains that could assist in delineating these mechanisms. Here we characterize a panel of primary mouse glioma cell lines for the preclinical testing of oncolytic viral therapy, including the orthotopic grafting of these lines into C57Bl/6J mice. These lines were derived from C57Bl/6J NPcis mice (Trp53 +/2 /Nf1 +/2 ), which spontaneously develop high-grade gliomas that recapitulate many clinical phenotypes of the human disease . These lines show loss-of-heterozygosity of Nf1 (encoding neurofibromin) and Trp53 (encoding p53) in addition to PDGFRa expression , clinically relevant molecular features seen in many MG patients . Here we show that the NPcis lines show a range of susceptibility to MYXV replication in vitro, but all succumb to viral-mediated cell death. Two of these lines, K1492 and K1861, orthotopically grafted in C57Bl/6 mice produced aggressive tumours that retain human glioma markers. Despite their susceptibility to infection and replication in vitro, intracranial injection of MYXV failed to result in viral replication or treatment efficacy, with minimal tumour infection that was completely resolved by 7 days post-infection. These results closely mimic what we have previously shown in syngeneic rat models with MYXV , and has viral clearance kinetics similar to what others have shown in syngeneic mouse models with other OVs . We believe this to be an important and relevant resistance mechanism that must be overcome for OVs to reach maximal success in the clinic. Type-I interferon (IFNa/b) is the quintessential anti-viral cytokine, being able to mediate anti-viral responses in a variety of cell types. Further, it is a fundamental part of the anti-viral immune response in the CNS, as shown by IFNa/b-deficient mice having increased neurovirulence and mortality . Importantly for our work, it has long been known that human cells are non-responsive to murine IFNa/b ; thus, any murine IFNa/b produced by the stroma in conventional MG xenografts in response to infection or injury would have no effect on human xenografts expressing the human IFNa/b receptor. Here we confirmed that human glioma cell lines and mouse glioma cell lines are unresponsive to heterospecific IFNb, and show that NPcis mouse glioma cell lines are exquisitely sensitive to mouse IFNb. However, we found that Type-I IFN signalling is not involved in mediating resistance of implanted syngeneic MG to the intracranial injection of MYXV. Rather, our data show that NPcis-derived MGs develop an antiviral state, independent of glioma IFNa/b signalling, that rapidly prevents the replication and spread of MYXV. Our results thus suggest that IFNa/b signalling may be an inappropriate target to overcome MYXV resistance clinically for MG virotherapy. Identifying and overcoming this unique antiviral treatment resistance in the brain will be an important step forward in the preclinical development of MYXV for MG and possible other brain cancers. In vitro infection, viability and titers To detect viability of NPcis cell lines following MYXV infection in vitro, 2610 3 cells were plated in 96-well plates overnight, then infected at different multiplicity of infection (MOI)s of vMyx-GFP. Cell viability was measured at 48 hours post-infection (hpi) by Alamar Blue (Invitrogen) as described by the manufacturer. In experiments using exogenously applied IFNa/b, NPcis lines were pre-incubated in indicated concentration of mouse or human IFNb (PBL Interferon Source) 6 hours prior to MYXV infection. Viral replication was qualitatively assessed via early viral gene expression (vMyx-GFP) at 48 hpi. Cells and GFP fluorescence were observed by microscopy (Zeiss microscope with AxioVision v4.5 Software). Additionally, viral titers were performed by seeding 2.5610 4 NPcis or U87 cells in 24-well plates overnight and then treated with MYXV (MOI = 1). The cells and culture media were then collected, freeze-thawed 3 times, and MYXV titered on BGMK cells as previously described . Type-I Interferon Measurements Quantitating functional type-I interferon (IFNa/b) in vitro was performed in 96-well plates. NPcis lines were plated overnight, treated with listed stimulus (LMW PolyI:C from CalTech) and supernatant collected and measured on B16-Blue IFNa/b cells (InvivoGen) following the manufacturers' protocol. To confirm these results at the transcriptional level, RNA was collected (Qiagen RNeasy Plus) from K1492 or K1861, plated in 6-well plates overnight and treated with listed stimulus. cDNA was created with SuperScript II Reverse Transcriptase (Invitrogen) and PCR performed using primers listed in Table S1. To measure IFNa/b production in vivo following listed treatments, mice were sacrificed at designated time points and brains removed. The tumour-bearing hemisphere was dissected out, and placed in 500 mL cold PBS in a 1.5 mL microfuge tube. Brains were crushed in the tube using a micropestle, and then sonicated (262 sec, 10% Amplitude; Fisher Scientific Sonic Dismembrator Model 500), and spun at 30006 G for 15 minutes. Supernatants were then diluted to normalize protein levels (Bradord Assay; BioRad) and applied to Mouse Verikine Interferon a (#42120) and b (#42400) Elisa kit from PBL Interferon Source. Orthotopic tumour implantation and intracranial MYXV treatment Six to eight week-old female wild-type C57Bl/6J mice from Jackson Laboratories (#000664) or CB17 SCID from Charles River were used in this study. The animals were housed in a vivarium maintained on a 12-hour light/dark schedule with a temperature of 22+/21uC and a relative humidity of 50+/25%. Food and water were available ad libitum. All protocols were reviewed and approved by the Animal Care Committee of the University of Calgary. All animal work procedures were in accordance with the Guide to the Care and Use of Experimental Animals published by the Canadian Council on Animal Care and the Guide for the Care and Use of Laboratory Animals issued by NIH. For orthotopic injections of K1492 and K1861, the cells were prepared in a 2.5610 4 cell/mL PBS solution and 2 mL (5610 4 ) cells implanted into the right striatum of mice as described previously . Briefly, mice were anesthetized with ketamine/xylazine and a 0.5-mm burr hole was made 1.5-2 mm right of the midline and 0.5-1 mm posterior to the coronal suture through a scalp incision. Stereotactic injection used a 10 mL syringe (Hamilton Co., Reno, NV) with a 30-gauge needle, inserted through the burr hole to 3 mm, mounted on a Kopf stereotactic apparatus (Kopf Instruments, Tujanga, CA). The needle was left in place for 60 seconds, and then slowly withdrawn over a 60 second period. For survival studies, animals were followed until they lost 20% of body weight or had trouble ambulating, feeding, or grooming. Intracranial injection of 5610 6 FFU of vMyx-FLuc or vMyx-GFP was performed on day 14 for the K1492 and K1861 lines, unless otherwise stated. Virus was intratumourally administered using the same stereotactic technique as described above, and through the same burr hole created for the tumour implantation. In vivo viral replication and bioluminescence imaging Viral recovery from the tumour-bearing mice was done at day 0 (1 hours post-infection), 1, 3, 5, and 7 days post-infection. Animals were sacrificed and the tumour-bearing hemisphere crushed in the 500 uL of cold PBS using a small pestle, and then sonicated (262 sec, 10% Amplitude; Fisher Scientific Sonic Dismembrator Model 500), and spun at 30006 G for 15 minutes and frozen. Supernatants were thawed and then titred on BGMK cells as described above. Bioluminescence from the vMyx-FLuc-infected cells was imaged with the Xenogen IVIS 200 system. Data were analyzed by drawing a region of interest around the entire skull and measuring the total luminescent emission from that area. Statistical Analysis All data were processed and graphed in either MS Excel 2010 or Prism GraphPad v5.0. Statistics were also performed in these programs. All T-tests were two-sided and values were considered to be statistically significant at p,0.05. Survival curves were generated by the Kaplan-Meier method, and stats were determined using the Log-rank Mantel-Cox test for all treatments together unless otherwise noted. NPcis cell line infection with MYXV in vitro NPcis cell lines K1491, K1492, K1861 and K5001 were assayed for cell viability and viral replication after MYXV treatment in vitro. Despite these tumours being derived from the same genetic background and having the same TP53 and NF1 null driving mutations , we found a large variability in MYXV infection and replication ( Figure 1). K1492 and K1492 provided the most robust viral replication, producing high titres of 6.1610 7 and 1.8610 8 at 72 hour-post-infection (hpi). These lines were also the most sensitive to viral treatment, with 1 MOI resulting in 25% and 38% viability at 48 hpi, respectively. Conversely, K1861 was the most resistant to cell death with 74% viability at 1 MOI at 48 hpi, but was killed by the virus at higher MOIs (21% viability with 10MOI, 48 hpi). K5001 had intermediate sensitivity to viral mediated cell death. These more resistant cell lines markedly differed in their ability to replicate the virus, with K1861 and K5001 unable to reach the high titres seen in the other lines, but still able to produce functional virions following infection. NPcis lines orthotopically implanted in C57Bl/6 mice and treated with Myxoma virus To establish which lines we would utilize for in vivo studies, we implanted 5.0610 4 cells in the right striatum of C57Bl/6J mice. All mice succumbed to tumour burden, but varied in length of survival ( Figure S1). Only K1492 and K1861 reproducibly produced intracranial tumours, whilst K1491 and K5001 both tended to produce large extracranial tumour masses with or without a corresponding intracranial tumour. K1492 and K1861 orthotopically implanted in C57Bl/6J mice produced aggressive tumours (Figure 2A). Despite having protruding tendrils into the adjacent brain parenchyma, these tumours appear to have a defined tumour border and overall lacked the single cell infiltrate pattern that can appear in astrocytic tumours. Microscopically, these tumours were composed of spindle cells arranged in bundles with a focal storiform pattern. Immunohistochemistry shows patchy expression of GFAP and S100b protein in tumour cells ( Figure 2A), a feature seen in a some MG patients . The histologic features and immunohistochemical profile are consistent with a gliosarcoma, a glioblastoma variant that has a similar evolution and prognosis. It is easy to speculate that this morphological change to a more mesenchymal phenotype was acquired through culture of the primary cells in serum , since it has been shown that the sarcomatous component in glioblastoma represents an aberrant differentiation of the glioblastoma cells . As the main purpose of this study was to identify intracranial glioma models in immunocompetent C57Bl/6J mice for the pre-clinical modelling of OVs, we deemed K1492 and K1861 relevant for use in our subsequent experiments. K1492 and K1861 were treated with an intratumoral injection of 5610 6 PFU of an MYXV construct that expresses Firefly Figure S2A). There was no viral replication as measured by viral luciferase activity ( Figure 2D), with complete clearance of bioluminescent activity by 5 days post-treatment. These viral clearance kinetics closely mimicked viral recovery assays from the tumour ( Figure 2E). Interestingly, the viral FLUX measured in these models did not differ from non-tumour-bearing animals ( Figure 2D), and seemed to be a consequence of minor off-target infection of cells in the ventricles ( Figure S2B) as previously described with intraventricular MYXV administration . However, IHC staining for the early MYXV viral protein, M-T7, found that there was indeed a small proportion of the tumour infected at 1 day-post treatment, with very little evidence of viral protein at 7 days-post treatment ( Figure 2F). These results demonstrate that the input virus underwent only very transient infection of these tumours, without any sustained viral replication in the tumour beds, and no measurable therapeutic benefit. The role of Type-I Interferon in mediating MYXV treatment resistance We have previously shown that we can cure or significantly extended lifespan in CB17 SCID or Nude mice bearing human xenografts of conventional or primary neurosphere cell cultures . A preliminary experiment implanting K1492 into CB17 SCID mice showed no treatment efficacy ( Figure S2C), suggesting to us that species-specific innate immune signalling could be involved in this mechanism. Type-I interferon (IFNa/b) is the quintessential antiviral cytokine , and we hypothesized that the production of IFNa/b, particularly by the tumour stroma, was responsible for in vivo treatment resistance. We first determined if the NPcis cell lines were protected by mIFNb from MYXV viral infection in vitro, and found protection with as little as 1 U/mL of mIFNb ( Figure 3A, B). This demonstrated that mIFNa/b production from the tumour or stroma in syngeneic models had the potential to protect the tumour from viral infection. We confirmed that murine IFNa/b does not interact with the human IFNa/b receptors in gliomas using the human U87 cell line and murine K1492 cell line ( Figure 3C, S3A). This suggested to us that any IFNa/b made by the murine stroma in response to MYXV could protect the murine but not human glioma grafts, and explain the treatment discrepancy between xenografts and syngeneic models. We then determined if IFNa/b was produced in the NPcis lines in vitro by MYXV infection. However, MYXV infection did not induce the production of any functional IFNa/b in any of the lines ( Figure 4A). This is similar to our previous results with all the human cell lines we have tested, including primary glioma neurosphere and primary human fetal astrocyte cultures, which fail to show any detectable IFNa/b production, despite, for the most part, being able to make IFNa/b in response to other stimuli . To confirm these results we performed reverse-transcriptase PCR on lines K1492 and K1861 ( Figure 4B), and found that after 24-hours of exposure to MYXV both lines had no significant transcriptional activation of the IFNb and IFNa4 genes, while both VSVD51 or polyI:C, both strong activators of IFNa/b, showed robust IFN responses. The time point of 24 hpTx also allowed us to look at auto/paracrine IFNa/b signalling, and showed that only K1861 had transcriptional activation of interferon-stimulated genes IRF7, ISG15 and IP10. The activation of these genes in the absence of functional IFN production suggests that perhaps these are activated upon infection independent of type-I IFN production . Interestingly, this only occurred in the resistant K1861 cell line and, thus, could be part of the mechanism mediating this in vitro resistance. Given the lack of IFNa/b produced by the lines in response to MYXV infection in vitro, we next wanted to determine if stromal IFNa/b production might have occurred in vivo. We measured IFNa/b production in vivo by ELISA in MYXV-treated K1492bearing C57Bl/6 mice. We were surprised to find no significant increase in IFNa/b following treatment ( Figure 4C); this is particularly striking in comparison to the response to a small amount of naked polyI:C (5ug) administered intracranially. Together with our in vitro data, this suggests that virus-induced IFNa/b is not involved in the in vivo resistance mechanism. To show definitively that IFNa/b production by the tumour or the stroma was not involved in mediating the in vivo resistance to MYXV, we reduced K1492's ability to respond to IFNa/b by silencing IRF9 with a shRNA construct transduced via lentiviral infection. Knockdown of IRF9, as a central mediator of IFN signalling, would also attenuate any anti-viral crosstalk from Type-II and III IFN produced by the tumour or stroma, which could also possibly mediate this resistance. We successfully knockeddown IRF9 in K1492 ( Figure 5A), which resulted in a functional loss of transcriptional activity at interferon-response elements (ISRE) as measured by an ISRE::FLUC reporter ( Figure 5B, S3B). Importantly, this IRF9 knockdown resulted in a dramatic loss of the protection provided by the application of exogenous IFNb in vitro ( Figure 5C, S3C). To determine if ablating IFN signalling in vivo would overcome resistance to MYXV in vivo, we implanted the K1492 IRF9 knockdown or its scrambled control into C57Bl/6J mice. Importantly, we found that the knockdown persisted in vivo through immunohistochemistry for IRF9 ( Figure 6A, S4), and that the knockdown had similar tumour growth kinetics to the K1492 scrambled control. Treatment with vMyx-FLuc resulted in no change in survival (35 days for no treatment versus 30 days for MYXV treatment in Scram-K1492 (Log-rank Mantel-Cox test; p = 0.8279) and 35 days for no treatment versus 36 days for MYXV treatment in IRF9kd-K1492 (Log-rank Mantel-Cox test; p = 0.6406); Figure 6B), with no change in viral luciferase ( Figure 6C). These experiments, coupled to the observations of no significant IFNa/b production in vitro and in vivo, strongly suggest that the in vivo resistance to MYXV therapy in the intracranial environment of immunocompetent mice is independent of the quintessential anti-viral IFNa/b signalling. Discussion Our study uses a panel of primary, syngeneic mouse glioma cell lines to determine the mechanisms of glioma resistance to virotherapy with a candidate oncolytic virus in preclinical models. As we have previously shown in syngeneic rodent models , MYXV treatment demonstrates neither replication nor survival benefit in these orthotopically grafted murine gliomas in vivo, despite being sensitive to MYXV-mediated cell death and viral replication in vitro. This is in stark contrast to what we have found in xenograft models with traditional human glioma cell lines and with freshly cultured patient neurospheres , where we found robust viral replication and survival benefit from MYXV treatment when these cells are grown in immunodeficient mice. This resistance of syngeneic MG tumours to MYXV is also in contrast to the situation for other classes of cancer localized outside the brain, such as for disseminated pancreatic cancer in the peritoneal cavity, where MYXV virotherapy is most effective against syngeneic murine Pan02 tumours in C57/Bl6 mice, compared to the reduced efficacy against the same cells engrafted into the intraperitoneal cavity of immunodeficient mice . Thus, we have investigated this apparently brain-specific blockade to MYXV replication and anti-tumour responses within the intracranial environment of the immunocompetent host. The murine glioma lines we used in this manuscript are derived from spontaneous low-high grade gliomas that arose in Trp53 +/2 / Nf1 +/2 C57Bl/6J mice . As such, these lines fill an underrepresented niche in the experimental glioma therapeutics field that is of special interest to investigators interested in oncolytic viruses, immunotherapies, or in stromal contributions to treatment. In this model, tumourigenesis is initiated by loss-ofheterozygosity at the Trp53 and Nf1 loci, leading to the development of low-grade astrocytomas, which can progress to diffusely infiltrative high-grade gliomas . The relevance of the tumour suppressors Trp53 and Nf1 to glioma biology has been robustly validated in comprehensive genomic studies. Recent characterization of the mutational profiles of high-grade human gliomas by the Cancer Genome Atlas (TCGA) Research Network demonstrated that 23% of patient samples harboured somatic NF1 inactivating mutations or deletions, of which 64% represented NF1 heterozygous deletions . The relevance of NF1 to human highgrade gliomas was further validated when the TCGA identified NF1 as the defining mutation for the mesenchymal subtype of glioblastoma in a multi-dimensional genomic analysis . Mutation of the human p53 gene, TP53, is the most frequent genetic alteration in precursor low-grade astrocytomas (present in 60% of cases) and was also shown to be frequently mutated in both the mesenchymal subtype and classical subtype of glioblastoma . In addition to TP53 and NF1 mutations, prior in vitro characterization of the Trp53 +/2 /Nf1 +/2 C57Bl/6J-derived cell lines revealed concomitant over-expression of commonly amplified receptor tyrosine kinases, including EGFR and PDGFRa . The accumulation of aberrations in gene expression accurately recapitulates the clinical progression from low-to high-grade gliomas in patients, whereby loss of p53 function in low-grade astrocytomas precedes further genetic and gene expression changes that ultimately lead to progression and development of high-grade gliomas . We consider it very important to preclinically test OVs in cell lines that contain relevant genomic alterations, as these changes may ultimately determine the susceptibility to viral infection, viral replication, and viralmediated cell death. Secondly, these lines arose in C57Bl/6J mice, and thus are 'graftable' into the most common immunocompetent laboratory mouse strain. The power of using this strain of mouse is the numerous transgenic and knockout animals available, allowing for the interrogation and modelling of glioma-stromal interactions that can influence tumour-development and treatment response. Utilizing transgenic mice for the precise and complete ablation of specific aspects of the immune system or other aspects of the glioma microenviroment (ie, ECM components) allows for comprehensive studies that can interrogate exactly how these therapies work and can be improved. Discovering minimal MYXV infection in the tumour in situ with no sustained viral replication, although not surprising, is worrisome if we extrapolate this data for the clinical use of virotherapy of gliomas and other brain cancers. We have recently published a review article summarizing the clinical experience of OVs for glioma treatment . Of the currently completed trials only two , both with a neuroattenuated HSV, were designed to investigate viral infection and possible replication in the tumour. These results, with a combined total of 21 patients with their tumours resected or biopsied 2-9 days post-intratumoural virus inoculation, only found recovery of functional virus in three cases. Further, IHC staining for viral proteins was only found in 4 of the 21 patients. Both of these strains of HSV produced robust viral infection or replication and/or measurable efficacy in mouse subcutaneous or orthotopic xenografts . Interestingly, HSV-G207, as well as other unarmed HSV-strains, was found to provide measurable survival benefit in an orthotopic syngeneic B6D2F1 glioma model, albeit only when infecting small tumours early after implantation . Of note in that study was the in vivo viral clearance kinetics closely mimicked what occurs in our model, and, ultimately, what was seen in patients. Collectively, this suggests to us that syngeneic models more closely recapitulate the clinical experience with OV therapy for gliomas, and further understanding and optimization of these therapies should be robustly interrogated using these or similar syngeneic systems as we advance these treatments. There has been much development in the area of tumourstroma interactions dictating treatment resistance, with much recent interest in how hepatocyte growth factor (HGF) can mediate BRAF-inhibitor resistance in melanoma . Although growth factors are largely thought to be cross-reactive between mouse and human, many chemokines and cytokines have species-specific interactions, such as Type-I and Type-II interferons and members of the TNFa family . These interactions may be of great importance to therapeutic outcome, especially for immune-based therapies such as OVs, and thus models where these interactions are conserved should become part of the standard for preclinical testing. Of great importance here is the incompatibility of mouse Type-I interferon (IFNa/b) and the human IFNa/b receptor. Some would argue that in many cancer cells, compromised IFNa/b signalling occurs as a consequence of transformation . Indeed, this seems to be the case in some cell lines, but many gliomas, as seen in the NPcis cell lines, seem to retain their ability to both produce and respond to Type-I IFNa/b . This is one of the main reasons for the pursuit of IFNa/b's anti-proliferative and pro-apoptotic effect as a glioma therapeutic in the clinic , in addition to its immunomodulatory functions. Indeed, it could be suggested that if MYXV did mount a robust IFNa/b response in the glioma microenvironment, we may see some indirect therapeutic response in these syngeneic models. The lack of a MYXV-induced IFNa/b response in vivo in the mouse glioma microenvironment is an interesting observation, and strongly suggests that an IFNa/b response is not necessary to protect the tumour or the rest of the brain from MYXV infection. It has previously been shown that STAT1-deficient mice on the 129Sv/Ev background rapidly succumb to intracranial injections of MYXV , suggesting that IFNa/b signalling is important in protecting against MYXV neurovirulence in this strain of mouse. Perhaps this is a result of inherent differences between the 129Sv/ Ev and C57Bl/6J background of mouse, which have shown strainspecific effects in models of HSV viral encephalitis and experimental autoimmune encephalomyelitis . It would be interesting to look at MYXV neurovirulence in C57BL/6J mice deficient in IFNAR1 or IRF9, which would specifically ablate IFNa/b signalling in these animals. The mechanism of treatment resistance in the syngeneic NPcis glioma cell lines when implanted intracranially into C57Bl/6J mice are of great interest to our laboratory. It has not escaped our notice that these tumours are highly infiltrated with myeloidderived and lymphoid-derived cell types before and after intratumoural treatment. In our previous study looking at MYXV in syngeneic rat models , we demonstrated that the mTOR inhibitor rapamycin administrated prior to MYXV treatment resulted in increased tumour infection, viral replication and an overall better efficacy then either treatment alone. In that study we found that rapamycin was able to inhibit the MYXV-induced infiltration of CD68+ and CD163+ microglia/myeloid-derived cells. We are currently immunophenotying the glioma microenvironment and using knock-out C57Bl/6J mice to determine which, if any, of these immunocytes are necessary for inhibiting viral infection and replication within these tumours. It will be interesting to see if we lose combination effects with immunosuppressants, such as rapamycin, that have been used to enhance oncolytic viral therapy. These types of experiments will allow a thorough understanding of the mechanisms behind these combination effects, and perhaps lead to more targeted combinations. We believe that by identifying the anti-viral effectors and cell types responsible for resistance in these immunocompetent models, we will be able to modify the treatment regime to include chemotherapeutics or genetic alterations to MYXV that will specifically enhance the ability of oncolytic viruses to treat brain tumours in patients. Further, as MYXV moves closer to a clinical evaluation in MG patients, we will have an understanding of how to translate this knowledge back into patients receiving different therapeutic regimens to see if similar challenges will indeed be the case. Of concern about these models is the 'mesenchymal' drift that seems to have occurred in these cells lines, such that the grafted tumours appear more of a gliosarcoma then a truly infiltrative astrocytoma like the tumours from which they originated . This has been shown to be a phenomenon associated with primary gliomas cultured in serum . To address this concern for future studies, we are currently deriving cell lines from NPcis astrocytoma-bearing mice cultured under neurosphere conditions, which have been reported to better retain the original tumour's genetics and phenotypic appearance in vivo . These cells may prove to be an even more relevant model for the preclinical testing of glioma experimental therapeutics in an immunocompetent setting. Further, it would be interesting to look at other oncolytic viruses in this model to ascertain if similar limitations exist, and if resistances are independent of IFNa/b. Once mechanisms for treatment resistance are discovered, it will be important to determine if these mechanisms are conserved across all OVs used in glioma preclinical studies. In conclusion, the use of an immunocompetent syngeneic model of orthotopic murine glioma reveals that an intracranial injection of an oncolytic virus with prospects of clinical application, MYXV, is ineffective at reducing glioma growth. Further, this virus blockade appears to be specific for the brain, and the prominent anti-viral cytokine, IFNa/b, is not responsible for the neutralization of viral activity, suggesting that other mechanisms yet to be uncovered must be identified in order for this OV therapy to have better clinical utility. Figure S1 NPcis cell lines orthotopically implanted in C57Bl/6 mice succumb to tumour burden. 5610 4 cells of K1492, K1861, K1491 and K5001 implanted into the right straitum of C57Bl/6 mice. (TIF) Figure S2 A -5610 4 K1492 were implanted into the right striatum of C57Bl/6 mice, and treated with 1610 7 PFU of vMyx-GFP (MYXV) or UV-inactivated MYXV (DV) at 7 and 14 dayspost implantation. P-value represents result of a Log-rank Mantel-Cox test. B -K1492 implanted into C57Bl/6 mice and treated with 5610 6 PFU of vMyx-GFP (MYXV), and sacrificed at 1 and 7 days post-infection (dpi). Pictures represent two mice at each time point with the GFP channel alone (left) and the GFP+brightfield (right). Arrows indicate tumour location. C -5610 4 K1492 were implanted into the right striatum of C57Bl/6 or CB17-SCID mice and treated with 1610 7 PFU of vMyx-GFP (MYXV). (TIF) Figure S3 A -Specificity of mouse and human IFN using the HEK-Blue system (InvivoGen) which uses an interferon specific promoter upstream of SEAP to detect human IFN. This is the human counterpart of the B16-Blue described in the methods. Supporting Information Graph is quantitated picture where error bars represent standard deviation and asterisks p,0.05 between IFN treatment at control. B -Reprehensive picture of luminescence from K1492 wildtype (WT), scrambled shRNA (Scram) or IRF9 shRNA (IRF9kd) stably transfected with a ISRE::FLUC construct and treated with listed doses of IFNb for 8 hours.
/** * Details of the movement instructions. * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "MovementInstruction1", propOrder = { "mvmntGnlInf", "undrlygSctiesMvmntDtls", "undrlygCshMvmntDtls", "prcdsMvmntDtls" }) public class MovementInstruction1 { @XmlElement(name = "MvmntGnlInf", required = true) protected CorporateActionMovement1 mvmntGnlInf; @XmlElement(name = "UndrlygSctiesMvmntDtls") protected List<UnderlyingSecurityMovement1> undrlygSctiesMvmntDtls; @XmlElement(name = "UndrlygCshMvmntDtls") protected List<CashMovement2> undrlygCshMvmntDtls; @XmlElement(name = "PrcdsMvmntDtls") protected List<ProceedsMovement1> prcdsMvmntDtls; /** * Gets the value of the mvmntGnlInf property. * * @return * possible object is * {@link CorporateActionMovement1 } * */ public CorporateActionMovement1 getMvmntGnlInf() { return mvmntGnlInf; } /** * Sets the value of the mvmntGnlInf property. * * @param value * allowed object is * {@link CorporateActionMovement1 } * */ public MovementInstruction1 setMvmntGnlInf(CorporateActionMovement1 value) { this.mvmntGnlInf = value; return this; } /** * Gets the value of the undrlygSctiesMvmntDtls property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the undrlygSctiesMvmntDtls property. * * <p> * For example, to add a new item, do as follows: * <pre> * getUndrlygSctiesMvmntDtls().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link UnderlyingSecurityMovement1 } * * */ public List<UnderlyingSecurityMovement1> getUndrlygSctiesMvmntDtls() { if (undrlygSctiesMvmntDtls == null) { undrlygSctiesMvmntDtls = new ArrayList<UnderlyingSecurityMovement1>(); } return this.undrlygSctiesMvmntDtls; } /** * Gets the value of the undrlygCshMvmntDtls property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the undrlygCshMvmntDtls property. * * <p> * For example, to add a new item, do as follows: * <pre> * getUndrlygCshMvmntDtls().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link CashMovement2 } * * */ public List<CashMovement2> getUndrlygCshMvmntDtls() { if (undrlygCshMvmntDtls == null) { undrlygCshMvmntDtls = new ArrayList<CashMovement2>(); } return this.undrlygCshMvmntDtls; } /** * Gets the value of the prcdsMvmntDtls property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the prcdsMvmntDtls property. * * <p> * For example, to add a new item, do as follows: * <pre> * getPrcdsMvmntDtls().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ProceedsMovement1 } * * */ public List<ProceedsMovement1> getPrcdsMvmntDtls() { if (prcdsMvmntDtls == null) { prcdsMvmntDtls = new ArrayList<ProceedsMovement1>(); } return this.prcdsMvmntDtls; } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); } @Override public boolean equals(Object that) { return EqualsBuilder.reflectionEquals(this, that); } @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } /** * Adds a new item to the undrlygSctiesMvmntDtls list. * @see #getUndrlygSctiesMvmntDtls() * */ public MovementInstruction1 addUndrlygSctiesMvmntDtls(UnderlyingSecurityMovement1 undrlygSctiesMvmntDtls) { getUndrlygSctiesMvmntDtls().add(undrlygSctiesMvmntDtls); return this; } /** * Adds a new item to the undrlygCshMvmntDtls list. * @see #getUndrlygCshMvmntDtls() * */ public MovementInstruction1 addUndrlygCshMvmntDtls(CashMovement2 undrlygCshMvmntDtls) { getUndrlygCshMvmntDtls().add(undrlygCshMvmntDtls); return this; } /** * Adds a new item to the prcdsMvmntDtls list. * @see #getPrcdsMvmntDtls() * */ public MovementInstruction1 addPrcdsMvmntDtls(ProceedsMovement1 prcdsMvmntDtls) { getPrcdsMvmntDtls().add(prcdsMvmntDtls); return this; } }
<gh_stars>10-100 /** * Copyright (C) 2016 <NAME> (<EMAIL>) * * 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.brunocvcunha.ghostme4j; import static org.junit.Assert.*; import org.brunocvcunha.ghostme4j.helper.GhostMeHelper; import org.brunocvcunha.ghostme4j.model.Proxy; import org.brunocvcunha.ghostme4j.model.ProxyBinResponse; import org.junit.Test; /** * Proxy Me Test * * @author <NAME> * */ public class ProxyMeTest { /** * Test Proxy Application * * @throws Exception */ @Test public void testProxySystem() throws Exception { Proxy used = GhostMe.ghostMySystemProperties(true); ProxyBinResponse response = GhostMeHelper.getMyInformation(); assertEquals(used.getIp().trim(), response.getOrigin().trim()); assertEquals(used.getIp().trim(), response.getHeaders().get("X-Forwarded-For")); assertEquals(used.getIp().trim(), response.getHeaders().get("X-Real-Ip")); } /** * Test Proxy in Connection * * @throws Exception */ @Test public void testProxyConnection() throws Exception { Proxy used = GhostMe.getProxy(true); ProxyBinResponse response = GhostMeHelper.getMyInformation(used.getJavaNetProxy()); assertEquals(used.getIp().trim(), response.getOrigin().trim()); assertEquals(used.getIp().trim(), response.getHeaders().get("X-Forwarded-For")); assertEquals(used.getIp().trim(), response.getHeaders().get("X-Real-Ip")); } /** * Test function to get random user agents */ @Test public void testUserAgent() { String agent = GhostMe.getRandomUserAgent(); System.out.println("Agent is: " + agent); assertNotNull(agent); assertTrue(agent.contains("Mozilla/5.0")); } }
#include "minunit.h" #include <list.h> #include <assert.h> static List *list = NULL; char *test1 = "test1 data"; char *test2 = "test2 data"; char *test3 = "test3 data"; char *test_create() { list = List_create(); mu_assert(list != NULL, "Failed to create list."); return NULL; } char *test_destroy() { List_clear_destroy(list); return NULL; } char *test_push_pop() { List_push(list, test1); mu_assert(List_last(list) == test1, "Wrong last value."); List_push(list, test2); mu_assert(List_last(list) == test2, "Wrong last value"); List_push(list, test3); mu_assert(List_last(list) == test3, "Wrong last value."); mu_assert(List_count(list) == 3, "Wrong count on push."); char *val = List_pop(list); mu_assert(val == test3, "Wrong value on pop."); val = List_pop(list); mu_assert(val == test2, "Wrong value on pop."); val = List_pop(list); mu_assert(val == test1, "Wrong value on pop."); mu_assert(List_count(list) == 0, "Wrong count after pop."); return NULL; } char *all_tests() { mu_suite_start(); mu_run_test(test_create); mu_run_test(test_push_pop); mu_run_test(test_destroy); return NULL; } RUN_TESTS(all_tests);
/* Copyright ⓒ 2015 grabbag contributors. Licensed under the MIT license (see LICENSE or <http://opensource.org /licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of <http://www.apache.org/licenses/LICENSE-2.0>), at your option. All files in the project carrying such notice may not be copied, modified, or distributed except according to those terms. */ /** ( <em>a</em><sub>0</sub>, <em>a</em><sub>1</sub>, ... ), ( <em>b</em><sub>0</sub>, <em>b</em><sub>1</sub>, ... ) &nbsp;&rarr;&nbsp; ( (<em>a</em><sub>0</sub>, <em>b</em><sub>0</sub>), (<em>a</em><sub>0</sub>, <em>b</em><sub>1</sub>), ..., (<em>a</em><sub>1</sub>, <em>b</em><sub>0</sub>), (<em>a</em><sub>1</sub>, <em>b</em><sub>1</sub>), ... ) */ pub trait CartesianProductIterator<LeftItem>: Iterator<Item=LeftItem> + Sized { /** Creates an iterator that yields the cartesian product of two input iterators. The element type of the first input iterator must implement Clone, as must the second iterator type. */ fn cartesian_product<RightIt, RightItem>(self, right: RightIt) -> CartesianProduct<Self, RightIt, LeftItem, RightItem> where RightIt: Clone + Iterator<Item=RightItem> { CartesianProduct { left: self, right: right.clone(), right_checkpoint: right, left_value: None, } } } impl<LeftIt, LeftItem> CartesianProductIterator<LeftItem> for LeftIt where LeftIt: Iterator<Item=LeftItem>, LeftItem: Clone {} #[derive(Clone, Debug)] #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] pub struct CartesianProduct<LeftIt, RightIt, LeftItem, RightItem> where LeftIt: Iterator<Item=LeftItem>, RightIt: Iterator<Item=RightItem> { left: LeftIt, right: RightIt, right_checkpoint: RightIt, left_value: Option<LeftItem>, } impl<LeftIt, RightIt, LeftItem, RightItem> Iterator for CartesianProduct<LeftIt, RightIt, LeftItem, RightItem> where LeftIt: Iterator<Item=LeftItem>, RightIt: Clone + Iterator<Item=RightItem>, LeftItem: Clone { type Item = (LeftItem, RightItem); fn next(&mut self) -> Option<(LeftItem, RightItem)> { loop { if let Some(e0) = self.left_value.clone() { match self.right.next() { Some(e1) => return Some((e0, e1)), None => { self.left_value = None; self.right = self.right_checkpoint.clone(); } } } match self.left.next() { Some(e0) => { self.left_value = Some(e0); } None => return None } } } fn size_hint(&self) -> (usize, Option<usize>) { let (l0, mu0) = self.left.size_hint(); let (l1, mu1) = self.right.size_hint(); let (lc, muc) = self.right_checkpoint.size_hint(); let combine_bounds: fn(usize, usize, usize) -> usize; if self.left_value.is_some() { combine_bounds = combine_bounds_with_partial; } else { combine_bounds = combine_bounds_without_partial; } let l = combine_bounds(l1, l0, lc); let mu = match (mu0, mu1, muc) { (None, _, _) | (_, None, _) | (_, _, None) => None, (Some(u0), Some(u1), Some(uc)) => Some(combine_bounds(u1, u0, uc)) }; (l, mu) } } fn combine_bounds_with_partial(b0: usize, b1: usize, bc: usize) -> usize { b1 + b0*bc } fn combine_bounds_without_partial(b0: usize, _: usize, bc: usize) -> usize { b0*bc } #[test] fn test_cartesian_product() { use super::CloneEachIterator; let a = vec![0usize, 1, 2]; let b = vec![3usize, 4]; let r: Vec<_> = a.into_iter().cartesian_product(b.iter().clone_each()).collect(); assert_eq!(r, vec![(0,3),(0,4),(1,3),(1,4),(2,3),(2,4)]); }
<gh_stars>0 # # Copyright 2018 the original author or authors. # # 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. # from voltha.extensions.omci.tasks.task import Task from twisted.internet import reactor from twisted.internet.defer import inlineCallbacks, failure, returnValue from voltha.extensions.omci.omci_defs import ReasonCodes, EntityOperations from voltha.extensions.omci.omci_me import PptpEthernetUniFrame RC = ReasonCodes OP = EntityOperations class BrcmUniLockException(Exception): pass class BrcmUniLockTask(Task): """ Lock or unlock all discovered UNI/PPTP on the ONU """ task_priority = 200 name = "Broadcom UNI Lock Task" def __init__(self, omci_agent, device_id, lock=True, priority=task_priority): """ Class initialization :param omci_agent: (OmciAdapterAgent) OMCI Adapter agent :param device_id: (str) ONU Device ID :param lock: (bool) If true administratively lock all the UNI. If false unlock :param priority: (int) OpenOMCI Task priority (0..255) 255 is the highest """ super(BrcmUniLockTask, self).__init__(BrcmUniLockTask.name, omci_agent, device_id, priority=priority, exclusive=False) self._device = omci_agent.get_device(device_id) self._lock = lock self._results = None self._local_deferred = None self._config = self._device.configuration def cancel_deferred(self): super(BrcmUniLockTask, self).cancel_deferred() d, self._local_deferred = self._local_deferred, None try: if d is not None and not d.called: d.cancel() except: pass def stop_if_not_running(self): if not self.running: raise BrcmUniLockException('UNI Lock Task was cancelled') def start(self): """ Start UNI/PPTP Lock/Unlock Task """ super(BrcmUniLockTask, self).start() self._local_deferred = reactor.callLater(0, self.perform_lock) @inlineCallbacks def perform_lock(self): """ Perform the lock/unlock """ self.log.info('setting-uni-lock-state', lock=self._lock) try: state = 1 if self._lock else 0 pptp = self._config.pptp_entities for key, value in pptp.iteritems(): msg = PptpEthernetUniFrame(key, attributes=dict(administrative_state=state)) frame = msg.set() self.log.debug('openomci-msg', msg=msg) results = yield self._device.omci_cc.send(frame) self.stop_if_not_running() status = results.fields['omci_message'].fields['success_code'] self.log.info('response-status', status=status) # Success? if status in (RC.Success.value, RC.InstanceExists): self.log.debug('set-lock-uni', uni=key, value=value, lock=self._lock) else: self.log.warn('cannot-set-lock-uni', uni=key, value=value, lock=self._lock) self.deferred.callback(self) except Exception as e: self.log.exception('setting-uni-lock-state', e=e) self.deferred.errback(failure.Failure(e))
class BlacklistEntry: """Defines a import blacklist entry.""" def __init__(self, alternative, modules_only=False, names=None, ignore_paths=None): """ :type alternative: str :type modules_only: bool :type names: tuple[str] | None :type ignore_paths: tuple[str] | None """ self.alternative = alternative self.modules_only = modules_only self.names = set(names) if names else None self.ignore_paths = ignore_paths def applies_to(self, path, name=None): """ :type path: str :type name: str | None :rtype: bool """ if self.names: if not name: return False if name not in self.names: return False if self.ignore_paths and any(path.endswith(ignore_path) for ignore_path in self.ignore_paths): return False if self.modules_only: return is_module_path(path) return True
/** * Indents the next text. * @throws IOException I/O exception */ final void indent() throws IOException { if(!indent) return; if(item) { item = false; } else { if(!suppress.isEmpty() && !tags.isEmpty()) { for(final byte[] s : suppress) { if(tags.contains(s)) return; } } print(nl); final int ls = level * indents; for(int l = 0; l < ls; ++l) print(tab); } }
package gfu import ( "bufio" "fmt" "io" //"log" ) type Writer bufio.Writer type WriterType struct { BasicType } func NewWriter(in io.Writer) *Writer { return (*Writer)(bufio.NewWriter(in)) } func (_ *Writer) Type(g *G) Type { return &g.WriterType } func (_ *WriterType) Dump(g *G, val Val, out *bufio.Writer) E { fmt.Fprintf(out, "writer-%v", (*bufio.Writer)(val.(*Writer))) return nil }
<reponame>GoldenHammerSoftware/GH // Copyright <NAME> #pragma once #include "GHBulletBtInclude.h" class GHBulletBroadphaseFilter : public btOverlapFilterCallback { public: virtual bool needBroadphaseCollision(btBroadphaseProxy* proxy0, btBroadphaseProxy* proxy1) const; };
<filename>packages/client-web/src/Container/LoginModal/index.tsx import React from 'react' import {Modal} from 'antd' import {Tabs} from 'antd' // import { Modal, Button, message } from 'antd' // import { throttle } from 'Utils/functions' import LoginSection from './LoginSection' import RegisterSection from './RegisterSection' import {config} from './config' import AccountStore from 'Store/account' import styles from './index.module.scss' import { observer } from 'mobx-react' interface Props { onCancel: () => void visiable: boolean onConfirm: (username: string, description: string) => Promise<void> account: AccountStore } @observer class LoginModal extends React.Component<Props> { handleLogin = async (email: string, password: string) => { const res = await this.props.account.login(email,password) console.log('registerRes', res) if (res.success) { this.props.onCancel() } } handleRegister = async (email: string, username: string, password: string) => { const res = await this.props.account.register(email,username, password) console.log('loginRes',res) if (res.success) { this.props.onCancel() } } render() { const { visiable, onCancel } = this.props return ( <Modal title={null} footer={null} visible={visiable} onCancel={onCancel} closable={true} className={styles.registerModal} style={{ width: '420px', marginTop: '100px' }} > <Tabs className={styles.tab} tabPosition="top"> <Tabs.TabPane tab={<span className={styles.tabsTab}>{config.loginTabName}</span>} key="1"> <LoginSection onLogin={this.handleLogin} /> </Tabs.TabPane> <Tabs.TabPane tab={<span className={styles.tabsTab}>{config.registerTabName}</span>} key="2"> <RegisterSection onRegister={this.handleRegister}/> </Tabs.TabPane> </Tabs> </Modal> ) } } export default LoginModal
/** * Mutate the constant nodes of an Encog program. This mutation only changes * values and does not alter the structure. */ public class ConstMutation implements EvolutionaryOperator { /** * The frequency that constant nodes are mutated with. */ private final double frequency; /** * The sigma value used to generate gaussian random numbers. */ private final double sigma; /** * Construct a const mutator. * * @param theContext * The program context. * @param theFrequency * The frequency of mutation. * @param theSigma * The sigma to use for mutation. */ public ConstMutation(final EncogProgramContext theContext, final double theFrequency, final double theSigma) { this.frequency = theFrequency; this.sigma = theSigma; } /** * {@inheritDoc} */ @Override public void init(final EvolutionaryAlgorithm theOwner) { // TODO Auto-generated method stub } /** * Called for each node in the progrmam. If this is a const node, then * mutate it according to the frequency and sigma specified. * * @param rnd Random number generator. * @param node The node to mutate. */ private void mutateNode(final Random rnd, final ProgramNode node) { if (node.getTemplate() == StandardExtensions.EXTENSION_CONST_SUPPORT) { if (rnd.nextDouble() < this.frequency) { final ExpressionValue v = node.getData()[0]; if (v.isFloat()) { final double adj = rnd.nextGaussian() * this.sigma; node.getData()[0] = new ExpressionValue(v.toFloatValue() + adj); } } } for (final TreeNode n : node.getChildNodes()) { final ProgramNode childNode = (ProgramNode) n; mutateNode(rnd, childNode); } } /** * {@inheritDoc} */ @Override public int offspringProduced() { return 1; } /** * {@inheritDoc} */ @Override public int parentsNeeded() { return 1; } /** * {@inheritDoc} */ @Override public void performOperation(final Random rnd, final Genome[] parents, final int parentIndex, final Genome[] offspring, final int offspringIndex) { final EncogProgram program = (EncogProgram) parents[0]; final EncogProgramContext context = program.getContext(); final EncogProgram result = context.cloneProgram(program); mutateNode(rnd, result.getRootNode()); offspring[0] = result; } }
class MEPSystemClassification(Enum,IComparable,IFormattable,IConvertible): """ This enumeration is used to classify MEP connectors and systems and drives certain behavior for a particular system type enum MEPSystemClassification,values: CableTrayConduit (32),Communication (14),CondensateDrain (15),Controls (13),DataCircuit (5),DomesticColdWater (20),DomesticHotWater (19),ExhaustAir (3),FireAlarm (11),FireProtectDry (24),FireProtectOther (26),FireProtectPreaction (25),FireProtectWet (23),Fitting (28),Global (29),NurseCall (12),OtherAir (4),OtherPipe (22),PowerBalanced (30),PowerCircuit (6),PowerUnBalanced (31),Recirculation (21),ReturnAir (2),ReturnHydronic (8),Sanitary (16),Security (10),Storm (18),SupplyAir (1),SupplyHydronic (7),SwitchTopology (27),Telephone (9),UndefinedSystemClassification (0),Vent (17) """ def __eq__(self,*args): """ x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx.__eq__(y) <==> x==y """ pass def __format__(self,*args): """ __format__(formattable: IFormattable,format: str) -> str """ pass def __ge__(self,*args): pass def __gt__(self,*args): pass def __init__(self,*args): """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass def __le__(self,*args): pass def __lt__(self,*args): pass def __ne__(self,*args): pass def __reduce_ex__(self,*args): pass def __str__(self,*args): pass CableTrayConduit=None Communication=None CondensateDrain=None Controls=None DataCircuit=None DomesticColdWater=None DomesticHotWater=None ExhaustAir=None FireAlarm=None FireProtectDry=None FireProtectOther=None FireProtectPreaction=None FireProtectWet=None Fitting=None Global=None NurseCall=None OtherAir=None OtherPipe=None PowerBalanced=None PowerCircuit=None PowerUnBalanced=None Recirculation=None ReturnAir=None ReturnHydronic=None Sanitary=None Security=None Storm=None SupplyAir=None SupplyHydronic=None SwitchTopology=None Telephone=None UndefinedSystemClassification=None value__=None Vent=None
EVIDENCE FOR GENTLY SLOPING PLASMA DENSITY PROFILES IN THE DEEP CORONA: TYPE III OBSERVATIONS Type III radio bursts are produced near the local electron plasma frequency fp and near its harmonic 2fp by fast electrons ejected from the solar active regions and moving through the corona and solar wind. The coronal bursts have dynamic spectra with frequency rapidly falling with time, the typical duration being about 1–3 s. In the present paper, 37 well-defined coronal type III radio bursts (25–450 MHz) are analyzed. The results obtained substantiate an earlier statement that the dependence of the central frequency of the emission on time can be fitted to a power-law model, f(t) ∝ (t − t0)−α, where α can be as low as 1. In the case of negligible plasma acceleration and conical flow, it means that the electron number density within about 1 solar radius above the photosphere will decrease as r−2, like in the solar wind. For the data set chosen, the index α varies in the range from 0.2 to 7 or bigger, with mean and median values of 1.2 and 0.5, respectively. A surprisingly large fraction of events, 84%, have α ⩽ 1.2. These results provide strong evidence that in the type III source regions the electron number density scales as n(r) ∝ (r − r0)−β, with minimum, mean, and median β = 2α of 0.4, 2.4, and 1.0, respectively. Hence, the typical density profiles are more gently sloping than those given by existing empirical coronal models. Several events are found with a wind-like dependence of burst frequency on time. Smaller power-law indices could result from the effects of non-conical geometry of the plasma flow tubes, deceleration of coronal plasma, and/or the curvature of the magnetic field lines. The last effect is shown to be too weak to explain such low power-law indices. A strong tendency is found for bursts from the same group to have similar power-law indices, thereby favoring the hypothesis that they are usually produced by the same source region.
A quantitative review of European stenonoid horses The taxonomy of the European stenonoid horses is revised using multivariate statistical techniques in this paper. The objectives are: to identify the taxonomic status of this group; to revise the specific and subspecific diagnoses, and the valid taxa; and to analyze their paleoecology and evolution. We conclude that: 1) there are six species among the Plio-Pleistocene European stenonoids: Equus major Depéret, in Delafond and Depéret 1893, ex Boule; Equus livenzovensis Bajgusheva, 1978; Equus stenonis Cocchi, 1867; Equus senezensis Prat, 1964; Equus altidens von Reichenau, 1915; and Equus sussenbornensis Wüts, 1901; 2) There are seven subspecies, three of E. stenonis, two of E. senezensis, and two of E. altidens; 3) There are two monophyletic groups according to the “neighbor-joining method,” one composed of the middle-to-small-size species, and the other of the biggest ones; 4) There is a trend toward decreasing body size through time in stenonoid horses. This trend, that follows the inverse direction of Cope's rule, can be related to the climatic-environmental changes that occurred from the middle Villafranchian to the early Galerian; 5) Large stenonoids were recorded in the middle Villafranchian and were associated with open and dry habitats (steppes), whereas the small ones lived in more closed and wet habitats (savanna-mosaic, woodlands) from late Villafranchian to earliest Galerian.
/** * Refreshes all <code>FileObject</code> that represent files <code>File.listRoots()</code> * and their children recursively. * @since 7.7 */ public static void refreshAll() { final RequestProcessor.Task taskToWaitFor; synchronized (REFRESH_RP) { if (refreshTask != null) { refreshTask.cancel(); } else { refreshTask = REFRESH_RP.create(new Runnable() { public void run() { LOG.fine("refreshAll - started"); refreshFor(File.listRoots()); try { getConfigRoot().getFileSystem().refresh(true); } catch (FileStateInvalidException ex) { Exceptions.printStackTrace(ex); } finally { LOG.fine("refreshAll - finished"); synchronized (REFRESH_RP) { refreshTask = null; } } } }); } taskToWaitFor = refreshTask; refreshTask.schedule(0); LOG.fine("refreshAll - scheduled"); } taskToWaitFor.waitFinished(); LOG.fine("refreshAll - finished"); }
import { jsx } from '../../../../src'; import { Polar, Rect } from '../../../../src/coord'; import { Canvas, Chart } from '../../../../src'; import { Interval, Axis, Legend, Tooltip } from '../../../../src/components'; import { createContext, delay } from '../../../util'; const data = [ { type: 'a', genre: 'Sports', sold: 5 }, { type: 'a', genre: 'Strategy', sold: 10 }, { type: 'a', genre: 'Action', sold: 20 }, { type: 'a', genre: 'Shooter', sold: 20 }, { type: 'a', genre: 'Other', sold: 40 }, { type: 'b', genre: 'Sports', sold: 5 }, { type: 'b', genre: 'Strategy', sold: 10 }, { type: 'b', genre: 'Action', sold: 20 }, { type: 'b', genre: 'Shooter', sold: 20 }, { type: 'b', genre: 'Other', sold: 40 }, ]; describe('条形图', () => { it('基础条形图', async () => { const chartRef = { current: null }; const context = createContext('基础条形图'); const { type, props } = ( <Canvas context={context} pixelRatio={1}> <Chart ref={chartRef} data={data} coord={{ transposed: true }}> <Interval x="genre" y="sold" color="type" /> </Chart> </Canvas> ); const canvas = new Canvas(props); canvas.render(); await delay(1000); expect(context).toMatchImageSnapshot(); }); it('基础条形图-转置+设置固定size', async () => { const chartRef = { current: null }; const context = createContext('基础条形图'); const { type, props } = ( <Canvas context={context} pixelRatio={1}> <Chart ref={chartRef} data={data} coord={{ transposed: true }}> <Interval x="genre" y="sold" color="type" /> </Chart> </Canvas> ); const canvas = new Canvas(props); canvas.render(); await delay(1000); expect(context).toMatchImageSnapshot(); }); it('分组条形图', async () => { const chartRef = { current: null }; const context = createContext('分组条形图'); const { type, props } = ( <Canvas context={context} pixelRatio={1}> <Chart ref={chartRef} data={data} coord={{ transposed: true }}> <Interval x="genre" y="sold" color="type" adjust="dodge" /> </Chart> </Canvas> ); const canvas = new Canvas(props); canvas.render(); await delay(1000); expect(context).toMatchImageSnapshot(); }); it('堆叠条形图', async () => { const chartRef = { current: null }; const context = createContext('堆叠条形图'); const { type, props } = ( <Canvas context={context} pixelRatio={1}> <Chart ref={chartRef} data={data} coord={{ transposed: true }}> <Interval x="genre" y="sold" color="type" adjust="stack" /> </Chart> </Canvas> ); const canvas = new Canvas(props); canvas.render(); await delay(1000); expect(context).toMatchImageSnapshot(); }); });
<gh_stars>1-10 package htpasswd import ( "bufio" "fmt" "io" "sort" "strings" // Namespace imports . "github.com/djthorpe/go-errors" ) /////////////////////////////////////////////////////////////////////////////// // TYPES type Htgroups struct { groups map[string][]string users map[string][]string } /////////////////////////////////////////////////////////////////////////////// // GLOBALS const ( groupSeparator = ":" GroupPrefix = "@" ) /////////////////////////////////////////////////////////////////////////////// // LIFECYCLE func NewGroups() *Htgroups { this := new(Htgroups) this.groups = make(map[string][]string) this.users = make(map[string][]string) return this } func ReadGroups(r io.Reader) (*Htgroups, error) { this := NewGroups() // Scan the file scanner := bufio.NewScanner(r) for scanner.Scan() { if line := strings.TrimSpace(scanner.Text()); line == "" { continue } else if strings.HasPrefix(line, "#") { continue } else if group := strings.SplitN(line, groupSeparator, 2); len(group) != 2 { continue } else if !rePOSIXName.MatchString(group[0]) { return nil, ErrBadParameter.With("group", group[0]) } else { users := strings.FieldsFunc(group[1], func(r rune) bool { return r == ',' || r == ' ' || r == ':' }) for _, user := range users { if rePOSIXName.MatchString(user) { this.groups[group[0]] = append(this.groups[group[0]], user) this.users[user] = append(this.users[user], group[0]) } } } } // Return any errors if err := scanner.Err(); err != nil { return nil, err } // Return success return this, nil } /////////////////////////////////////////////////////////////////////////////// // STRINGIFY func (this *Htgroups) String() string { str := "<htgroups" for group, users := range this.groups { str += fmt.Sprintf(" %s%v=%q", GroupPrefix, group, users) } return str + ">" } /////////////////////////////////////////////////////////////////////////////// // PUBLIC METHODS // Return all groups func (this *Htgroups) Groups() []string { result := make([]string, 0, len(this.groups)) for group := range this.groups { result = append(result, group) } sort.Strings(result) return result } // Return groups for a user func (this *Htgroups) GroupsForUser(user string) []string { groups, ok := this.users[user] if !ok { return nil } else { return groups } } // Return users for a group func (this *Htgroups) UsersForGroup(group string) []string { users, ok := this.groups[group] if !ok { return nil } sort.Strings(users) return users } // Return true if a user is a member of a group func (this *Htgroups) UserInGroup(user, group string) bool { groups, ok := this.users[user] if !ok { return false } for _, g := range groups { if g == group { return true } } // Not found in groups return false } // Add user to a group func (this *Htgroups) AddUserToGroup(user, group string) error { // Return if user already in group if this.UserInGroup(user, group) { return nil } // Check user and group names if !rePOSIXName.MatchString(group) { return ErrBadParameter.Withf("group %q", group) } if !rePOSIXName.MatchString(user) { return ErrBadParameter.Withf("user %q", user) } // Append user to group and group to user and sort this.groups[group] = append(this.groups[group], user) this.users[user] = append(this.users[user], group) // Return success return nil } // Remove user from a group func (this *Htgroups) RemoveUserFromGroup(user, group string) error { // Return if user not in group if !this.UserInGroup(user, group) { return nil } // Check user and group names if !rePOSIXName.MatchString(group) { return ErrBadParameter.Withf("group %q", group) } if !rePOSIXName.MatchString(user) { return ErrBadParameter.Withf("user %q", user) } // Remove user from group, etc this.groups[group] = removeString(this.groups[group], user) this.users[user] = removeString(this.users[user], group) // Remove user or group if empty if len(this.groups[group]) == 0 { delete(this.groups, group) } if len(this.users[user]) == 0 { delete(this.users, user) } // Return success return nil } // Write out group file func (this *Htgroups) Write(w io.Writer) error { for group, users := range this.groups { if _, err := fmt.Fprintln(w, group+groupSeparator+strings.Join(users, " ")); err != nil { return err } } return nil } /////////////////////////////////////////////////////////////////////////////// // PRIVATE METHODS func removeString(arr []string, elem string) []string { for i, v := range arr { if v == elem { return append(arr[:i], arr[i+1:]...) } } return arr }
/** * Default correlation manager implementation works on simple in memory map for storing objects. * Correlation key is the map key. Clients can access objects in the store using the correlation key. * * @author Christoph Deppisch * @since 2.0 */ public class DefaultCorrelationManager<T> implements CorrelationManager<T> { /** Logger */ private static Logger log = LoggerFactory.getLogger(DefaultCorrelationManager.class); /** Map of managed objects */ private ObjectStore<T> objectStore = new DefaultObjectStore<T>(); @Override public void saveCorrelationKey(String correlationKeyName, String correlationKey, TestContext context) { if (log.isDebugEnabled()) { log.debug(String.format("Saving correlation key for '%s'", correlationKeyName)); } context.setVariable(correlationKeyName, correlationKey); } @Override public String getCorrelationKey(String correlationKeyName, TestContext context) { if (log.isDebugEnabled()) { log.debug(String.format("Get correlation key for '%s'", correlationKeyName)); } if (context.getVariables().containsKey(correlationKeyName)) { return context.getVariable(correlationKeyName); } throw new CitrusRuntimeException(String.format("Failed to get correlation key for '%s'", correlationKeyName)); } @Override public void store(String correlationKey, T object) { if (object == null) { log.warn(String.format("Ignore correlated null object for '%s'", correlationKey)); return; } if (log.isDebugEnabled()) { log.debug(String.format("Saving correlated object for '%s'", correlationKey)); } objectStore.add(correlationKey, object); } @Override public T find(String correlationKey, long timeout) { if (log.isDebugEnabled()) { log.debug(String.format("Finding correlated object for '%s'", correlationKey)); } return objectStore.remove(correlationKey); } @Override public void setObjectStore(ObjectStore<T> store) { this.objectStore = store; } @Override public ObjectStore<T> getObjectStore() { return this.objectStore; } }
<gh_stars>1-10 import React from 'react'; import {tSwitchTarget_app} from './index' import ListItemInSwitch from './commons/listItemInSwitch'; import ListItemInTextField from './commons/listItemInTextField'; import Box from '@material-ui/core/Box'; import Paper from '@material-ui/core/Paper'; import List from '@material-ui/core/List'; import Typography from '@material-ui/core/Typography'; import { makeStyles, createStyles, Theme} from '@material-ui/core/styles'; const useStyle = makeStyles((theme:Theme) => createStyles({ rootBox: { width:"100%", display:"flex", [theme.breakpoints.up("lg")] : { flexWrap: "wrap" }, [theme.breakpoints.down("md")] : { flexDirection:"column", } }, paper: { flex: "auto", [theme.breakpoints.down("md")]: { width: "100%" } }, list:{ marginBottom:theme.spacing(2), [theme.breakpoints.down("xs")]: { width:"100%" }, [theme.breakpoints.up("sm")]: { minWidth:"380px" } } })) type tAppTabPanel = { isDisplay:boolean, status:{ isUseDark: boolean, isUseSmallTable: boolean, isDispTableWideScroll: boolean, isDispCheckBoxMaterialTable: boolean, isDispCreationEverytime: boolean, suggestMax: number, isDefDispSummary: boolean, isDefDispCostSheet: boolean, isDefDispCreationTree: boolean, } handler:{ suggestMax: (event: React.ChangeEvent<HTMLInputElement>) => void, switch: (target:tSwitchTarget_app, terminus?:boolean) => void, } } const AppTabPanel:React.FC<tAppTabPanel> = (props) => { const classes = useStyle(); if(! props.isDisplay) return null; return ( <Box className={classes.rootBox} > <Paper className={classes.paper}> <List className={classes.list} dense subheader={<Typography variant="subtitle1">表示設定全般</Typography>} > <ListItemInSwitch helpText={<Typography variant="body2">アプリ全体の色設定を黒背景に変更します。</Typography>} isChecked={props.status.isUseDark} onClick={props.handler.switch.bind(null,"useDark",undefined)} > ダークモード使用 </ListItemInSwitch> <ListItemInSwitch helpText={ <> <Typography variant="body2">表の余白を狭くすることにより、画面内の情報密度を上げます。</Typography> <Typography variant="body2">スマホなどを使用中の場合、表の中をタップしづらくなる可能性があります。</Typography> </> } isChecked={props.status.isUseSmallTable} onClick={props.handler.switch.bind(null,"useSmallTable",undefined)} > 緻密表の使用 </ListItemInSwitch> <ListItemInSwitch helpText={ <> <Typography variant="body2">3列以上の幅の広い表を画面に表示できないとき、横スクロールを可能にしてパソコンレイアウトで表示します。</Typography> </> } isChecked={props.status.isDispTableWideScroll} onClick={props.handler.switch.bind(null,"dispTableWideScroll",undefined)} > 表の横スクロール表示 </ListItemInSwitch> <ListItemInSwitch helpText={ <> <Typography variant="body2">材料表にチェックボックスを追加します。準備済みかどうかの判別に使うことができます。</Typography> </> } isChecked={props.status.isDispCheckBoxMaterialTable} onClick={props.handler.switch.bind(null,"dispMaterialCheckbox",undefined)} > 材料表にチェックボックスを追加 </ListItemInSwitch> <ListItemInSwitch helpText={ <> <Typography variant="body2">原価表に常に最終成果物を表示します。</Typography> <Typography variant="body2">OFFの場合、セット生産時のみ表示します。</Typography> </> } isChecked={props.status.isDispCreationEverytime} onClick={props.handler.switch.bind(null,"dispCreationEverytime",undefined)} > 常時最終作成物表示 </ListItemInSwitch> </List> </Paper> <Paper className={classes.paper}> <List className={classes.list} dense subheader={<Typography variant="subtitle1">レシピ入力支援</Typography>} > <ListItemInTextField helpText={ <> <Typography variant="body2">レシピ検索候補の表示可能とする最大上限数を設定します。</Typography> <Typography variant="body2">0を指定することで無制限となり、未入力時にすべてのレシピが表示されます。</Typography> <Typography variant="body2">動作が重いようでしたら、30程度に絞ることで検索時の動作を軽くできます。</Typography> </> } value={props.status.suggestMax} handleChange={props.handler.suggestMax} > 検索候補表示数 </ListItemInTextField> </List> </Paper> <Paper className={classes.paper}> <List className={classes.list} dense subheader={<Typography variant="subtitle1">結果の初期表示</Typography>} > <ListItemInSwitch helpText={<Typography variant="body2">計算後の画面で、結果の概要を初期状態で展開します。</Typography>} isChecked={props.status.isDefDispSummary} onClick={props.handler.switch.bind(null,"defDispSummary",undefined)} > 概要 </ListItemInSwitch> <ListItemInSwitch helpText={<Typography variant="body2">計算後の画面で、結果の原価表を初期状態で展開します。</Typography>} isChecked={props.status.isDefDispCostSheet} onClick={props.handler.switch.bind(null,"defDispCostSheet",undefined)} > 原価表 </ListItemInSwitch> <ListItemInSwitch helpText={<Typography variant="body2">計算後の画面で、結果の生産ツリーを初期状態で展開します。</Typography>} isChecked={props.status.isDefDispCreationTree} onClick={props.handler.switch.bind(null,"defDispCreationTree",undefined)} > 原価表 </ListItemInSwitch> </List> </Paper> </Box> ) } export default AppTabPanel;
package io.scalecube.services; import static java.util.stream.Collectors.toMap; import com.codahale.metrics.MetricRegistry; import io.scalecube.services.ServiceCall.Call; import io.scalecube.services.discovery.ServiceScanner; import io.scalecube.services.discovery.api.ServiceDiscovery; import io.scalecube.services.discovery.api.ServiceDiscoveryConfig; import io.scalecube.services.gateway.Gateway; import io.scalecube.services.gateway.GatewayConfig; import io.scalecube.services.methods.ServiceMethodRegistry; import io.scalecube.services.methods.ServiceMethodRegistryImpl; import io.scalecube.services.metrics.Metrics; import io.scalecube.services.registry.ServiceRegistryImpl; import io.scalecube.services.registry.api.ServiceRegistry; import io.scalecube.services.transport.ServiceTransportConfig; import io.scalecube.services.transport.api.Address; import io.scalecube.services.transport.api.ClientTransport; import io.scalecube.services.transport.api.ServerTransport; import io.scalecube.services.transport.api.ServiceTransport; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.concurrent.Executor; import java.util.function.Consumer; import java.util.function.Function; import java.util.stream.Collectors; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; /** * The ScaleCube-Services module enables to provision and consuming microservices in a cluster. * ScaleCube-Services provides Reactive application development platform for building distributed * applications Using microservices and fast data on a message-driven runtime that scales * transparently on multi-core, multi-process and/or multi-machines Most microservices frameworks * focus on making it easy to build individual microservices. ScaleCube allows developers to run a * whole system of microservices from a single command. removing most of the boilerplate code, * ScaleCube-Services focuses development on the essence of the service and makes it easy to create * explicit and typed protocols that compose. True isolation is achieved through shared-nothing * design. This means the services in ScaleCube are autonomous, loosely coupled and mobile (location * transparent)—necessary requirements for resilance and elasticity ScaleCube services requires * developers only to two simple Annotations declaring a Service but not regards how you build the * service component itself. the Service component is simply java class that implements the service * Interface and ScaleCube take care for the rest of the magic. it derived and influenced by Actor * model and reactive and streaming patters but does not force application developers to it. * ScaleCube-Services is not yet-anther RPC system in the sense its is cluster aware to provide: * * <ul> * <li>location transparency and discovery of service instances. * <li>fault tolerance using gossip and failure detection. * <li>share nothing - fully distributed and decentralized architecture. * <li>Provides fluent, java 8 lambda apis. * <li>Embeddable and lightweight. * <li>utilizes completable futures but primitives and messages can be used as well completable * futures gives the advantage of composing and chaining service calls and service results. * <li>low latency * <li>supports routing extensible strategies when selecting service end-points * </ul> * * <b>basic usage example:</b> * * <pre>{@code * // Define a service interface and implement it: * &#64; Service * public interface GreetingService { * &#64; ServiceMethod * Mono<String> sayHello(String string); * } * * public class GreetingServiceImpl implements GreetingService { * &#64; Override * public Mono<String> sayHello(String name) { * return Mono.just("hello to: " + name); * } * } * * // Build a microservices cluster instance: * Microservices microservices = Microservices.builder() * // Introduce GreetingServiceImpl pojo as a micro-service: * .services(new GreetingServiceImpl()) * .startAwait(); * * // Create microservice proxy to GreetingService.class interface: * GreetingService service = microservices.call().create() * .api(GreetingService.class); * * // Invoke the greeting service async: * service.sayHello("joe").subscribe(resp->{ * // handle response * }); * * }</pre> */ public class Microservices { private final String id; private final Metrics metrics; private final Map<String, String> tags; private final List<ServiceInfo> serviceInfos = new ArrayList<>(); private final List<Function<Call, Collection<Object>>> serviceProviders; private final ServiceRegistry serviceRegistry; private final ServiceMethodRegistry methodRegistry; private final ServiceTransportBootstrap transportBootstrap; private final GatewayBootstrap gatewayBootstrap; private final ServiceDiscovery discovery; private final Consumer<ServiceDiscoveryConfig.Builder> discoveryOptions; private Microservices(Builder builder) { this.id = UUID.randomUUID().toString(); this.metrics = builder.metrics; this.tags = new HashMap<>(builder.tags); this.serviceProviders = new ArrayList<>(builder.serviceProviders); this.serviceRegistry = builder.serviceRegistry; this.methodRegistry = builder.methodRegistry; this.gatewayBootstrap = builder.gatewayBootstrap; this.discovery = builder.discovery; this.discoveryOptions = builder.discoveryOptions; this.transportBootstrap = new ServiceTransportBootstrap( ServiceTransportConfig.builder(builder.transportOptions).build()); } public static Builder builder() { return new Builder(); } public String id() { return this.id; } private Mono<Microservices> start() { return transportBootstrap .start(methodRegistry) .flatMap( input -> { ClientTransport clientTransport = transportBootstrap.clientTransport(); InetSocketAddress serviceAddress = transportBootstrap.serviceAddress(); Call call = new Call(clientTransport, methodRegistry, serviceRegistry); // invoke service providers and register services serviceProviders .stream() .flatMap(serviceProvider -> serviceProvider.apply(call).stream()) .forEach(this::collectAndRegister); // register services in service registry ServiceEndpoint endpoint = null; if (!serviceInfos.isEmpty()) { String serviceHost = serviceAddress.getHostString(); int servicePort = serviceAddress.getPort(); endpoint = ServiceScanner.scan(serviceInfos, id, serviceHost, servicePort, tags); serviceRegistry.registerService(endpoint); } // configure discovery and publish to the cluster ServiceDiscoveryConfig discoveryConfig = ServiceDiscoveryConfig.builder(discoveryOptions) .serviceRegistry(serviceRegistry) .endpoint(endpoint) .build(); return discovery .start(discoveryConfig) .then(Mono.defer(this::doInjection)) .then(Mono.defer(() -> startGateway(call))) .then(Mono.just(this)); }) .onErrorResume( ex -> { // return original error then shutdown return Mono.when(Mono.error(ex), shutdown()).cast(Microservices.class); }); } private Mono<GatewayBootstrap> startGateway(Call call) { Executor workerThreadPool = transportBootstrap.workerThreadPool(); boolean preferNative = transportBootstrap.transport().isNativeSupported(); return gatewayBootstrap.start(workerThreadPool, preferNative, call, metrics); } private Mono<Microservices> doInjection() { List<Object> serviceInstances = serviceInfos.stream().map(ServiceInfo::serviceInstance).collect(Collectors.toList()); return Mono.just(Reflect.inject(this, serviceInstances)); } private void collectAndRegister(Object serviceInstance) { // collect ServiceInfo serviceInfo = serviceInstance instanceof ServiceInfo ? ((ServiceInfo) serviceInstance) : ServiceInfo.fromServiceInstance(serviceInstance).build(); serviceInfos.add(serviceInfo); // register service object methodRegistry.registerService(serviceInfo.serviceInstance()); } public Metrics metrics() { return this.metrics; } public InetSocketAddress serviceAddress() { return transportBootstrap.serviceAddress(); } public Call call() { return new Call(transportBootstrap.clientTransport(), methodRegistry, serviceRegistry); } public InetSocketAddress gatewayAddress(String name, Class<? extends Gateway> gatewayClass) { return gatewayBootstrap.gatewayAddress(name, gatewayClass); } public Map<GatewayConfig, InetSocketAddress> gatewayAddresses() { return gatewayBootstrap.gatewayAddresses(); } public ServiceDiscovery discovery() { return this.discovery; } /** * Shutdown instance and clear resources. * * @return result of shutdown */ public Mono<Void> shutdown() { return Mono.defer( () -> Mono.when( Optional.ofNullable(discovery).map(ServiceDiscovery::shutdown).orElse(Mono.empty()), Optional.ofNullable(gatewayBootstrap) .map(GatewayBootstrap::shutdown) .orElse(Mono.empty()), Optional.ofNullable(transportBootstrap) .map(ServiceTransportBootstrap::shutdown) .orElse(Mono.empty()))); } public static final class Builder { private Metrics metrics; private Map<String, String> tags = new HashMap<>(); private List<Function<Call, Collection<Object>>> serviceProviders = new ArrayList<>(); private ServiceRegistry serviceRegistry = new ServiceRegistryImpl(); private ServiceMethodRegistry methodRegistry = new ServiceMethodRegistryImpl(); private ServiceDiscovery discovery = ServiceDiscovery.getDiscovery(); private Consumer<ServiceDiscoveryConfig.Builder> discoveryOptions; private Consumer<ServiceTransportConfig.Builder> transportOptions; private GatewayBootstrap gatewayBootstrap = new GatewayBootstrap(); public Mono<Microservices> start() { return Mono.defer(() -> new Microservices(this).start()); } public Microservices startAwait() { return start().block(); } public Builder services(Object... services) { serviceProviders.add(call -> Arrays.stream(services).collect(Collectors.toList())); return this; } public Builder services(Function<Call, Collection<Object>> serviceProvider) { serviceProviders.add(serviceProvider); return this; } public Builder serviceRegistry(ServiceRegistry serviceRegistry) { this.serviceRegistry = serviceRegistry; return this; } public Builder methodRegistry(ServiceMethodRegistry methodRegistry) { this.methodRegistry = methodRegistry; return this; } public Builder discovery(ServiceDiscovery discovery) { this.discovery = discovery; return this; } public Builder discovery(Consumer<ServiceDiscoveryConfig.Builder> discoveryOptions) { this.discoveryOptions = discoveryOptions; return this; } public Builder transport(Consumer<ServiceTransportConfig.Builder> transportOptions) { this.transportOptions = transportOptions; return this; } public Builder metrics(MetricRegistry metrics) { this.metrics = new Metrics(metrics); return this; } public Builder tags(Map<String, String> tags) { this.tags = tags; return this; } public Builder gateway(GatewayConfig config) { gatewayBootstrap.addConfig(config); return this; } } private static class GatewayBootstrap { private Set<GatewayConfig> gatewayConfigs = new HashSet<>(); // config private Map<GatewayConfig, Gateway> gatewayInstances = new HashMap<>(); // calculated private GatewayBootstrap addConfig(GatewayConfig config) { if (!gatewayConfigs.add(config)) { throw new IllegalArgumentException( "GatewayConfig with name: '" + config.name() + "' and gatewayClass: '" + config.gatewayClass().getName() + "' was already defined"); } return this; } private Mono<GatewayBootstrap> start( Executor workerThreadPool, boolean preferNative, Call call, Metrics metrics) { return Flux.fromIterable(gatewayConfigs) .flatMap( gatewayConfig -> Gateway.getGateway(gatewayConfig.gatewayClass()) .start(gatewayConfig, workerThreadPool, preferNative, call, metrics) .doOnSuccess(gw -> gatewayInstances.put(gatewayConfig, gw))) .then(Mono.just(this)); } private Mono<Void> shutdown() { return Mono.defer( () -> gatewayInstances != null && !gatewayInstances.isEmpty() ? Mono.when( gatewayInstances.values().stream().map(Gateway::stop).toArray(Mono[]::new)) : Mono.empty()); } private InetSocketAddress gatewayAddress(String name, Class<? extends Gateway> gatewayClass) { Optional<GatewayConfig> result = gatewayInstances .keySet() .stream() .filter(config -> config.name().equals(name)) .filter(config -> config.gatewayClass() == gatewayClass) .findFirst(); if (!result.isPresent()) { throw new IllegalArgumentException( "Didn't find gateway address under name: '" + name + "' and gateway class: '" + gatewayClass.getName() + "'"); } return gatewayInstances.get(result.get()).address(); } private Map<GatewayConfig, InetSocketAddress> gatewayAddresses() { return Collections.unmodifiableMap( gatewayInstances .entrySet() .stream() .collect(toMap(Entry::getKey, e -> e.getValue().address()))); } } private static class ServiceTransportBootstrap { private static final int DEFAULT_NUM_OF_THREADS = Runtime.getRuntime().availableProcessors(); private String serviceHost; // config private int servicePort; // config private ServiceTransport transport; // config or calculated private ClientTransport clientTransport; // calculated private ServerTransport serverTransport; // calculated private Executor workerThreadPool; // calculated private InetSocketAddress serviceAddress; // calculated private int numOfThreads; // calculated public ServiceTransportBootstrap(ServiceTransportConfig options) { this.serviceHost = options.host(); this.servicePort = Optional.ofNullable(options.port()).orElse(0); this.numOfThreads = Optional.ofNullable(options.numOfThreads()).orElse(DEFAULT_NUM_OF_THREADS); this.transport = options.transport(); } private ServiceTransport transport() { return transport; } private ClientTransport clientTransport() { return clientTransport; } private Executor workerThreadPool() { return workerThreadPool; } private InetSocketAddress serviceAddress() { return serviceAddress; } private Mono<ServiceTransportBootstrap> start(ServiceMethodRegistry methodRegistry) { return Mono.defer( () -> { this.transport = Optional.ofNullable(this.transport).orElseGet(ServiceTransport::getTransport); this.workerThreadPool = transport.getWorkerThreadPool(numOfThreads); this.clientTransport = transport.getClientTransport(workerThreadPool); this.serverTransport = transport.getServerTransport(workerThreadPool); // bind service serverTransport transport return serverTransport .bind(servicePort, methodRegistry) .map( listenAddress -> { // prepare service host:port for exposing int port = listenAddress.getPort(); String host = Optional.ofNullable(serviceHost) .orElseGet(() -> Address.getLocalIpAddress().getHostAddress()); this.serviceAddress = InetSocketAddress.createUnresolved(host, port); return this; }); }); } private Mono<Void> shutdown() { return Mono.defer( () -> Mono.when( Optional.ofNullable(serverTransport) .map(ServerTransport::stop) .orElse(Mono.empty()), Optional.ofNullable(transport) .map(transport -> transport.shutdown(workerThreadPool)) .orElse(Mono.empty()))); } } }
Use of Alternative Treatments by People with Multiple Sclerosis The prevalence, predictors, and description of alternative treatment use among peo ple with multiple sclerosis (MS) have not been well studied despite interest and con cern about such use among health care professionals and people with MS. The goal of this study was to describe the prevalence of the use of specific alternative treatments by people with MS, the sociodemographic and disease characteristics of those most likely to use alternative treatments, perceived benefits and harms from use of these treatments, and the reasons for their use. Almost three-fifths of the study sample of 240 people diagnosed with MS from two chapters of the National Multiple Sclerosis Society had used alternative treatments. Most (90 percent) of those who had used al ternative treatments did so in combination with traditional treatments. Only 7.1 per cent used any treatments considered to be high risk or dangerous. The primary reason for using alternative treatments was to obtain relief from physical and psychological symptoms. Implications of these findings for health care professionals are discussed. Key Words: Multiple sclerosis—Alternative therapies—Complementary therapies— Alternative medical practices—Unconventional medicine.
import type { RouteMatcher } from '../route-matcher'; import type { MatrixRoute } from './matrix-route'; /** * Builds matrix route matcher that matches a matrix attribute. * * @param name - Required matrix attribute. * @param value - A value the attribute should have. Or nothing to just require the attribute to present. * * @returns New URL route matcher. */ export function rmatchMatrixAttr(name: string, value?: string): RouteMatcher<MatrixRoute> { const condition: (attrs: URLSearchParams) => boolean = value == null ? attrs => attrs.has(name) : attrs => attrs.getAll(name).includes(value); return { test: ({ entry: { attrs } }) => condition(attrs) && { nameChars: 0 }, }; }
<filename>gen/transports/grpc/grpc.go package kafka_grpctransport import ( "fmt" grpctransport "github.com/go-kit/kit/transport/grpc" context "golang.org/x/net/context" endpoints "github.com/moul/kafka-gateway/gen/endpoints" pb "github.com/moul/kafka-gateway/gen/pb" ) // avoid import errors var _ = fmt.Errorf func MakeGRPCServer(ctx context.Context, endpoints endpoints.Endpoints) pb.KafkaServiceServer { var options []grpctransport.ServerOption _ = options return &grpcServer{ consumer: grpctransport.NewServer( ctx, endpoints.ConsumerEndpoint, decodeRequest, encodeConsumerResponse, options..., ), producer: grpctransport.NewServer( ctx, endpoints.ProducerEndpoint, decodeRequest, encodeProducerResponse, options..., ), consumerstream: &server{ e: endpoints.ConsumerStreamEndpoint, }, } } type grpcServer struct { consumer grpctransport.Handler producer grpctransport.Handler consumerstream streamHandler } func (s *grpcServer) Consumer(ctx context.Context, req *pb.ConsumerRequest) (*pb.ConsumerResponse, error) { _, rep, err := s.consumer.ServeGRPC(ctx, req) if err != nil { return nil, err } return rep.(*pb.ConsumerResponse), nil } func encodeConsumerResponse(ctx context.Context, response interface{}) (interface{}, error) { resp := response.(*pb.ConsumerResponse) return resp, nil } func (s *grpcServer) Producer(ctx context.Context, req *pb.ProducerRequest) (*pb.ProducerResponse, error) { _, rep, err := s.producer.ServeGRPC(ctx, req) if err != nil { return nil, err } return rep.(*pb.ProducerResponse), nil } func encodeProducerResponse(ctx context.Context, response interface{}) (interface{}, error) { resp := response.(*pb.ProducerResponse) return resp, nil } func (s *grpcServer) ConsumerStream(req *pb.ConsumerStreamRequest, server pb.KafkaService_ConsumerStreamServer) error { return s.consumerstream.Do(server, req) } func decodeRequest(ctx context.Context, grpcReq interface{}) (interface{}, error) { return grpcReq, nil } type streamHandler interface { Do(server interface{}, req interface{}) (err error) } type server struct { e endpoints.StreamEndpoint } func (s server) Do(server interface{}, req interface{}) (err error) { if err := s.e(server, req); err != nil { return err } return nil }
<filename>net/diagnostics/netdiag/tfschar.h //============================================================================ // Copyright (C) Microsoft Corporation, 1997- 1999 // // File: tfschar.h // // String functions that are used in general for TFS code. // // History: // // 05/28/97 <NAME> Created. // // Declarations for some common code/macros. //============================================================================ #ifndef _TFSCHAR_H #define _TFSCHAR_H #if _MSC_VER >= 1000 // VC 5.0 or later #pragma once #endif #define TFSCORE_API(x) x //$ Win95: kennt, the list of Unicode-enabled functions on Win95 will // have to be checked. Does lstrlenW work, but lstrcpyW doesn't? (that's // what the ATL versions of the functions imply). /*--------------------------------------------------------------------------- String copy functions ---------------------------------------------------------------------------*/ // Baisc conversion functions TFSCORE_API(LPSTR) StrCpyAFromW(LPSTR psz, LPCWSTR pswz); TFSCORE_API(LPWSTR) StrCpyWFromA(LPWSTR pswz, LPCSTR psz); TFSCORE_API(LPSTR) StrnCpyAFromW(LPSTR psz, LPCWSTR pswz, int iMax); TFSCORE_API(LPWSTR) StrnCpyWFromA(LPWSTR pswz, LPCSTR psz, int iMax); #define StrCpy lstrcpy #define StrnCpy lstrcpyn #define StrCpyW lstrcpyW #define StrCpyA lstrcpyA #define StrnCpyW lstrcpynW #define StrnCpyA lstrcpynA #define StrCpyOle StrCpyW #define StrnCpyOle StrnCpyW #ifdef _UNICODE #define StrCpyAFromT StrCpyAFromW #define StrCpyTFromA StrCpyWFromA #define StrCpyTFromW lstrcpy #define StrCpyWFromT lstrcpy #define StrnCpyAFromT StrnCpyAFromW #define StrnCpyTFromA StrnCpyWFromA #define StrnCpyTFromW lstrcpyn #define StrnCpyWFromT lstrcpyn #else #define StrCpyAFromT lstrcpy #define StrCpyTFromA lstrcpy #define StrCpyTFromW StrCpyAFromW #define StrCpyWFromT StrCpyWFromA #define StrnCpyAFromT lstrcpyn #define StrnCpyTFromA lstrcpyn #define StrnCpyTFromW StrnCpyAFromW #define StrnCpyWFromT StrnCpyWFromA #endif #define StrCpyOleFromT StrCpyWFromT #define StrCpyTFromOle StrCpyTFromW #define StrCpyOleFromA StrCpyWFromA #define StrCpyAFromOle StrCpyAFromW #define StrCpyWFromOle StrCpyW #define StrCpyOleFromW StrCpyW #define StrnCpyOleFromT StrnCpyWFromT #define StrnCpyTFromOle StrnCpyTFromW #define StrnCpyOleFromA StrnCpyWFromA #define StrnCpyAFromOle StrnCpyAFromW #define StrnCpyOleFromW StrnCpyW #define StrnCpyWFromOle StrnCpyW /*--------------------------------------------------------------------------- String length functions ---------------------------------------------------------------------------*/ #define StrLen lstrlen #define StrLenA lstrlenA #define StrLenW lstrlenW #define StrLenOle StrLenW // // CbStrLenA() is inaccurate for DBCS strings! It will return the // incorrect number of bytes needed. // #define CbStrLenA(psz) ((StrLenA(psz)+1)*sizeof(char)) #define CbStrLenW(psz) ((StrLenW(psz)+1)*sizeof(WCHAR)) #ifdef _UNICODE #define CbStrLen(psz) CbStrLenW(psz) #else #define CbStrLen(psz) CbStrLenA(psz) #endif // Given a number of characters, this it the minimal number of TCHARs // that needs to be allocated to hold the string #define MinTCharNeededForCch(ch) ((ch) * (2/sizeof(TCHAR))) #define MinCbNeededForCch(ch) (sizeof(TCHAR)*MinTCharNeededForCch(ch)) // Given a cb (count of bytes) this is the maximal number of characters // that can be in this string #define MaxCchFromCb(cb) ((cb) / sizeof(TCHAR)) #ifdef _UNICODE // Given a cb, this is the minimum number of chars found in this string // MinCchFromCb #define MinCchFromCb(cb) ((cb) / sizeof(WCHAR)) #else // Number of characters is only half due to DBCS #define MinCchFromCb(cb) ((cb) / (2*sizeof(char))) #endif /*--------------------------------------------------------------------------- String dup functions The returned string from these functions must be freed using delete! ---------------------------------------------------------------------------*/ TFSCORE_API(LPSTR) StrDupA( LPCSTR psz ); TFSCORE_API(LPWSTR) StrDupW( LPCWSTR pws ); TFSCORE_API(LPSTR) StrDupAFromW( LPCWSTR pwsz ); TFSCORE_API(LPWSTR) StrDupWFromA( LPCSTR psz ); #ifdef _UNICODE #define StrDup StrDupW #define StrDupTFromW StrDupW #define StrDupWFromT StrDupW #define StrDupTFromA StrDupWFromA #define StrDupAFromT StrDupAFromW #define StrDupOleFromA StrDupWFromA #define StrDupAFromOle StrDupAFromW #define StrDupOleFromW StrDupW #define StrDupWFromOle StrDupW #define StrDupOleFromT StrDupOleFromW #define StrDupTFromOle StrDupWFromOle #else #define StrDup StrDupA #define StrDupTFromA StrDupA #define StrDupAFromT StrDupA #define StrDupTFromW StrDupAFromW #define StrDupWFromT StrDupWFromA #define StrDupOleFromA StrDupWFromA #define StrDupAFromOle StrDupAFromW #define StrDupOleFromW StrDupW #define StrDupWFromOle StrDupW #define StrDupOleFromT StrDupOleFromA #define StrDupTFromOle StrDupAFromOle #endif // AllocaStrDup // AllocaStrDupA // AllocaStrDupW // // These functions will dup a string on the STACK. // #define AllocaStrDupA(lpa) (\ ((LPCSTR)lpa == NULL) ? NULL : (\ StrCpyA((LPSTR) alloca(CbStrLenA(lpa)*2), lpa))) #define AllocaStrDupW(lpw) (\ ((LPCWSTR)lpw == NULL) ? NULL : (\ StrCpyW((LPWSTR) alloca(CbStrLenW(lpw)), lpw))) #ifdef _UNICODE #define AllocaStrDup AllocaStrDupW #else #define AllocaStrDup AllocaStrDupA #endif /*--------------------------------------------------------------------------- String comparison functions ---------------------------------------------------------------------------*/ #define StrCmpA lstrcmpA #define StrCmpW lstrcmpW #define StrCmpOle StrCmpW TFSCORE_API(int) StrnCmpA(LPCSTR psz1, LPCSTR psz2, int nLen); TFSCORE_API(int) StrnCmpW(LPCWSTR pswz1, LPCWSTR pswz2, int nLen); #define StriCmpA lstrcmpiA #define StriCmpW lstrcmpiW #define StriCmpOle StriCmpW TFSCORE_API(int) StrniCmpA(LPCSTR psz1, LPCSTR psz2, int nLen); TFSCORE_API(int) StrniCmpW(LPCWSTR pswz1, LPCWSTR pswz2, int nLen); #ifdef _UNICODE #define StrCmp StrCmpW #define StrnCmp StrnCmpW #define StriCmp StriCmpW #define StrniCmp StrniCmpW #else #define StrCmp StrCmpA #define StrnCmp StrnCmpA #define StriCmp StriCmpA #define StrniCmp StrniCmpA #endif /*--------------------------------------------------------------------------- String concatenation routines ---------------------------------------------------------------------------*/ #define StrCatW lstrcatW #define StrCatA lstrcatA #ifdef _UNICODE #define StrCat StrCatW #else #define StrCat StrCatA #endif /*--------------------------------------------------------------------------- LoadString helpers ---------------------------------------------------------------------------*/ LPTSTR LoadAndAllocString(UINT ids); /*--------------------------------------------------------------------------- Get safe strings ---------------------------------------------------------------------------*/ LPTSTR GetSafeString(LPTSTR psz); LPWSTR GetSafeStringW(LPWSTR pwsz); LPSTR GetSafeStringA(LPSTR pasz); /*--------------------------------------------------------------------------- Local conversion routines (conversions performed on stack!) ---------------------------------------------------------------------------*/ // Make sure MFC's afxconv.h hasn't already been loaded to do this #ifndef USES_CONVERSION #ifndef _DEBUG #define USES_CONVERSION int _convert; _convert #else #define USES_CONVERSION int _convert = 0 #endif ///////////////////////////////////////////////////////////////////////////// // Global UNICODE<>ANSI translation helpers LPWSTR WINAPI AtlA2WHelper(LPWSTR lpw, LPCSTR lpa, int nChars); LPSTR WINAPI AtlW2AHelper(LPSTR lpa, LPCWSTR lpw, int nChars); #define A2W(lpa) (\ ((LPCSTR)lpa == NULL) ? NULL : (\ _convert = (lstrlenA(lpa)+1),\ AtlA2WHelper((LPWSTR) alloca(_convert*2), lpa, _convert))) #define W2A(lpw) (\ ((LPCWSTR)lpw == NULL) ? NULL : (\ _convert = (lstrlenW(lpw)+1)*2,\ AtlW2AHelper((LPSTR) alloca(_convert), lpw, _convert))) #define A2CW(lpa) ((LPCWSTR)A2W(lpa)) #define W2CA(lpw) ((LPCSTR)W2A(lpw)) #ifdef _UNICODE #define T2A W2A #define A2T A2W #define T2W(_lp) (_lp) #define W2T(_lp) (_lp) #define T2CA W2CA #define A2CT A2CW #define T2CW(_lp) (_lp) #define W2CT(_lp) (_lp) #else #define T2W A2W #define W2T W2A #define T2A(_lp) (_lp) #define A2T(_lp) (_lp) #define T2CW A2CW #define W2CT W2CA #define T2CA(_lp) (_lp) #define A2CT(_lp) (_lp) #endif #endif // !USES_CONVERSION #endif // _TFSCHAR_H
//////////////////////////////////////////////////////////////////// // Function: Filename::set_extension // Access: Published // Description: Replaces the file extension. This is everything after // the rightmost dot, if there is one, or the empty // string if there is not. //////////////////////////////////////////////////////////////////// void Filename:: set_extension(const string &s) { if (s.empty()) { if (_basename_end != string::npos) { _filename.replace(_basename_end, string::npos, ""); _basename_end = string::npos; _extension_start = string::npos; } } else if (_basename_end == string::npos) { _basename_end = _filename.length(); _extension_start = _filename.length() + 1; _filename += '.' + s; } else { _filename.replace(_extension_start, string::npos, s); } locate_hash(); }
// Single delete should not cancel out values that not visible to the // same set of snapshots TEST_F(CompactionIteratorWithSnapshotCheckerTest, SingleDeleteAcrossSnapshotBoundary) { AddSnapshot(2, 1); RunTest({test::KeyStr("a", 2, kTypeSingleDeletion), test::KeyStr("a", 1, kTypeValue)}, {"", "v1"}, {test::KeyStr("a", 2, kTypeSingleDeletion), test::KeyStr("a", 1, kTypeValue)}, {"", "v1"}, 2 ); }
n,m,k=map(int,raw_input().split()); print n%2*min(min(list(map(int,raw_input().split()))[0::2]),m/(n/2+1)*k)
// EndModule closes the current module definition if the module is a child module and clears the generator's module // field. func (g *generator) EndModule(m *il.Graph) error { if !g.isRoot() { g.Indent = g.Indent[:len(g.Indent)-4] g.Printf("};\n") } g.module = nil return nil }
/* * File: main.cpp * Author: andrew * * Created on 17 Февраль 2012 г., 19:58 */ #include<stdio.h> #include <iostream> #include<algorithm> #include <vector> #define Forn(i,n) for(int i=0;i<(n);i++) using namespace std; struct info { string nm; int girl,pizza,taxi; }; int mgirl,mpizza,mtaxi; int mgirl1,mpizza1,mtaxi1; void sc_num(info * inf) { string str; cin>>str; char num[6]; int k=0; Forn(i,8) { if(str[i]!='-') { num[k++]=str[i]-'0'; } } bool is_eq=true; Forn(i,5) if(num[i+1]!=num[i]) is_eq=false; if(is_eq) { inf->taxi++; return; } is_eq = true; Forn(i,5) if(num[i+1]>=num[i]) is_eq=false; if(is_eq) { inf->pizza++; return; } inf->girl++; }; /* * */ #define pb push_back; info usrs[100]; int n; int k; int main(int argc, char** argv) { cin>>n; Forn(i,n) { cin>>k>>usrs[i].nm; Forn(j,k) sc_num(&usrs[i]); mtaxi1 = max(mtaxi1,usrs[i].taxi); mpizza1=max(mpizza1,usrs[i].pizza); mgirl1=max(mgirl1,usrs[i].girl); } cout<<"If you want to call a taxi, you should call: "; bool b1=false; Forn(i,n) if(usrs[i].taxi== mtaxi1) { if(b1) cout<<", "; cout<< usrs[i].nm; b1=true; } cout<<".\nIf you want to order a pizza, you should call: "; b1=false; Forn(i,n) if(usrs[i].pizza==mpizza1) { if(b1) cout<<", "; cout<< usrs[i].nm; b1=true; } cout<<".\nIf you want to go to a cafe with a wonderful girl, you should call: "; b1=false; Forn(i,n) if(usrs[i].girl==mgirl1) { if(b1) cout<<", "; cout<< usrs[i].nm; b1=true; } cout<<"."; return 0; }
<reponame>calmsacibis995/minix /* $NetBSD: test_engine_dso.c,v 1.1.1.2 2014/04/24 12:45:30 pettai Exp $ */ /* * Copyright (c) 2006 <NAME> * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include <config.h> #include <stdio.h> #include <krb5/roken.h> #include <krb5/getarg.h> #include <engine.h> #include <evp.h> struct { const char *cpriv; const char *cpub; const char *spriv; const char *spub; } dhtests[] = { { "<KEY>", "<KEY>", "42644BA7CF74689E18BA72BF80FCA674D1A2ADF81795EB3828E67C30E42ABD07A8E90E27F046189FAC122D915276870B72427388EAAB5D06994FC38885BBACCEA1CFC45951B730D73C1A8F83208CD1351746601648C11D70BC95B817C86E4A5C40D633654615041C7934BB3CAF4E02754D542033DB024E94C7E561A29ED0C6EC", "C233633AB116E2DB20B4E08DA42DE8766293E6D9042F7A2C2A2F34F18FE66010B074CCF3C9B03EF27B14F0746B738AF22776224161D767D96AEC230A1DFA6DECFFCE9FED23B96F50CCB0093E59817AD0CEAEB7993AB5764679948BFB1293C9560B07AA3DFA229E341EB17C9FAE0B1D483082461D2DDBCEEE6FE7C0A34D96F66D" }, { "<KEY>", "<KEY>", "68D84A8F92082F113542CFD990DEEFAD9C7EFA545268F8B3EBDF4CCBAF2865CF03EF60044EB4AF4154E6804CC2BDD673B801507446CEFC692DA577B6DC6E0272B7B081A1BEFDC2A4FAC83DB8845E3DA0D1B64DB33AA2164FEDB08A01E815336BD58F4E6DE6A265468E61C8C988B8AEC0D52DB714448DDC007E7C3382C07357DB", "<KEY>" }, { "7307D6C3CB874327A95F7A6A91C336CEAA086736525DF3F8EC49497CF444C68D264EB70CD6904FE56E240EEF34E6C5177911C478A7F250A0F54183BCBE64B42BAB5D019E73E2F17C095C211E4815E6BA5FDD72786AF987ABBC9109ECEEF439AF9E2141D5222CE7DC0152D8E9A6CCCE301D21A7D1D6ACB9B91B5E28379C91890D", "<KEY>", "61BCF748BB05A48861578B8CB1855200B2E62A40E126BD7323E5B714645A54A2C8761EE39EE39BA6D2FE19B688168EDEA6DC5056400B5315ED299E7926176B887012E58634D78F05D7BCF0E1B81B1B41F5F8EF0B0711D3A64F9A317DD183AE039A4D3BE02A515892362F8C7BB6EB6434BB25418A438ED33D50C475122CBBE862", "7DB8D69D1605D9812B7F2F3E92BCEEB3426FEEE3265A174D71B2B6E16B332B43DF0B3C2FA152E48DE2FAC110D8CECE122C3398558E7987B27CACE12722C0032AC7E7766A9BCC881BA35B9DB9E751BD4E51F7683DE092F6C1D4DD937CDCE9C16E6F7D77CC6AAD806E4082E8E22E28592C4D78256354393FE831E811E03ED0A81A" }, { "<KEY>", "0DEDA337C38EA005D5B8567EAB681CE91892C2C62C9D42BF748FBFE681E11F25D98280E42E1539A10EEE9177EF2F40216987936AF19D9B5EBE22EEAC27242D77CE3A5061F2E5CFACF15CD0F80E736AE8642252FE91E129DE3C78CFB85A0B1BB87B059CBB24483444F8A07244F4E89370BA78D58BD409DFBB3D41921B8879B9C7", "<KEY>", "56DB382EDB8C2D95934D20261CE1A37090B0802D451E647DB1DA3B73CDB5A878EAD598A8817302449370F9D45E34F5C45F73D02BF4EB2B3712A8665F446F5D2B774039E5444AB74807859FA58DF9EBA4B12BA4545ACED827E4ED64CC71F937D64A1033BC43403F2490C1B715A74822B8D50A72A102213F0CF7A1B98B771B34C4" }, { "61B7321207F4A73646E43E99221F902D2F38095E84CE7346A1510FE71BA7B9B34DCB6609E4DDDA8C82426E82D1C23F1E761130ECE4638D77554A7618E1608625049328FCC1F8845CA9A88E847106B01BD31EF6500E3C7EE81A048924BEAA3EDF367E5F4575341206C7A76427571898294B07BD918D4C2642854CC89D439042E5", "<KEY>", "5ED5AFB04CBFEE43EF3D9B60A57080831563648A2380D98F1EA4A96CF153903A40A2E564DED87E7254DF3270568AB952BF6F400681DD6AD919C9B06AC0F45F0646BCF37B217191AA0B7B7BED226B61F48B46DEA2E5A09E41F316583823A38A60FFD79085F43F60D98871ECA1A0F667701425094E88885A81DE9DA6C293E95060", "4DE4F24EAA3E2790FBCB1B13C2ED0EFD846EC33154DBEBBEFD895E1399B3617D55EC2CE8D71CF380B55D93636FEF741328D6B1E224D46F8A8B60A41D08DD86E88DE806AA781791364E6D88BF68571BF5D8C35CB04BA302227B7E4CB6A67AB7510ACBCDBF2F8A95EB5DEE693CCA5CC425A0F1CA2D18C369A767906A2477E32704" } }; static void dh_test(DH *server, DH *client) { void *skey, *ckey; int ssize, csize; skey = emalloc(DH_size(server)); ckey = emalloc(DH_size(client)); ssize = DH_compute_key(skey, client->pub_key, server); if (ssize == -1) errx(1, "DH_compute_key failed for server"); csize = DH_compute_key(ckey, server->pub_key, client); if (csize == -1) errx(1, "DH_compute_key failed for client"); if (ssize != csize) errx(1, "DH_compute_key size mismatch"); if (memcmp(skey, ckey, csize) != 0) errx(1, "DH_compute_key key mismatch"); free(skey); free(ckey); } static int version_flag; static int help_flag; static char *id_flag; static char *rsa_flag; static int dh_flag = 1; static int test_random_flag; static struct getargs args[] = { { "id", 0, arg_string, &id_flag, "selects the engine id", "engine-id" }, { "rsa", 0, arg_string, &rsa_flag, "tests RSA modes", "private-rsa-der-file" }, { "dh", 0, arg_negative_flag, &dh_flag, "test dh", NULL }, { "test-random", 0, arg_flag, &test_random_flag, "test if there is a random device", NULL }, { "version", 0, arg_flag, &version_flag, "print version", NULL }, { "help", 0, arg_flag, &help_flag, NULL, NULL } }; static void usage (int ret) { arg_printusage (args, sizeof(args)/sizeof(*args), NULL, "filename.so"); exit (ret); } int main(int argc, char **argv) { ENGINE *engine = NULL; int idx = 0; int have_rsa, have_dh; setprogname(argv[0]); if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &idx)) usage(1); if (help_flag) usage(0); if(version_flag){ print_version(NULL); exit(0); } argc -= idx; argv += idx; OpenSSL_add_all_algorithms(); if (argc == 0) { OpenSSL_add_all_algorithms(); ENGINE_load_builtin_engines(); engine = ENGINE_by_id("builtin"); } else { engine = ENGINE_by_dso(argv[0], id_flag); } if (engine == NULL) errx(1, "ENGINE_by_dso failed"); printf("name: %s\n", ENGINE_get_name(engine)); printf("id: %s\n", ENGINE_get_id(engine)); have_rsa = ENGINE_get_RSA(engine) != NULL; have_dh = ENGINE_get_DH(engine) != NULL; printf("RSA: %s", have_rsa ? "yes," : "no"); if (have_rsa) printf(" %s", ENGINE_get_RSA(engine)->name); printf("\n"); printf("DH: %s", have_dh ? "yes," : "no"); if (have_dh) printf(" %s", ENGINE_get_DH(engine)->name); printf("\n"); if (RAND_status() != 1) errx(77, "no functional random device, can't execute tests"); if (test_random_flag) exit(0); if (rsa_flag && have_rsa) { unsigned char buf[1024 * 4]; const unsigned char *p; size_t size; int keylen; RSA *rsa; FILE *f; f = fopen(rsa_flag, "rb"); if (f == NULL) err(1, "could not open file %s", rsa_flag); size = fread(buf, 1, sizeof(buf), f); if (size == 0) err(1, "failed to read file %s", rsa_flag); if (size == sizeof(buf)) err(1, "key too long in file %s!", rsa_flag); fclose(f); p = buf; rsa = d2i_RSAPrivateKey(NULL, &p, size); if (rsa == NULL) err(1, "failed to parse key in file %s", rsa_flag); RSA_set_method(rsa, ENGINE_get_RSA(engine)); /* * try rsa signing */ memcpy(buf, "hejsan", 7); keylen = RSA_private_encrypt(7, buf, buf, rsa, RSA_PKCS1_PADDING); if (keylen <= 0) errx(1, "failed to private encrypt"); keylen = RSA_public_decrypt(keylen, buf, buf, rsa, RSA_PKCS1_PADDING); if (keylen <= 0) errx(1, "failed to public decrypt"); if (keylen != 7) errx(1, "output buffer not same length: %d", (int)keylen); if (memcmp(buf, "hejsan", 7) != 0) errx(1, "string not the same after decryption"); /* * try rsa encryption */ memcpy(buf, "hejsan", 7); keylen = RSA_public_encrypt(7, buf, buf, rsa, RSA_PKCS1_PADDING); if (keylen <= 0) errx(1, "failed to public encrypt"); keylen = RSA_private_decrypt(keylen, buf, buf, rsa, RSA_PKCS1_PADDING); if (keylen <= 0) errx(1, "failed to private decrypt"); if (keylen != 7) errx(1, "output buffer not same length: %d", (int)keylen); if (memcmp(buf, "hejsan", 7) != 0) errx(1, "string not the same after decryption"); RSA_free(rsa); printf("rsa test passed\n"); } if (dh_flag) { DH *server, *client; int i; /* RFC2412-MODP-group2 */ const char *p = "FFFFFFFF" "FFFFFFFF" "C90FDAA2" "2168C234" "C4C6628B" "80DC1CD1" "29024E08" "8A67CC74" "020BBEA6" "3B139B22" "514A0879" "8E3404DD" "EF9519B3" "CD3A431B" "302B0A6D" "F25F1437" "4FE1356D" "6D51C245" "E485B576" "625E7EC6" "F44C42E9" "A637ED6B" "0BFF5CB6" "F406B7ED" "EE386BFB" "5A899FA5" "AE9F2411" "7C4B1FE6" "49286651" "ECE65381" "FFFFFFFF" "FFFFFFFF"; const char *g = "02"; /* * Try generated keys */ for (i = 0; i < 10; i++) { server = DH_new_method(engine); client = DH_new_method(engine); BN_hex2bn(&server->p, p); BN_hex2bn(&client->p, p); BN_hex2bn(&server->g, g); BN_hex2bn(&client->g, g); if (!DH_generate_key(server)) errx(1, "DH_generate_key failed for server"); if (!DH_generate_key(client)) errx(1, "DH_generate_key failed for client"); dh_test(server, client); DH_free(server); DH_free(client); } /* * Try known result */ for (i = 0; i < sizeof(dhtests)/sizeof(dhtests[0]); i++) { server = DH_new_method(engine); client = DH_new_method(engine); BN_hex2bn(&server->p, p); BN_hex2bn(&client->p, p); BN_hex2bn(&server->g, g); BN_hex2bn(&client->g, g); BN_hex2bn(&client->priv_key, dhtests[i].cpriv); BN_hex2bn(&client->pub_key, dhtests[i].cpub); BN_hex2bn(&server->priv_key, dhtests[i].spriv); BN_hex2bn(&server->pub_key, dhtests[i].spub); dh_test(server, client); DH_free(server); DH_free(client); } printf("DH test passed\n"); } ENGINE_finish(engine); return 0; }
#include <iostream> using namespace std; int main() { int q,w,e,r,t,n,m,c; cin>>n>>m>>r; int a[51],s[51]; c=r; t=0; w=10001; for (q=1; q<=n; q++) cin>>a[q]; for (q=1; q<=m; q++) cin>>s[q]; for (q=1; q<=m; q++) if (s[q]>t) t=s[q]; for (q=1; q<=n; q++) if (c<t*(r/a[q])+r%a[q]) c=t*(r/a[q])+r%a[q]; cout<<c; return 0; }
<reponame>xhunmon/AFPlayer /** * description: 使用ffmpeg对音频数据进行重采样 <br> * * @author 秦城季 * @email <EMAIL> * @blog https://qincji.gitee.io * @date 2021/2/10 */ #include "audio_swr.h" AudioSwr::AudioSwr(AVCodecContext *d, Global *g) { decCtx = d; global = g; } bool AudioSwr::isNeedSwr() { bool needSampleRate; bool needSampleFmt; switch (decCtx->sample_rate * 1000) {//需要根据OpenSL ES所支持的来判断是否需要重采样。 case SL_SAMPLINGRATE_8: case SL_SAMPLINGRATE_11_025: case SL_SAMPLINGRATE_12: case SL_SAMPLINGRATE_16: case SL_SAMPLINGRATE_22_05: case SL_SAMPLINGRATE_24: case SL_SAMPLINGRATE_32: case SL_SAMPLINGRATE_44_1: case SL_SAMPLINGRATE_48: case SL_SAMPLINGRATE_64: case SL_SAMPLINGRATE_88_2: case SL_SAMPLINGRATE_96: case SL_SAMPLINGRATE_192: needSampleRate = false; outSampleRate = decCtx->sample_rate; break; default: LOGE("OpenSL ES not support the %d sample_rate.", decCtx->sample_rate); needSampleRate = true; outSampleRate = DEFAULT_AUDIO_SAMPLE_RATE; break; } //OpenSL ES 1.1支持浮点的值 switch (decCtx->sample_fmt) { case AV_SAMPLE_FMT_FLT: case AV_SAMPLE_FMT_FLTP: needSampleFmt = false; outSampleFmt = decCtx->sample_fmt; outFmtType = SL_ANDROID_PCM_REPRESENTATION_FLOAT; break; case AV_SAMPLE_FMT_S16: case AV_SAMPLE_FMT_S32: case AV_SAMPLE_FMT_S16P: case AV_SAMPLE_FMT_S32P: case AV_SAMPLE_FMT_S64: case AV_SAMPLE_FMT_S64P: needSampleFmt = false; outSampleFmt = decCtx->sample_fmt; outFmtType = SL_ANDROID_PCM_REPRESENTATION_SIGNED_INT; break; case AV_SAMPLE_FMT_U8: case AV_SAMPLE_FMT_U8P: needSampleFmt = false; outSampleFmt = decCtx->sample_fmt; outFmtType = SL_ANDROID_PCM_REPRESENTATION_UNSIGNED_INT; break; default: LOGE("OpenSL ES not support the %d sample_fmt.", decCtx->sample_fmt); needSampleFmt = true; outSampleFmt = DEFAULT_AUDIO_FORMAT; outFmtType = SL_ANDROID_PCM_REPRESENTATION_FLOAT; break; } return needSampleRate || needSampleFmt; } bool AudioSwr::initSwr() { bool ret = false; if (!(swrCtx = swr_alloc())) { LOGE("Could not allocate swr: %d(%s)", ret, av_err2str(ret)); return ret; } av_opt_set_int(swrCtx, "in_channel_count", decCtx->channels, 0); av_opt_set_int(swrCtx, "in_sample_rate", decCtx->sample_rate, 0); av_opt_set_sample_fmt(swrCtx, "in_sample_fmt", decCtx->sample_fmt, 0); av_opt_set_int(swrCtx, "out_channel_count", decCtx->channels, 0); av_opt_set_int(swrCtx, "out_sample_rate", outSampleRate, 0); av_opt_set_sample_fmt(swrCtx, "out_sample_fmt", (AVSampleFormat) outSampleFmt, 0); if (swr_init(swrCtx) < 0) { LOGE("Failed to initialize swr: %d(%s)", ret, av_err2str(ret)); return ret; } return true; } AudioSwr::~AudioSwr() { decCtx = nullptr; global = nullptr; if (swrCtx) { swr_free(&swrCtx); swrCtx = nullptr; } outSampleRate = 0; outSampleFmt = AV_SAMPLE_FMT_NONE; nbSample = 0; outFmtType = 0; } void AudioSwr::resampleAudio(AVFrame **frame) { AVFrame *re_frame; int ret; if (!(re_frame = av_frame_alloc())) { LOGE("Could not allocate swr frame!"); return; } if ((ret = av_frame_copy_props(re_frame, *frame)) < 0) { LOGE("Copy audio frame failed: %d(%s)", ret, av_err2str(ret)); return; } //需要改变的 re_frame->format = outSampleFmt; re_frame->channel_layout = (*frame)->channel_layout; re_frame->channels = (*frame)->channels; re_frame->sample_rate = outSampleRate; re_frame->nb_samples = nbSample; if ((ret = av_frame_get_buffer(re_frame, 0)) < 0) { LOGE("Fail to get buffer: %d(%s)", ret, av_err2str(ret)); return; } int64_t delays = swr_get_delay(swrCtx,(*frame)->sample_rate); int64_t max_samples = av_rescale_rnd(delays + (*frame)->nb_samples,global->sampleRate,(*frame)->sample_rate,AV_ROUND_UP); // int samples = swr_convert(swrCtx, re_frame->data, max_samples, (const uint8_t **) (*frame)->data, (*frame)->nb_samples); if ((ret = swr_convert(swrCtx, re_frame->data, max_samples, (const uint8_t **) (*frame)->data, (*frame)->nb_samples)) < 0) { LOGE("Fail to resample: %d(%s)", ret, av_err2str(ret)); av_frame_free(&re_frame); return; } //获得 samples 个 * 2 声道 * 2字节(16位) // global->frameSize = samples * global->channels * global->bytesPerSample; //获取 frame 的一个相对播放时间 (相对开始播放) // 获得 相对播放这一段数据的秒数 re_frame->pts = (*frame)->pts * av_q2d(decCtx->time_base);//time_base应该是stream的 /*if ((ret = swr_convert(swrCtx, re_frame->data, nbSample, (const uint8_t **) (*frame)->data, (*frame)->nb_samples)) < 0) { LOGE("Fail to resample: %d(%s)", ret, av_err2str(ret)); av_frame_free(&re_frame); return; }*/ av_frame_free(frame); *frame = re_frame; // LOGD("resample audio success!"); }
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++03, c++11, c++14 // <variant> // template <size_t I, class T> struct variant_alternative; // undefined // template <size_t I, class T> struct variant_alternative<I, const T>; // template <size_t I, class T> struct variant_alternative<I, volatile T>; // template <size_t I, class T> struct variant_alternative<I, const volatile T>; // template <size_t I, class T> // using variant_alternative_t = typename variant_alternative<I, T>::type; // // template <size_t I, class... Types> // struct variant_alternative<I, variant<Types...>>; #include <memory> #include <type_traits> #include <variant> #include "test_macros.h" #include "variant_test_helpers.h" template <class V, size_t I, class E> void test() { static_assert( std::is_same_v<typename std::variant_alternative<I, V>::type, E>, ""); static_assert( std::is_same_v<typename std::variant_alternative<I, const V>::type, const E>, ""); static_assert( std::is_same_v<typename std::variant_alternative<I, volatile V>::type, volatile E>, ""); static_assert( std::is_same_v< typename std::variant_alternative<I, const volatile V>::type, const volatile E>, ""); static_assert(std::is_same_v<std::variant_alternative_t<I, V>, E>, ""); static_assert(std::is_same_v<std::variant_alternative_t<I, const V>, const E>, ""); static_assert( std::is_same_v<std::variant_alternative_t<I, volatile V>, volatile E>, ""); static_assert(std::is_same_v<std::variant_alternative_t<I, const volatile V>, const volatile E>, ""); } int main(int, char**) { { using V = std::variant<int, void *, const void *, long double>; test<V, 0, int>(); test<V, 1, void *>(); test<V, 2, const void *>(); test<V, 3, long double>(); } #if !defined(TEST_VARIANT_HAS_NO_REFERENCES) { using V = std::variant<int, int &, const int &, int &&, long double>; test<V, 0, int>(); test<V, 1, int &>(); test<V, 2, const int &>(); test<V, 3, int &&>(); test<V, 4, long double>(); } #endif return 0; }
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'variables': { 'chromium_code': 1, }, 'includes': [ '../build/common_untrusted.gypi', 'ipc.gypi', ], 'conditions': [ ['disable_nacl==0 and disable_nacl_untrusted==0', { 'targets': [ { 'target_name': 'ipc_nacl', 'type': 'none', 'variables': { 'ipc_target': 1, 'nacl_untrusted_build': 1, 'nlib_target': 'libipc_nacl.a', 'build_glibc': 0, 'build_newlib': 0, 'build_irt': 1, }, 'dependencies': [ '../base/base_nacl.gyp:base_nacl', '../native_client/tools.gyp:prep_toolchain', ], }, { 'target_name': 'ipc_nacl_nonsfi', 'type': 'none', 'variables': { 'ipc_target': 1, 'nacl_untrusted_build': 1, 'nlib_target': 'libipc_nacl_nonsfi.a', 'build_glibc': 0, 'build_newlib': 0, 'build_irt': 0, 'build_pnacl_newlib': 0, 'build_nonsfi_helper': 1, # Use linux IPC channel implementation for nacl_helper_nonsfi, # instead of NaCl's IPC implementation (ipc_channel_nacl.cc), # because nacl_helper_nonsfi will be running directly on Linux. # ipc_channel_nacl.cc is excluded below. 'sources': [ 'ipc_channel.cc', 'ipc_channel_posix.cc', ], }, 'sources!': [ 'ipc_channel_nacl.cc', ], 'dependencies': [ '../base/base_nacl.gyp:base_nacl_nonsfi', '../native_client/tools.gyp:prep_toolchain', ], }, ], }], ], }
/** * Generates a visualized object between the two corners and destroys the source * * @param player player * @return Rendered object */ public Selection renderAndDestroy(Player player) { if (!this.manager.getWorldEditController().getLeftClickLocation(player).isPresent() || !this.manager.getWorldEditController().getRightClickLocation(player).isPresent()) return null; return this.render(player, this.manager.getWorldEditController().<Location, Player>getLeftClickLocation(player).get(), this.manager.getWorldEditController().<Location, Player>getRightClickLocation(player).get(), true); }
def read(self, split=None, read_options={}): if self.splits and split is None: raise ValueError( "The training dataset has splits, please specify the split you want to read" ) return self._training_dataset_engine.read(self, split, read_options)
<reponame>Pintulalmeena/Projects 14 uid=311598 27 mtime=1430738578.001251 27 atime=1430738578.000251
<reponame>Mike-Neto/json-api-rs<filename>src/value/collections/map.rs //! A hash map implementation with consistent ordering. //! //! The types in this module are commonly used as the underlying data structure //! of arbitrary objects found in JSON API data. use std::fmt::{self, Debug, Formatter}; use std::hash::Hash; use std::iter::FromIterator; use std::ops::RangeFull; use ordermap::{self, OrderMap}; use serde::de::{Deserialize, Deserializer}; use serde::ser::{Serialize, Serializer}; use crate::value::collections::Equivalent; use crate::value::{Key, Value}; /// A hash map implementation with consistent ordering. #[derive(Clone, Eq, PartialEq)] pub struct Map<K = Key, V = Value> where K: Eq + Hash, { inner: OrderMap<K, V>, } impl<K, V> Map<K, V> where K: Eq + Hash, { /// Creates an empty `Map`. /// /// # Example /// /// ``` /// # extern crate json_api; /// # /// # fn main() { /// use json_api::value::{Key, Map, Value}; /// let mut map = Map::<Key, Value>::new(); /// # } /// ``` pub fn new() -> Self { Default::default() } /// Creates a new empty `Map`, with specified capacity. /// /// # Example /// /// ``` /// # extern crate json_api; /// # /// # use json_api::Error; /// # use json_api::value::Map; /// # /// # fn example() -> Result<(), Error> { /// let mut map = Map::with_capacity(2); /// /// map.insert("x", 1); /// map.insert("y", 2); /// /// // The next insert will likely require reallocation... /// map.insert("z", 3); /// # /// # Ok(()) /// # } /// # /// # fn main() { /// # example().unwrap(); /// # } /// ``` pub fn with_capacity(capacity: usize) -> Self { let inner = OrderMap::with_capacity(capacity); Map { inner } } /// Returns the number of key-value pairs the map can hold without /// reallocating. /// /// # Example /// /// ``` /// # extern crate json_api; /// # /// # use json_api::value::{Key, Map, Value}; /// # /// # fn main() { /// let map = Map::<Key, Value>::with_capacity(2); /// assert!(map.capacity() >= 2); /// # } /// ``` pub fn capacity(&self) -> usize { self.inner.capacity() } /// Clears the map, removing all key-value pairs. Keeps the allocated memory /// for reuse. /// /// # Example /// /// ``` /// # extern crate json_api; /// # /// # use json_api::value::Map; /// # /// # fn main() { /// let mut map = Map::new(); /// /// map.insert("x", 1); /// map.clear(); /// assert!(map.is_empty()); /// # } /// ``` pub fn clear(&mut self) { self.inner.clear(); } /// Returns true if the map contains a value for the specified key. /// /// # Example /// /// ``` /// # extern crate json_api; /// # /// # use json_api::value::Map; /// # /// # fn main() { /// let mut map = Map::new(); /// /// map.insert(1, "a"); /// assert_eq!(map.contains_key(&1), true); /// assert_eq!(map.contains_key(&2), false); /// # } /// ``` pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool where Q: Equivalent<K> + Hash, { self.inner.contains_key(key) } /// Clears the map, returning all key-value pairs as an iterator. Keeps the /// allocated memory for reuse. /// /// # Example /// /// ``` /// # extern crate json_api; /// # /// # use json_api::value::Map; /// # /// # fn main() { /// let mut map = Map::new(); /// /// map.insert("x", 1); /// map.insert("y", 2); /// /// for (key, value) in map.drain(..) { /// assert!(key == "x" || key == "y"); /// assert!(value == 1 || value == 2); /// } /// /// assert!(map.is_empty()); /// # } /// ``` pub fn drain(&mut self, range: RangeFull) -> Drain<K, V> { let iter = self.inner.drain(range); Drain { iter } } /// Returns a reference to the value corresponding to the key. /// /// # Example /// /// ``` /// # extern crate json_api; /// # /// # use json_api::value::Map; /// # /// # fn main() { /// let mut map = Map::new(); /// /// map.insert("x", 1); /// /// assert_eq!(map.get("x"), Some(&1)); /// assert_eq!(map.get("y"), None); /// # } /// ``` pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V> where Q: Equivalent<K> + Hash, { self.inner.get(key) } /// Inserts a key-value pair into the map. /// /// If a value already existed for key, that old value is returned in /// `Some`; otherwise, `None` is returned. /// /// # Example /// /// ``` /// # extern crate json_api; /// # /// # use json_api::value::Map; /// # /// # fn main() { /// let mut map = Map::new(); /// /// assert_eq!(map.insert("x", 1), None); /// assert_eq!(map.insert("x", 2), Some(1)); /// # } /// ``` pub fn insert(&mut self, key: K, value: V) -> Option<V> { self.inner.insert(key, value) } /// Return an iterator visiting all the key-value pairs of the map in the /// order in which they were inserted. /// /// # Example /// /// ``` /// # extern crate json_api; /// # /// # use json_api::value::Map; /// # /// # fn main() { /// let mut map = Map::new(); /// /// map.insert("a", 1); /// map.insert("b", 2); /// map.insert("c", 3); /// /// for (key, value) in map.iter() { /// println!("key: {} value: {}", key, value); /// } /// # } /// ``` pub fn iter(&self) -> Iter<K, V> { let iter = self.inner.iter(); Iter { iter } } /// Return an iterator visiting all the key-value pairs of the map in the /// order in which they were inserted, with mutable references to the /// values. /// /// # Example /// /// ``` /// # extern crate json_api; /// # /// # use json_api::value::Map; /// # /// # fn main() { /// let mut map = Map::new(); /// /// map.insert("a", 1); /// map.insert("b", 2); /// map.insert("c", 3); /// /// for (_, value) in map.iter_mut() { /// *value += 1; /// } /// /// for (key, value) in &map { /// println!("key: {} value: {}", key, value); /// } /// # } /// ``` pub fn iter_mut(&mut self) -> IterMut<K, V> { let iter = self.inner.iter_mut(); IterMut { iter } } /// Return an iterator visiting all keys in the order in which they were /// inserted. /// /// # Example /// /// ``` /// # extern crate json_api; /// # /// # use json_api::value::Map; /// # /// # fn main() { /// let mut map = Map::new(); /// /// map.insert("a", 1); /// map.insert("b", 2); /// map.insert("c", 3); /// /// for key in map.keys() { /// println!("{}", key); /// } /// # } /// ``` pub fn keys(&self) -> Keys<K, V> { let iter = self.inner.keys(); Keys { iter } } /// Return the number of key-value pairs in the map. /// /// # Example /// /// ``` /// # extern crate json_api; /// # /// # use json_api::value::Map; /// # /// # fn main() { /// let mut map = Map::new(); /// assert_eq!(map.len(), 0); /// /// map.insert("x", 1); /// assert_eq!(map.len(), 1); /// # } /// ``` pub fn len(&self) -> usize { self.inner.len() } /// Returns true if the map contains no elements. /// /// # Example /// /// ``` /// # extern crate json_api; /// # /// # use json_api::value::Map; /// # /// # fn main() { /// let mut map = Map::new(); /// assert!(map.is_empty()); /// /// map.insert("x", 1); /// assert!(!map.is_empty()); /// # } /// ``` pub fn is_empty(&self) -> bool { self.len() == 0 } /// Removes a key from the map, returning the value at the key if the key /// was previously in the map. /// /// # Example /// /// ``` /// # extern crate json_api; /// # /// # use json_api::value::Map; /// # /// # fn main() { /// let mut map = Map::new(); /// /// map.insert("x", 1); /// /// assert_eq!(map.remove("x"), Some(1)); /// assert_eq!(map.remove("x"), None); /// # } /// ``` pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V> where Q: Equivalent<K> + Hash, { self.inner.remove(key) } /// Reserves capacity for at least additional more elements to be inserted /// in the `Map`. The collection may reserve more space to avoid frequent /// reallocations. /// /// # Note /// /// This method has yet to be fully implemented in the [`ordermap`] crate. /// /// # Example /// /// ``` /// # extern crate json_api; /// # /// # use json_api::value::{Key, Map, Value}; /// # /// # fn main() { /// let mut map = Map::<Key, Value>::new(); /// map.reserve(10); /// # } /// ``` /// /// [`ordermap`]: https://docs.rs/ordermap pub fn reserve(&mut self, additional: usize) { self.inner.reserve(additional); } /// Return an iterator visiting all values in the order in which they were /// inserted. /// /// # Example /// /// ``` /// # extern crate json_api; /// # /// # use json_api::value::Map; /// # /// # fn main() { /// let mut map = Map::new(); /// /// map.insert("a", 1); /// map.insert("b", 2); /// map.insert("c", 3); /// /// for value in map.values() { /// println!("{}", value); /// } /// # } /// ``` pub fn values(&self) -> Values<K, V> { let iter = self.inner.values(); Values { iter } } /// Return an iterator visiting all values mutably in the order in which /// they were inserted. /// /// # Example /// /// ``` /// # extern crate json_api; /// # /// # use json_api::value::Map; /// # /// # fn main() { /// let mut map = Map::new(); /// /// map.insert("a", 1); /// map.insert("b", 2); /// map.insert("c", 3); /// /// for value in map.values_mut() { /// *value += 1; /// } /// /// for value in map.values() { /// println!("{}", value); /// } /// # } pub fn values_mut(&mut self) -> ValuesMut<K, V> { let iter = self.inner.values_mut(); ValuesMut { iter } } } impl<K, V> Debug for Map<K, V> where K: Debug + Eq + Hash, V: Debug, { fn fmt(&self, f: &mut Formatter) -> fmt::Result { f.debug_map().entries(self).finish() } } impl<K, V> Default for Map<K, V> where K: Eq + Hash, { fn default() -> Self { let inner = Default::default(); Map { inner } } } impl<K, V> Extend<(K, V)> for Map<K, V> where K: Eq + Hash, { fn extend<I>(&mut self, iter: I) where I: IntoIterator<Item = (K, V)>, { self.inner.extend(iter); } } impl<K, V> FromIterator<(K, V)> for Map<K, V> where K: Eq + Hash, { fn from_iter<I>(iter: I) -> Self where I: IntoIterator<Item = (K, V)>, { let inner = OrderMap::from_iter(iter); Map { inner } } } impl<K, V> IntoIterator for Map<K, V> where K: Eq + Hash, { type Item = (K, V); type IntoIter = IntoIter<K, V>; fn into_iter(self) -> Self::IntoIter { let iter = self.inner.into_iter(); IntoIter { iter } } } impl<'a, K, V> IntoIterator for &'a Map<K, V> where K: Eq + Hash, { type Item = (&'a K, &'a V); type IntoIter = Iter<'a, K, V>; fn into_iter(self) -> Self::IntoIter { self.iter() } } impl<'a, K, V> IntoIterator for &'a mut Map<K, V> where K: Eq + Hash, { type Item = (&'a K, &'a mut V); type IntoIter = IterMut<'a, K, V>; fn into_iter(self) -> Self::IntoIter { self.iter_mut() } } impl<'de, K, V> Deserialize<'de> for Map<K, V> where K: Deserialize<'de> + Eq + Hash, V: Deserialize<'de>, { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { OrderMap::deserialize(deserializer).map(|inner| Map { inner }) } } impl<K, V> Serialize for Map<K, V> where K: Eq + Hash + Serialize, V: Serialize, { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { self.inner.serialize(serializer) } } /// A draining iterator over the entries of a `Map`. pub struct Drain<'a, K: 'a, V: 'a> { iter: ordermap::Drain<'a, K, V>, } impl<'a, K, V> Iterator for Drain<'a, K, V> { type Item = (K, V); fn next(&mut self) -> Option<Self::Item> { self.iter.next() } fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } } /// An iterator over the entries of a `Map`. pub struct Iter<'a, K: 'a, V: 'a> { iter: ordermap::Iter<'a, K, V>, } impl<'a, K, V> Iterator for Iter<'a, K, V> { type Item = (&'a K, &'a V); fn next(&mut self) -> Option<Self::Item> { self.iter.next() } fn count(self) -> usize { self.iter.len() } fn last(mut self) -> Option<Self::Item> { self.next_back() } fn nth(&mut self, n: usize) -> Option<Self::Item> { self.iter.nth(n) } fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } } impl<'a, K, V> DoubleEndedIterator for Iter<'a, K, V> { fn next_back(&mut self) -> Option<Self::Item> { self.iter.next_back() } } impl<'a, K, V> ExactSizeIterator for Iter<'a, K, V> { fn len(&self) -> usize { self.iter.len() } } /// An mutable iterator over the entries of a `Map`. pub struct IterMut<'a, K: 'a, V: 'a> { iter: ordermap::IterMut<'a, K, V>, } impl<'a, K, V> Iterator for IterMut<'a, K, V> { type Item = (&'a K, &'a mut V); fn next(&mut self) -> Option<Self::Item> { self.iter.next() } fn count(self) -> usize { self.iter.len() } fn last(mut self) -> Option<Self::Item> { self.next_back() } fn nth(&mut self, n: usize) -> Option<Self::Item> { self.iter.nth(n) } fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } } impl<'a, K, V> DoubleEndedIterator for IterMut<'a, K, V> { fn next_back(&mut self) -> Option<Self::Item> { self.iter.next_back() } } impl<'a, K, V> ExactSizeIterator for IterMut<'a, K, V> { fn len(&self) -> usize { self.iter.len() } } /// An owning iterator over the entries of a `Map`. pub struct IntoIter<K, V> { iter: ordermap::IntoIter<K, V>, } impl<K, V> Iterator for IntoIter<K, V> { type Item = (K, V); fn next(&mut self) -> Option<Self::Item> { self.iter.next() } fn count(self) -> usize { self.iter.len() } fn last(mut self) -> Option<Self::Item> { self.next_back() } fn nth(&mut self, n: usize) -> Option<Self::Item> { self.iter.nth(n) } fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } } impl<K, V> DoubleEndedIterator for IntoIter<K, V> { fn next_back(&mut self) -> Option<Self::Item> { self.iter.next_back() } } impl<K, V> ExactSizeIterator for IntoIter<K, V> { fn len(&self) -> usize { self.iter.len() } } /// An iterator over the keys of a `Map`. pub struct Keys<'a, K: 'a, V: 'a> { iter: ordermap::Keys<'a, K, V>, } impl<'a, K, V> Iterator for Keys<'a, K, V> { type Item = &'a K; fn next(&mut self) -> Option<Self::Item> { self.iter.next() } fn count(self) -> usize { self.iter.len() } fn last(mut self) -> Option<Self::Item> { self.next_back() } fn nth(&mut self, n: usize) -> Option<Self::Item> { self.iter.nth(n) } fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } } impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> { fn next_back(&mut self) -> Option<Self::Item> { self.iter.next_back() } } impl<'a, K, V> ExactSizeIterator for Keys<'a, K, V> { fn len(&self) -> usize { self.iter.len() } } /// An iterator over the values of a `Map`. pub struct Values<'a, K: 'a, V: 'a> { iter: ordermap::Values<'a, K, V>, } impl<'a, K, V> Iterator for Values<'a, K, V> { type Item = &'a V; fn next(&mut self) -> Option<Self::Item> { self.iter.next() } fn count(self) -> usize { self.iter.len() } fn last(mut self) -> Option<Self::Item> { self.next_back() } fn nth(&mut self, n: usize) -> Option<Self::Item> { self.iter.nth(n) } fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } } impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> { fn next_back(&mut self) -> Option<Self::Item> { self.iter.next_back() } } impl<'a, K, V> ExactSizeIterator for Values<'a, K, V> { fn len(&self) -> usize { self.iter.len() } } /// A mutable iterator over the values of a `Map`. pub struct ValuesMut<'a, K: 'a, V: 'a> { iter: ordermap::ValuesMut<'a, K, V>, } impl<'a, K, V> Iterator for ValuesMut<'a, K, V> { type Item = &'a mut V; fn next(&mut self) -> Option<Self::Item> { self.iter.next() } fn count(self) -> usize { self.iter.len() } fn last(mut self) -> Option<Self::Item> { self.next_back() } fn nth(&mut self, n: usize) -> Option<Self::Item> { self.iter.nth(n) } fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } } impl<'a, K, V> DoubleEndedIterator for ValuesMut<'a, K, V> { fn next_back(&mut self) -> Option<Self::Item> { self.iter.next_back() } } impl<'a, K, V> ExactSizeIterator for ValuesMut<'a, K, V> { fn len(&self) -> usize { self.iter.len() } }
/** * Change the inventory source (dangerous). * * @param source new inventory source * @return this SettingsBuilder. * @see Settings.InventorySettings#source */ public SettingsBuilder inventorySource(String source) { inventorySource = source; return this; }
<gh_stars>10-100 import { ethers } from "ethers"; import { Contract } from "./Contract"; import { Sep20 } from "./Sep20"; import { RegTestSmartBchWallet } from "./SmartBchWallet"; describe(`Test Ethereum functions`, () => { test.skip("Test eth mainnet contract", async () => { const abi = Sep20.abi; const contract = new Contract( "0xdac17f958d2ee523a2206206994597c13d831ec7", // tether usd abi, "EthMainnet" as any ); // const balance: ethers.BigNumber = await contract.balanceOf( // "0x227F0226499E308769478669669CbdCf4E7dA002" // tether usd deployer address // ); // expect(balance.toNumber()).toBeGreaterThanOrEqual(0); // const contractId = contract.toString(); // const cont = Contract.fromId(contractId); // delete (cont as any).provider; // delete (cont as any).contract; // delete (contract as any).provider; // delete (contract as any).contract; // expect(JSON.stringify(cont)).toEqual(JSON.stringify(contract)); // console.log(contract.contract.filters.Transfer(null, null)) // console.log(await contract.provider.getLogs(contract.contract.filters.Transfer(null, null))) console.log( await contract.provider.getLogs({ // address: '0xdac17f958d2ee523a2206206994597c13d831ec7', fromBlock: 0xa3b631, topics: [ "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", null, "0x000000000000000000000000b55438d2261c9dfa801848c89377d77fa35a1917", ], }) ); }); test("Test deploying contract, getting gas estimates and invoking methods", async () => { const script = Sep20.script; const wallet = await RegTestSmartBchWallet.fromId( process.env.SBCH_ALICE_ID! ); const contract = await Contract.deploy( wallet, script, "Mainnet Coin", "MNC", 8, 1000000000, wallet.getDepositAddress(), wallet.getDepositAddress(), undefined === true, { gasPrice: 10 ** 10, } ); const totalSupply: ethers.BigNumber = await contract.totalSupply(); expect(totalSupply.toNumber()).toBeGreaterThanOrEqual(0); const constGas = await contract.estimateGas("decimals"); expect(constGas).toStrictEqual(ethers.BigNumber.from(0)); let constReply = await contract.runFunctionFromStrings({ function: "decimals", }); expect(constReply.result).toBe(8); let constReply2 = await contract.decimals(); expect(constReply2).toBeDefined(); expect(constReply.result).toStrictEqual(constReply2); const to = contract.getDepositAddress(); const value = 10000; const overrides = { gasPrice: 10 ** 10 }; const txGas = await contract.estimateGas("transfer", to, value, overrides); expect(txGas.toNumber()).toBeGreaterThan(0); const txReply = await contract.runFunctionFromStrings({ function: "transfer", arguments: [to, value], overrides: overrides, }); expect(txReply.txId!.length).toBe(66); expect(txReply.receipt!.transactionHash.length).toBe(66); }); });
package com.g2forge.enigma.bash.model.statement.redirect; import org.junit.Test; import com.g2forge.alexandria.test.HAssert; import com.g2forge.enigma.bash.convert.BashRenderer; import com.g2forge.enigma.bash.model.BashScript; import com.g2forge.enigma.bash.model.statement.BashCommand; import com.g2forge.enigma.bash.model.statement.redirect.BashRedirectHereString; import com.g2forge.enigma.bash.model.statement.redirect.BashRedirection; public class TestBashRedirectHereString { @Test public void other() { HAssert.assertEquals("#!/bin/bash\ncat 3<<< Hello\n", new BashRenderer().render(new BashScript(BashRedirection.builder().executable(new BashCommand("cat")).redirect(new BashRedirectHereString(3, "Hello")).build()))); } @Test public void std() { HAssert.assertEquals("#!/bin/bash\ncat <<< Hello\n", new BashRenderer().render(new BashScript(BashRedirection.builder().executable(new BashCommand("cat")).redirect(new BashRedirectHereString("Hello")).build()))); } }
#!/usr/bin/env python # coding: utf-8 # In[1]: ''' All labeled videos in PA-HMDB51 are used as testing set. The rest videos in HMDB51 are used as training set. This script gets the file names of PA_HMDB51 dataset. ''' import numpy as np import matplotlib.pyplot as plt plt.style.use(['/Users/wuzhenyu/.matplotlib/stylelib/science.mplstyle', '/Users/wuzhenyu/.matplotlib/stylelib/ieee.mplstyle']) import json, os, csv import matplotlib as mpl # mpl.rcParams['text.usetex'] = True # mpl.rcParams['text.latex.preamble'] = [r'\usepackage{amsmath}'] # font = {'family': 'Times New Roman', # 'color': 'black', # 'weight': 'semibold', # 'size': 24, # } from calculate_statistics import attribute_list, attribute_value_dict attr_list = [attr.replace('_', ' ') for attr in attribute_list] attr_value_dict = {k.replace('_', ' '):v for k,v in attribute_value_dict.items()} attr_value_num = json.load(open(os.path.join("attr_value_num.json"))) attr_value_num = {k.replace('_', ' '):v for k,v in attr_value_num.items()} skin_color_lst = attr_value_num['skin color'] attr_value_num['skin color'] = [skin_color_lst[0], skin_color_lst[1], skin_color_lst[2], skin_color_lst[3], sum(skin_color_lst[-3:])] print(attr_value_dict) print(attr_value_num) # In[2]: # construct attribute_value_num_mat: attr_value_num_mat = np.zeros((5,5)) # all initialized as 0. for i in range(5): each_attr_value_num = attr_value_num[attr_list[i]] print(each_attr_value_num, np.sum(each_attr_value_num)) attr_value_num_mat[i,0:len(each_attr_value_num)] = each_attr_value_num print('attribute_value_num_mat:\n', attr_value_num_mat) print(np.sum(attr_value_num_mat, axis=1)) # In[4]: def plot_attribute_distribution(): ''' Plot privacy attribut - Number of Frames (i.e., Fig 5 in camera ready version) ''' plt.figure(figsize=(16, 12)) colors = ['r', 'g', 'b', 'm'] # plot: for j in range(4): if j == 0: plt.bar(range(5), attr_value_num_mat[:,j], label=j, tick_label=attr_list, fc=colors[j], width=0.4) else: plt.bar(range(5), attr_value_num_mat[:,j], bottom=np.sum(attr_value_num_mat[:,0:j], axis=1), label=j, tick_label=attr_list, fc=colors[j], width=0.4) plt.tick_params(labelsize=fontsize_ticks) plt.ylim(0,65000) font = {'family': 'Times New Roman', 'color': 'black', 'weight': 'semibold', 'size': fontsize_axis_labels, } plt.xlabel('Privacy Attribute', fontdict=font) plt.ylabel('Number of Frames', fontdict=font) plt.legend(prop={'size': fontsize_legend}, ncol=4, loc='upper center', framealpha=0.9) plt.gcf().subplots_adjust(left=0.12, right=0.96, top=0.98, bottom=0.08) plt.savefig('attribute_distribution.pdf',bbox_inches="tight", pad_inches=0) # In[16]: def plot_attribute_distribution_transposed(): category_names = ['$\\bf{0}$', '$\\bf{1}$', '$\\bf{2}$', '$\\bf{3}$', '$\\bf{4}$'] results = { '$\\bf{SC}$': list(attr_value_num_mat[0]), '$\\bf{RL}$': list(attr_value_num_mat[1]), '$\\bf{FC}$': list(attr_value_num_mat[2]), '$\\bf{ND}$': list(attr_value_num_mat[3]), '$\\bf{GR}$': list(attr_value_num_mat[4]) } labels = list(results.keys()) data = np.array(list(results.values())) data_cum = data.cumsum(axis=1) category_colors = ['red', 'green', 'blue', 'orange', 'black'] fig, ax = plt.subplots(figsize=(10, 4)) ax.invert_yaxis() ax.xaxis.set_visible(False) ax.set_xlim(0, np.sum(data, axis=1).max()) for i, (colname, color) in enumerate(zip(category_names, category_colors)): widths = data[:, i] starts = data_cum[:, i] - widths ax.barh(labels, widths, left=starts, height=0.75, label=colname, color=color, edgecolor='k', linewidth=1.4) xcenters = starts + widths / 2 for y, (x, c) in enumerate(zip(xcenters, widths)): print(y) print(x,c) ratio = float(c) / 52413.0 if ratio > 1e-5: round_ratio = round(ratio*100) digit = round_ratio % 10 tens = round_ratio // 10 if tens > 0: ax.text(x, y, r'$\boldsymbol{}\boldsymbol{}$'.format(tens, digit), ha='center', va='center', color='w', fontsize=22) else: ax.text(x, y, r'$\boldsymbol{}$'.format(digit), ha='center', va='center', color='w', fontsize=22) ax.legend(ncol=len(category_names), bbox_to_anchor=(0.5, 1.05), loc='center', fontsize=20, frameon=False) ax.tick_params(labelsize=24, which='both', axis='y', length=0) plt.savefig('attributes_distribution.pdf', bbox_inches="tight", pad_inches=0) if __name__ == '__main__': # plot_attribute_distribution() plot_attribute_distribution_transposed()
<gh_stars>0 import { DiscoveryService } from '@golevelup/nestjs-discovery' import { Injectable, Logger, OnModuleInit } from '@nestjs/common' import { ModuleRef } from '@nestjs/core' import { AmqpConnectionManager } from 'amqp-connection-manager' import { PUBLISH_EXCHANGE_CONTEXT_METADATA_TOKEN, PUBLISH_EXCHANGE_METADATA_TOKEN, PUBLISH_EXCHANGE_PRODUCER_METADATA_TOKEN, PUBLISH_QUEUE_CONTEXT_METADATA_TOKEN, PUBLISH_QUEUE_METADATA_TOKEN, PUBLISH_QUEUE_PRODUCER_METADATA_TOKEN, SUBSCRIBE_QUEUE_CONSUME_OPTIONS_METADATA_TOKEN, SUBSCRIBE_QUEUE_CONSUMER_METADATA_TOKEN, SUBSCRIBE_QUEUE_CONTEXT_METADATA_TOKEN, SUBSCRIBE_QUEUE_METADATA_TOKEN, USE_AMQP_CONNECTION_TOKEN, SUBSCRIBE_EXCHANGE_CONSUMER_METADATA_TOKEN, SUBSCRIBE_EXCHANGE_CONTEXT_METADATA_TOKEN, SUBSCRIBE_EXCHANGE_OPTIONS_METADATA_TOKEN, SUBSCRIBE_EXCHANGE_QUEUE_OPTIONS_METADATA_TOKEN, } from './amqp.constants' import { Exchange, ConsumeExchangeOptions } from './interfaces/exchange' import { ConsumeQueueOptions, Queue } from './interfaces/queue' import { QueueConsumer } from './services/queue-consumer' import { ExchangeProducer } from './services/exchange-producer' import { QueueProducer } from './services/queue-producer' import { getAMQPConnectionToken } from './shared/token.util' import { ExchangeConsumer } from './services/exchange-consumer' @Injectable() export class AMQPExplorer implements OnModuleInit { private readonly logger = new Logger(AMQPExplorer.name) constructor(private readonly moduleRef: ModuleRef, private readonly discoveryService: DiscoveryService) {} async onModuleInit() { await this.explore() } async explore() { await this.registerPublishQueueMethods() await this.registerPublishExchangeMethods() await this.registerSubscribeQueueMethods() await this.registerSubscribeExchangeMethods() } /** * @desc discover all providers' method with `@PublishQueue`, create producer instance * */ private async registerPublishQueueMethods() { /** scan all `@PublishQueue` methods */ const publishQueueMethods = await this.discoveryService.providerMethodsWithMetaAtKey(PUBLISH_QUEUE_METADATA_TOKEN) /** create all queue producer with spec connection if have `@UseConnection` */ for (const method of publishQueueMethods) { const originalHandler = method.discoveredMethod.handler const connectionName = Reflect.getMetadata(USE_AMQP_CONNECTION_TOKEN, originalHandler) const injectConnectionToken = getAMQPConnectionToken(connectionName) const connection: AmqpConnectionManager = this.moduleRef.get<AmqpConnectionManager>(injectConnectionToken) const queue: Queue = Reflect.getMetadata(PUBLISH_QUEUE_METADATA_TOKEN, originalHandler) const handlerContext = method.discoveredMethod.parentClass.instance const producer = new QueueProducer(connection, queue) await producer.onModuleInit() Reflect.defineMetadata(PUBLISH_QUEUE_PRODUCER_METADATA_TOKEN, producer, originalHandler) Reflect.defineMetadata(PUBLISH_QUEUE_CONTEXT_METADATA_TOKEN, handlerContext, originalHandler) this.logger.log( `Found ${method.discoveredMethod.parentClass.name}#${method.discoveredMethod.methodName} using @PublishQueue()` ) } } private async registerPublishExchangeMethods() { const publishExchangeMethods = await this.discoveryService.providerMethodsWithMetaAtKey( PUBLISH_EXCHANGE_METADATA_TOKEN ) for (const method of publishExchangeMethods) { const originalHandler = method.discoveredMethod.handler const connectionName = Reflect.getMetadata(USE_AMQP_CONNECTION_TOKEN, originalHandler) const injectConnectionToken = getAMQPConnectionToken(connectionName) const connection: AmqpConnectionManager = this.moduleRef.get<AmqpConnectionManager>(injectConnectionToken) const exchange: Exchange = Reflect.getMetadata(PUBLISH_EXCHANGE_METADATA_TOKEN, originalHandler) const handlerContext = method.discoveredMethod.parentClass.instance const producer = new ExchangeProducer(connection, exchange) await producer.onModuleInit() Reflect.defineMetadata(PUBLISH_EXCHANGE_PRODUCER_METADATA_TOKEN, producer, originalHandler) Reflect.defineMetadata(PUBLISH_EXCHANGE_CONTEXT_METADATA_TOKEN, handlerContext, originalHandler) this.logger.log( `Found ${method.discoveredMethod.parentClass.name}#${method.discoveredMethod.methodName} using @PublishExchange()` ) } } private async registerSubscribeQueueMethods() { const subscribeQueueMethods = await this.discoveryService.providerMethodsWithMetaAtKey( SUBSCRIBE_QUEUE_METADATA_TOKEN ) for (const method of subscribeQueueMethods) { const originalHandler = method.discoveredMethod.handler const connectionName = Reflect.getMetadata(USE_AMQP_CONNECTION_TOKEN, originalHandler) const injectConnectionToken = getAMQPConnectionToken(connectionName) const connection: AmqpConnectionManager = this.moduleRef.get<AmqpConnectionManager>(injectConnectionToken) const queue: Queue = Reflect.getMetadata(SUBSCRIBE_QUEUE_METADATA_TOKEN, originalHandler) const consumeOptions: ConsumeQueueOptions = Reflect.getMetadata( SUBSCRIBE_QUEUE_CONSUME_OPTIONS_METADATA_TOKEN, originalHandler ) const handlerContext = method.discoveredMethod.parentClass.instance const consumer = new QueueConsumer(connection, queue, consumeOptions) await consumer.applyHandler(originalHandler) await consumer.applyContext(handlerContext) Reflect.defineMetadata(SUBSCRIBE_QUEUE_CONSUMER_METADATA_TOKEN, consumer, originalHandler) Reflect.defineMetadata(SUBSCRIBE_QUEUE_CONTEXT_METADATA_TOKEN, handlerContext, originalHandler) this.logger.log( `Found ${method.discoveredMethod.parentClass.name}#${method.discoveredMethod.methodName} using @SubscribeQueue()` ) await consumer.listen() } } private async registerSubscribeExchangeMethods() { const subscribeExchangeMethods = await this.discoveryService.providerMethodsWithMetaAtKey( SUBSCRIBE_EXCHANGE_OPTIONS_METADATA_TOKEN ) for (const method of subscribeExchangeMethods) { const originalHandler = method.discoveredMethod.handler const connectionName = Reflect.getMetadata(USE_AMQP_CONNECTION_TOKEN, originalHandler) const injectConnectionToken = getAMQPConnectionToken(connectionName) const connection: AmqpConnectionManager = this.moduleRef.get<AmqpConnectionManager>(injectConnectionToken) const queueOptions: ConsumeQueueOptions = Reflect.getMetadata( SUBSCRIBE_EXCHANGE_QUEUE_OPTIONS_METADATA_TOKEN, originalHandler ) const exchangeOptions: ConsumeExchangeOptions = Reflect.getMetadata( SUBSCRIBE_EXCHANGE_OPTIONS_METADATA_TOKEN, originalHandler ) const handlerContext = method.discoveredMethod.parentClass.instance const consumer = new ExchangeConsumer(connection, exchangeOptions, queueOptions) await consumer.applyHandler(originalHandler) await consumer.applyContext(handlerContext) Reflect.defineMetadata(SUBSCRIBE_EXCHANGE_CONSUMER_METADATA_TOKEN, consumer, originalHandler) Reflect.defineMetadata(SUBSCRIBE_EXCHANGE_CONTEXT_METADATA_TOKEN, handlerContext, originalHandler) this.logger.log( `Found ${method.discoveredMethod.parentClass.name}#${method.discoveredMethod.methodName} using @SubscribeExchange()` ) await consumer.listen() } } }
/** * Determine if MobileDirectory should use mock data sources * * @return True if MobileDirectory should use mock data sources */ public boolean isMocking() { boolean res = getIsMocking(); Log.d(C.TAG, "Using mock data: " + res); return res; }
from autoarray.util import array_util as array from autoarray.util import binning_util as binning from autoarray.util import fit_util as fit from autoarray.util import grid_util as grid from autoarray.util import mask_util as mask from autoarray.util import sparse_util as sparse from autoarray.util import pixelization_util as pixelization from autoarray.util import regularization_util as regularization from autoarray.util import mapper_util as mapper from autoarray.util import inversion_util as inversion from autoarray.util import transformer_util as transformer from ..util import cosmology_util as cosmology
/** * Add a single card to this set. The hand parser will keep track of the suit and value. * * @param card */ public void addCard(final Card card) { final int suit = card.getSuit().ordinal(); final int height = card.getHeight().ordinal(); decks[suit][height]++; suitCount[suit]++; valueCount[height]++; }
**Begin Reading** Table of Contents A Preview of _Murder in the House of Angels_ Copyright Page In accordance with the U.S. Copyright Act of 1976, the scanning, uploading, and electronic sharing of any part of this book without the permission of the publisher constitute unlawful piracy and theft of the author's intellectual property. If you would like to use material from the book (other than for review purposes), prior written permission must be obtained by contacting the publisher at [email protected]. Thank you for your support of the author's rights. Many thanks to Gabrielle Charbonnet, my coconspirator, who flies high and cracks wise # To the Reader THE IDEA FOR the Maximum Ride series comes from earlier books of mine called _When the Wind Blows_ and _The Lake House_ , which also feature a character named Max who escapes from a quite despicable School. Most of the similarities end there. Max and the other kids in the Maximum Ride books are not the same Max and kids featured in those two books. Nor do Frannie and Kit play any part in the series. I hope you enjoy the ride anyway. # Prologue ## AFTER # _IT WAS NIGHT, and Angel was perched on the hot surface of the scorched rock cliff. Her wings were spread out behind her, her ravaged legs swinging into nothingness, her ears straining in the strange new silence._ _It seemed wrong, this silence. Shouldn't there be the din of destruction thundering around her? The crash of buildings sinking into rubble? Inconsolable wails mourning all that was lost? That the world as they'd known it had gone so quietly, slipping into the ether like an old, beaten dog, was disconcerting, to say the least. Wasn't noise what the apocalypse was supposed to be about?_ _Where was the chaos?_ _But there had been chaos, Angel reminded herself. Before. There had been plenty of screaming, fire and brimstone, and panic. She had endured enough panic to last her a lifetime._ _Angel hugged her knees to her chest and folded her dingy white wings around herself, cocoon-like. She traced her fingers along her scars and fought back the memories._ _Despite the warnings from nature—the earthquakes, the floods—despite all the efforts of science—Angel winced,remembering the scalpels and fluorescent lightbulbs and blindingly white sheets—despite everything, in the end, the earth had been savagely claimed back for nature._ _And despite Max's missions and the flock's preparations over the years, they still hadn't been ready._ _But then, who could ever really be ready for the end of the world?_ You, _Angel whispered to herself._ You were ready. _Angel squinted into the darkness. She couldn't see anything from her night perch on the cliff, but even in the light of day, the horizon didn't look like anything familiar or natural. You didn't see what was there—you saw the spaces between._ _Watching Max fall had felt like that. Angel had imagined her grief as a blackness stretching out before her, the crushing weight of Max's death a night without stars, without hope, without end. It had terrified her so much more than the idea of Armageddon._ _The power inside her was the only thing that scared Angel now. That she had seen how it would happen. That she had known. That she hadn't told anyone._ _Angel tilted her head back to feel the chill of wind rustling her blond curls, now stringy and dirty. She listened in the silence. No whitecoats probing her, taunting her. No voices at all._ _It almost felt like she was completely and totally alone. Almost._ _Angel thought of the flock. Flying, diving together in one strong V, with Max at its center. She thought of Max holding her hand, calling Angel her baby. She wasn't a baby anymore._ _How many seven-year-olds had seen the world go up in flames?_ _Angel shut her eyes tight. She waited for the visions she had fought for so many years before coming to accept and even depend on them. But no future appeared before her._ _For the first time in her young life, Angel had no idea what would happen next._ # Book One # BEFORE # _"IN WORLDVIEW THIS morning, whole villages in the Philippines have been demolished, and hundreds are missing as typhoons triggering massive mudslides continue to wreak havoc."_ I sat at the kitchen counter, staring at the small TV. The news anchor peered out at me with grave accusation. Yep, felt like a Monday. _"On the home front, officials rush to quell pockets of unrest as a subversive new movement takes hold in the cities."_ The camera zoomed in on a glassy-eyed fanatic raving about an advanced society and how we must act now to preserve the purity of the planet. He carried a sign that read 99% IS THE FUTURE. I shivered involuntarily. The newscaster raised one perfectly groomed eyebrow and leaned forward. _"Just who—or what—is ninety-nine percent?"_ The newscaster's face, frozen in practiced concern, dissolved into static as fuzzy black lines hiccupped across the screen. I frowned and smashed a fist down on top of the set, which only resulted in setting off a series of loud, plaintive beeps. Not that it was a quiet morning to start with. Behind me in the kitchen, the usual chaos was unraveling. Iggy was slinging waffles at Gazzy and Total, who were trying to catch them in their wide-open mouths, like baby birds. How perfect. "I can't find the socks that match this skirt!" Nudge said, holding up some floaty, layer-y clothing situation. A waffle whapped her in the head, and with turbo-charged reflexes, she snatched it out of midair and hurled it back at Iggy as hard as she could. It exploded against his forehead. "Don't throw waffles at me!" she screeched. "I'm trying to get dressed!" Gazzy shot a fist into the air, his face twisted into that maniacally guilty grin that only nine-year-old angelic-looking boys seem to be able to master. "Food fi—" he began happily, only to stop at the look in my eyes. "Try it," I said with deadly calm. He sat down. "Quit throwing waffles!" I yelled, snatching the syrup bottle away from Iggy, who was aiming it at his open mouth. "Use plates! Use forks!" "But I don't have thumbs!" Total said indignantly. "Just because I can talk doesn't mean I'm _human_ ," he complained. For a small, Scotty-like dog, he had a lot of presence. "Neither are we. At least not completely." I unfolded my wings partway. Yes, folks— _wings_. In case this is your first dip into the deep end of the ol' freak-of-nature pool, I'll just put it out there: We fly. Total rolled his eyes. "Yes, Max, I am aware." He fluttered his own miniature pair of flappers. Unfortunately, his mate for life, Akila, didn't have wings, so the non-mutant Samoyed spent most of the year with her one-hundred-percent-human owner. She had a hard time keeping up with us. I shrugged. "So use a dog bowl, then." His nose twitched in distaste. "I can't find—" Nudge started again, but I held up my hand. She knew I couldn't answer complicated fashion questions. She whirled and stalked off to the bathroom to begin her twelve-step daily beauty regimen—involving many potions, lotions, and certain buffing techniques. The whole thing made my head hurt, and since Nudge was a naturally gorgeous twelve-year-old, I had no idea why she bothered. Iggy, who can't even see the TV anyway due to that tiny hitch of being blind and all, expertly manipulated the complicated wire system inside the set with one hand while the other continued to stir waffle batter. When the image was crystal clear and the monotonous beeping had ceased, he cocked his head, listening to the talking head deliver the morning doom with unbeatable pep. _"A new report has stated that steadily increasing levels of pollution in China have caused the extinction of a recordnumber of plants this year. And could the growing number of meteor showers we're experiencing require the implementation of asteroid deflection strategies? Dr. Emily Elert has some answers."_ "Lemme guess. The end of the world?" Iggy asked. I smiled. "Yeah, same old, same old." _"Next on_ In the Know _, Sharon Shattuck uncovers the truth behind the growing number of enhanced humans among us. Created for the greater good, are these genetic anomalies an advanced race or an unpredictable risk? Heroes of science or botched experiments? And what do we have to fear? Stay tuned to find out!"_ My mouth twisted in annoyance. I leaned over and snapped off the TV. It was time to get going, anyway. Why had I agreed to this again? A lot had changed for us in the past year, but one thing had remained constant, and that was my unyielding loathing for a certain activity that all "normal" kids—those with homes, parents, and a distinct lack of genetic mutations—seemed to engage in. "Okay, guys, are we ready for school?" I rubbed my hands together, trying to at least give the impression of being mildly enthusiastic. I studied the faces before me. Nudge's: excited. Iggy's: bored. Gazzy's: mischievous. Total's: furry. Someone was missing. Someone whose stupid idea this whole thing was in the first place. "Where's—?" "Present," a voice said from behind me. I whirled around and found myself face-to-face with Dylan. Actually, I had to look up slightly, since he was almost six-one to my five-nine. He gave me a slow smile and I wondered, not for the first time, how anyone could manage to look so flawless in general, let alone at buttcrack-of-dawn o'clock in the morning. "Oh, good, you're up," I said, inappropriate thoughts running around my head like squirrels on speed. "About time." I coughed. "Everyone else is ready. We were about to leave without you." "Um, Max?" Dylan said, dipping a waffle into a bowl of syrup. I looked into his Caribbean Sea–colored eyes, trying to ignore the little thrill that went through my body when I thought of the time I woke up next to those bright blues. "What?" I asked, a little too defensively. "You're in your pajamas." # "WHY ARE WE walking?" Gazzy's voice was plaintive. "We're walking because other kids walk to school," I said, _again_ , as I'd said every morning that week. "It's part of the whole being-normal experience." Next to me, Dylan smiled. "And I appreciate your sacrifice," he said. I tried to ignore his movie-star looks, with approximately zero success. Every once in a while his arm brushed mine, and each time it was like a tiny electric shock. Maybe it was a new trait he was developing, like an electric eel. (Don't laugh—stranger things have happened. Like when we bird kids developed the ability to breathe underwater.) "I'm glad we're going to school," Nudge said, as she had every morning that week. Was this normalcy—predictable patterns, the certainty of doing the same thing every day? Because if so, normalcy was about to make me freak out and start screaming. "Me, too," said Dylan. "Only for me, it's the first time, of course." Dylan's had a lot of firsts since he joined the flock, but school was something he actually _wanted_ to try. He was kind of weirdly obsessed with learning—especially anything about science. (Which I, of course, thought was totally repulsive. _Science = Wackjob Whitecoats_ in my sad and tragic life story.) "If it's your first time in school, it might as well be a schmancy joint like Newton," Gazzy said, and Dylan smiled. I had to admit, so far our school week hadn't been a complete suckfest. Would I rather be home, doing almost anything else? Yes. Of course. I'm not _nuts_. But when our mysterious billionaire BFF Nino Pierpont, who some might call our "benefactor," had offered to pay for Newton, here in mountain-licious Oregon, Dylan had made Bambi eyes at me and I had caved. Beyond the regular guilt trips from Nudge about wanting to lead a "normal" life, I felt kind of... _responsible_ for Dylan. There was so much he didn't know about surviving. He might've looked like the original teenager he was cloned from, and it was true he was a kick-butt fighter, but I had to keep reminding myself that this version had been alive only about two years. Plus, there was that whole issue of him supposedly being created especially for me. To be my "perfect other half." No pressure or anything. I thought maybe he liked me more than I liked him, but still—once someone has kissed you in the rain on top of the Arc de Triomphe in Paris at sunset, you're kind of toast. Anyway, agreeing to go to school with him—just for a while—didn't seem like that much of a big deal for me. The ratio of my discomfort to his happiness was acceptable. And because he's, you know, _perfect_ , he fit right in at school and was already super popular. Because I'm, you know, _me_ , I wasn't exactly super popular. Or popular. Or even noticed that much. Which was the whole point, right? Normalcy. "Thank you for doing this." Dylan's voice was quiet, meant just for me. I looked up at him, feeling the inevitable flush warming my cheeks. "Let's see how long I can stomach it." He grinned. He didn't seem to mind that I wasn't all girly-girl and didn't have the smoothest of social skills. True, I was trying to brush my hair more these days, but I was still predictably clueless about clothes and how regular girls acted. Dylan seemed to accept me for me. But why was I even thinking about that? Sooner or later, his crush on me would end, right? And we'd go back to being—there's that word again— _normal_. And just like that, my thin facade of agreeableness shattered. "You know, life's not about being _normal_ ," I snapped. Dylan glanced at me, one eyebrow raised. "It's about being _happy_. And right now, what would make me happy is _not walking_!" And just like that, I took off at a run, then threw myself into the air, snapping my wings out. I stroked downward powerfully and pushed upward, the familiar rush of exhilaration at taking flight filling me. I knew the other five bird kids—no, four—would be close behind. I kept forgetting we were only five. There'd always been six of us (plus Total), but my flock had changed a lot recently. First Dylan showed up, then Fang left—don't get me started about that—and then, not too long ago... something happened. And we were down to five. But I'm not going to talk about that. I can't. Not yet. "Tag!" I felt a rush of wind and Dylan's hand tapped my foot as he rose strongly above me, his fifteen-foot wings shining in the morning sun. I blinked at him, breathing in deeply, and the trees shrank below me, along with all those painful memories. "Come on, slowpoke. You're it!" Dylan said, surging ahead. Laughing, I soared after him, feeling a dash of pride. I'd been the one to teach him how to fly, even if he was a wicked-fast learner. The two of us rose and swooped and chased each other until we were a block away from school. At one point I looked over at him, still smiling wide, and something seemed to light up his eyes. "Normal's overrated," he said. # FANG OPENED ONE alert eye to see the early-morning sky lightening on the desert horizon. The slow, even breathing around him told him his gang was still asleep, and Fang felt the familiar weight of anxiety closing in on him snugger than his sleeping bag. They had to get going. He could feel it—the new threat was developing exponentially with every minute. _Get up_ , his instincts hissed. _Go. Now._ But Fang felt the warm body in the sleeping bag next to his stir slightly in her sleep and knew there was something else entirely that was making it difficult to breathe. It was this whole situation. It was _her_. He studied her relaxed features: the familiar cheekbones; the strong arch of the brow, making her look surprised in sleep like she never would in daylight; the full mouth he knew so well, the mouth he wanted to kiss, but wouldn't, not now... She still looked so heart-stoppingly like Max that it made Fang wince. Fang wriggled up out of the cocoon of his sleeping bag and leaned over her. He reached one tentative hand out and ran his fingers through her short hair. She sighed. "Time to get up," he whispered into her ear. "We have to get going." "Stay," the girl murmured dreamily, pulling him back down next to her. She nuzzled into his neck and stretched one smooth arm over him. Fang swallowed. Even through the sleeping bag he could feel the heat coming off her body, sense the outline of her shape. It felt so natural, so familiar. He felt so guilty. Fang had never imagined he'd be sleeping next to a different girl, ever, in his life. And here he was, with Maya, of all people—Max's _clone_. The cute, short pixie cut she'd gotten two days ago helped. _No ratty mane to get tangled when I'm flying_ , she'd said. But Fang knew she needed it for other reasons, too. She wanted to look different. To distinguish herself from Max. And she _was_ different. She was tough, but she seemed less angry than Max did, more accepting of her Gen 54 status. She smiled more often, and more easily. It made him feel way disloyal, but in some ways, Maya was just easier to be around than Max was. Very carefully, with Fanglike stealth, he eased out from under Maya's arm, lifting it and placing it back on his sleeping bag without waking her. He needed to... not be lying there anymore. He wasn't comfortable with where his mind—or his heart—was taking him. One glance showed Fang that the members of his small gang—Maya, Ratchet, Star, and Kate—were all still asleep. He poked at the sleeping bags and shook some shoulders but got little more in response than annoyed grunts and thick snores. These kids were definitely not the light sleepers the flock had been. Fang sighed. First, some fuel. The previous night's fire had been banked, and now Fang stirred the embers and added more tinder. Five minutes later he had a nice blaze, and he opened his wings, letting them bask in the heat. On the horizon, the sun was just starting to spill its pink glaze over the mountaintops. He tried to swallow the sense of urgency building within him. They weren't actually being chased, he reminded himself. He was in charge. Years on the run had taught Fang how to make almost anything edible, including desert rats, pigeons, cacti, dandelions, and stuff reclaimed from restaurant Dumpsters. But this morning he had better raw materials to work with. He set the collapsible grill over the fire and pulled out a lightweight bowl and the one small frying pan he had in his pack. Max was... Max. She wasn't easy, she wasn't restful, she wasn't a little dollop of sunshine. But since when did he need a little dollop of sunshine? It wasn't exactly what a life on the run tended to create. Max was... his soul mate. Wasn't she? She knew him better than anyone. He cracked some eggs open a little more forcefully than he needed to and started whisking them in the bowl. He and Max had been through so much together—losses, betrayals, joyous reunions. Life-threatening injuries, gunshots, broken bones. Christmases and birthdays and Max Appreciation Days and Angel's— A pain almost physical made Fang pause as he chopped the supermarket ham. _Don't think about that_ , he told himself. Anyway. Max. She was so familiar to him. _So_ familiar. Maybe even... too familiar? No! He couldn't believe he was thinking that way. She still surprised him, after all. It was just that he hardly knew Maya. He couldn't predict what she would say or how she would say it. It was all really... new. He'd thought leaving the flock would simplify things, make things easier. Instead his life was just more complicated, more confusing. He blinked when Maya's arms came around his waist. Only years of pseudo-military training had kept him from jumping a foot in the air. How had she snuck up behind him? "Mmm," Maya said sleepily, leaning her head against his back. "That smells like heaven. Where'd you learn to cook like that? You're amazing." Fang swallowed again and shrugged. "Just picked it up." Maya came to stand next to him, one arm still around his waist. Her hair was just so... cute. He blinked again in surprise. When had he ever thought someone's hair was _cute_? Not since... never. Frowning, he looked down at Maya, who met his frown with a slow smile. She reached up on her tiptoes as he stood, frozen, and kissed his cheek. Her lips were cool and soft. "Thanks for... breakfast," she said, and Fang got the feeling that he was caught in an undertow. And he didn't know if he wanted to get out of it. # AS A RULE, I like to remain an international girl of mystery. I err on the side of caution, to put it mildly, and we used to go to extreme lengths to not let regular people see us fly. But we'd been outed ages ago, and now we bother with non-winged-person camouflage only when we absolutely have to. All of which explains why we landed right on top of the school buses in the parking lot, then jumped to the ground, where we were greeted with much wide-eyed amazement and murmurs of surprise from kids who'd been milling around, waiting for the bell. I gave my shirt a little tug and unzipped my ever-present windbreaker. I felt stares and started to get that zoo-exhibit feeling. I bristled and put my shoulders back—I'm all too used to dealing with people's curiosity, fear, and even, I dare say, a little awe. Then I realized they weren't staring at me. "Dylan!" A girl separated from her clowder (look it up—you'll learn something) and practically knocked me down to get to him. "That was—" she began. "So awesome!" another girl interrupted. Right about then I noticed that these girls were wearing short skirts and spaghetti-strap tank tops, and had long, shiny hair. Trendy flip-flops emphasized dainty toenails painted blue and green and pink. It would be shallow to mention what I was wearing, so I won't. If I'd been with Fang, he would have stiffened and then slipped away into the shadows before they even realized what had happened. But I was with Dylan. "Hello, ladies," he said, and his smile _visibly_ took their breath away. I had no idea eyelashes could flutter that fast. Or why they would. "I haven't seen anything that cool since Andi's couch caught on fire at our last party," said one girl, expertly flipping her hair over one shoulder. "It was totally an accident!" the girl I guessed was Andi said, giving the first girl a little shove. Dylan's smile widened, and I waited for the girls to bow down and chant _We are not worthy!_ Except they clearly thought they were _so_ worthy. Completely secure in their worthiness. The first girl tapped Dylan on the chest with one painted fingernail. I stuck my hands in my pockets and fell back to walk with the rest of the flock. "You're eating with me at lunchtime!" possibly-Andi said, smiling up at Dylan. "And me!" said the other girl. "And us!" Three more girls crowded around him and I had a sudden mental image of a bunch of hyenas circling their prey. "I'm gonna have to get some wings," I heard a guy mutter as they watched the girls move with Dylan toward the school. "Retrofitted wings are a disaster!" I informed him wryly, remembering my sometimes-evil, now-deceased half brother Ari's horrible grafted-on pair. The guy's eyes widened, and I got too late that he didn't _actually_ mean he was going to get himself _wings_. In my science-gone-wrong world, it was only too possible, and I'd seen enough botched experiments to prove it. "Sloan!" Nudge's excited greeting made me look over to where a boy was loping toward us. He had smooth brown skin and a million thin dreadlocks pulled back in a loose ponytail. He was male-model cute, and I could practically hear the squeal Nudge was repressing. "Hey, girl," Sloan called back with an easy smile. "How old is he?" I hissed under my breath. Sure, Nudge is five-six, but she's only twelve years old, and in way too much of a hurry to get older, IMHO. "I don't know," Nudge said blithely, heading off to meet him. I gave him a once-over—he was wearing a varsity jersey, which meant he was in at least tenth grade, probably eleventh. So, like, fifteen? Sixteen? Crap. What was she doing? A light touch grazed my arm and I snapped my head sideways to see Dylan turning his full wattage to me. "Catch you later," he said, and his sea-colored eyes seemed to look right into my soul. Again I remembered kissing him on top of the Arc de Triomphe. And a couple other places. Now he was throwing himself into the group of girls like chum into shark-infested waters. _Well, they can have him_ , I thought, touching my arm where his fingers had left a warm trail. I didn't want him. Right? # "WE NEED TO hit the road," Fang said to his small gang. "San Francisco's next up." Maya squeezed his leg and flashed a smile that instantly eased his anxiety. "Ready when you are," she said, her eyes meeting his. "Go, go, go," Star complained with characteristic attitude. "We just got here. At least let me finish breakfast." She tied back her silky blond hair and proceeded to house her entire omelet in one enormous bite. It reminded Fang of Gazzy gnawing every bit of meat off the hind leg of a roasted rabbit, and contrasted so sharply with Star's spotless Catholic-schoolgirl image that he had to smirk. "What?" Star challenged Holden Squibb, who was also openly staring from behind his huge glasses. "You know my heart's beating like five times as fast as yours. Speed needs fuel." Holden was the youngest, most awkward member of the gang, and his main skill seemed to be annoying Star. Well, that and being an incredibly fast healer. Came in handy, since he'd been horribly bullied in school. "What's in San Fran that's got your panties in a bunch, anyway?" Ratchet was eyeing Fang cautiously. Regardless of his extraordinarily perceptive senses, after living on the streets, he could always smell trouble. "Yeah, what's up?" Kate brushed her glossy black hair back from her face and followed Ratchet's gaze, looking worried. For someone with the kind of superhuman strength Kate had, she tended to look worried way more often than Fang was comfortable with. "I'll show you." Fang flipped open his laptop and the others crowded around. "I've been tracking world news reports. A new threat is developing faster than anything I've seen so far. Three days ago there were five mentions of it. Two days ago there were five thousand. Yesterday, a hundred thousand different sources were talking about this movement. And today my Web counter shows more than a million mentions." "You going to tell us what it is, or what?" Holden asked, showering the keyboard with toast crumbs. "They call themselves the Apocalypticas," Fang said, flipping through tabs until he found their home page. "More commonly known as the 99 Percenters. I've done some hunting, and I think one of their bases is around San Francisco." "99 Percenters?" Star leaned closer to read. "Please. That sounds so lame. At least the Apocalypticas sounds kind of like a rock band." "I wouldn't dismiss them so lightly." Fang leveled his gaze at Star, and then at the rest of the gang. "You all remember the Doomsday Group." Solemn nods all around. "This is, like, the next level," Fang said. "The Apocalypticas make the Doomsday Group look like a glee club. They call themselves that because they want to start where the Doomsday Group left off—they want to reduce the world's population by _ninety-nine percent_ , to obliterate all non-enhanced people." Enhanced people. Fang and the flock had always called them _mutant freaks_ , like themselves. Now it was _enhanced people_. "Man, that is so messed up." Ratchet shook his head, the aviator glasses he wore even in darkness reflecting the screen. "I mean, we're safe, though, right?" Kate said uneasily. "We're enhanced. It's not us they're after. Maybe we should... I don't know... stay out of the line of fire this time. We don't _have_ to seek them out. Let's not forget what happened in Paris." Once again Fang felt a stab of pain so sharp that it almost took his breath away. As if he could forget. He bristled, frowning at Kate. "Aren't you the _vegan_?" he asked. "The one who's always talking about the plight of other creatures and how we have to work together to make a difference? So now that things are getting a bit heavy, you just want to walk away?" "It's not that, it's just..." Kate trailed off, looking sheepish. "It's just that it's none of our business and we have ourselves to worry about," Star continued for her. Kate and Star stuck together because they'd been the only two freaks in their private school, but it was Star who had the mouth on her. "What exactly are you saying?" Fang's words were low, measured. "We're talking about the human apocalypse." "Come on, Fang," Star said harshly. "Don't tell me you've never thought that the world might be better if everyone was a bit more _evolved_." Fang gaped at her, but Star took it a step further. "Just look at Maya. She's like the next generation of your old girlfriend, isn't she?" "Ouch." Holden gave a low whistle. Maya's eyes narrowed. "What's that supposed to mean?" Star shrugged. "I'm just saying, looks like Fang went for the upgrade. Shouldn't the rest of the world? Anyway, like Kate said, it's not us they're after." "Look, you're welcome to leave at any time," Fang said, his eyes dark and furious. "You wanted the protection of the group, and I gave you that. I totally understand if, now that you're safe, you just want to slink away like a coward and let everyone else take the fall. I couldn't live with myself, but that's just me." "Can you all just stop for a sec?" Rachet said, pushing his oversized hoodie back and tilting his head to the side. "I can take care of myself," Star snapped at Fang, ignoring Ratchet. "I didn't realize being a part of 'Fang's gang' meant following you like lemmings over a cliff." "Fang, Star doesn't mean that," Kate said, trying to defuse the situation. "You know we believe in stopping these maniacs as much as you do. We're just... we're nervous after Paris. We're still not used to being targets and all." "Yeah, it must be really tough, being away from the cushy comforts of your private-school McMansions," Maya said icily, and Kate's face fell. "Don't even—" Star started. "You guys, _shut up_!" Ratchet yelled. He took in a deep, slow breath, his hypersensitive ears listening intently. "Something's coming this way." Immediately Fang went on alert, jumping to his feet, putting the argument—as screwed up as it was—behind him for now. "Stow the gear in the van," he directed. "Maya and I will scout it out from above." He glanced at the sky, cursing. It was maybe seven AM. They should have been on the road an hour ago. "You guys, we're in the middle of the desert," Kate said. "Maybe we shouldn't freak out yet. There are tons of wild animals around here—coyotes and big lizards and turkey buzzards—and that might be what Ratchet's hearing. I really think we should keep talking this out, try to find some middle ground, and—" Ratchet shook his head. "Yo. I can tell the difference between a fox or a lizard and... this thing. This mofo is big—bigger than a wolf, or even a bear. And I smell _blood_. Lots of it." # "I SMELL _BLOOOOD_ ," Star intoned in a deep voice an hour later. "Lots of it." Ratchet scowled. "Say it again, girl, and see what happens to you. Go on—say it one more time. I'm telling you, something was out there." "At least it wasn't worse," Kate said, her easy smile returning. Fang nodded, glancing quickly in the rearview mirror. All he and Maya had found was a bunch of buzzards having a prairie-dog party. "Yeah," said Star solemnly, "it could've been a small lizard, bent on destroying us all. Or a mutant desert bat, prone to feasting on the hearts of 'enhanced humans'. Right, Ratch?" Holden and Kate couldn't help giggling, and Fang was reminded of the flock. How many times had they joked with one another just like this, teasing and arguing? And here he was with a whole new gang. But the teasing felt harsher, the arguments more real. No flock in sight. No flock, but there was Maya, next to him. She sighed unconsciously, like she felt as separate from the group as he did. It made sense. As the only two flyers, they could've made it to San Francisco in about forty-five minutes, but instead they had six hours of driving ahead of them. Maya leaned her head on his shoulder. The bench seat in the front of their "borrowed" van meant she could sit really close, and she was. _Really_ close. He breathed her in, ignoring the squabbling in the backseat, and an understanding seemed to pass between them. It was more than just having wings that separated them from the gang. They felt weird with the others because they felt _good_ alone. Together. Like he had with Max. Just as Fang's thoughts started to spiral, Maya straightened up and frowned, leaning forward. "Do you see that? Like a dust cloud, way ahead, on the road?" Fang squinted and saw what she was talking about: a growing haze, blocking the road ahead of them. "Ratchet?" Ratchet looked smug. "I thought you guys didn't trust my senses." Fang sighed. After the theatrics with Star and Kate, his gang was exhausting him. "Please?" Ratchet sighed and lowered his sunglasses, peering through the windshield. When he spoke his voice was gruff, all business. "We got company. Looks like a convoy of vehicles, hogging both lanes and about to pay us a visit." In seconds Fang had slammed on the brakes and made a tight, fast U-turn that sent the van up on two wheels. He stomped on the gas and shot them down the road in the direction they'd just come from. "Sorry, but I'm not into sticking around for the welcoming committee," Fang said tersely, scanning the road ahead for the turnoff he'd seen a while back. There was a slim chance that he was overreacting, that these were trucks taking vegetables somewhere or something. Fang estimated the chance of that to be approximately point-zero-one percent. He accelerated more. He could feel the engine straining—and the van definitely wasn't up to off-roading. Fang watched the dust cloud advancing in the rearview mirror and felt Maya's tension next to him, her wings brushing his. It was tempting to break loose and fly... but no. They couldn't leave the others. Fang breathed a sigh of relief as he saw the thin outline of the gravel road ahead. After the turnoff, they could ditch the van, flee to forest cover, and take whoever it was hand to hand. If necessary. "Almost there," Fang muttered under his breath. Half a mile... a few more seconds... _Wham!_ # THE IMPACT ROCKED the van sideways, and there was a deafening screech as it skidded across the asphalt. The doors on the left side were crunched shut. Windows shattered, Kate shrieked, and Ratchet started swearing—they'd been T-boned by a truck shooting out from the dirt road that Fang had planned to turn down. Fang looked to his right and felt a tightening in his chest as he saw the gash, the slack jaw, the unfocused eyes. "Maya?" Fang said sharply, shaking her arm. "I'm fine." Maya blinked, touching the blood at her temple. She smiled. "Just a bump." Fang gave a brief nod and started climbing out through the broken windshield, reaching behind him for Maya's hand. Why was he worried? Maya could take care of herself. "Out and scatter!" he ordered, and the gang started to scramble out the right side of the van. Fang leaped to the roof and did a 360. Two monster trucks blocked the dirt road, and four others had screamed into place in front of the van. The other convoy was maybe a quarter of a mile away and speeding toward them. They were boxed in. He surveyed the gang. Ratchet was holding a tire iron, and Holden had already assumed a battle stance. Star's speed and Kate's strength made them a fierce pair. And Maya... he had complete confidence in Maya. He'd seen her fight before, and knew what she was capable of. In seconds, the other convoy was screeching to a halt behind the van. _Here we go_ , Fang thought, and felt his muscles tighten in readiness for whatever craziness was about to explode in the next thirty seconds. For several moments, it was dead silent. "What is this?" Fang heard Ratchet mutter. "I want to bust some heads." Then, slowly, a door on one of the trucks opened. Fang tensed, ready to dodge bullets. But what emerged from the truck was a much more effective weapon, one that left Fang speechless, with his eyes bugging out of his head. "Hello, Fang," said Ari. Ari, Max's usually evil half brother, who was enhanced, like the rest of the Erasers, with wolf DNA. Ari, who Fang had seen die, _twice_. He'd helped bury him! But... here Ari was. With a missile launcher balanced on one hulking shoulder. Pointed at Fang. "Ari," Fang managed to say. "I heard you were going to be the first to die," Ari said, his amused tone in sharp contrast to the crazy, feral gleam in his eyes. Fang shifted, remembering Angel's creepy doomsday prediction. "I wanted to make sure I got to do the honors." Ari pointed the heavy launcher on his huge, unnaturally muscled body at Fang. He smiled, baring long yellow teeth. "How about it, sport? You ready to die?" He tilted his head and looked through the gunsight. For maybe the first time in his life, Fang felt... absolutely frozen. # "GUYS! OVER HERE!" Dylan waved to me, Gazzy, Iggy, and Nudge from where he sat sandwiched between Eager Girl #1 and Eager Girl #2 at the popular-crowd lunch table. I'd been headed toward the dweeb and misfit section, but when Dylan called out to us, Nudge squealed and hurried over. She confidently squeezed herself between some girls who looked less than thrilled at her arrival. That decided it. "Cover me," I said, sighing. "I'm going in." "Got your back," said Iggy. "Later, bye," Gazzy said, making a U-turn to go eat with some kids his own age. I couldn't blame him. I, too, would rather eat with a bunch of nine-year-olds than have to bear witness to the popular girls slavering over Dylan. "Max!" Dylan beckoned. "Sarah, could you scoot over a little, please?" Sarah looked like she would rather eat a slug than make room for me, but then Dylan turned his Pied Piper smile on her and she melted. She even patted the bench next to her. It was almost scary, the effect he had. Thank God I was completely immune to it. I sat down and a sudden silence fell as the girls looked at my heavily laden lunch tray. Dylan seemed oblivious, and kept up his easy conversation with Nudge. "You must be... hungry," said one girl, whose name I think was Bethany. I wasn't about to go into bird-kid caloric requirements, so I just smiled and said, "I don't have to watch my weight, thank goodness." _So bite me._ Nudge popped open her juice. "Last night on _Project Makeover_ , did you guys see where Tabitha was wearing those capris that looked like fruit salad?" she asked, her eyes wide. Eyes quickly turned to her and heads nodded. "Those were the ugliest pants I've ever seen," Sarah said solemnly. I busied myself with my huge chunk of cafeteria meat loaf. Of that last exchange, I had understood the words "pants" and "fruit," but I couldn't see how they would go together. Then it hit me: Nudge really did fit into this world. I mean, okay, she'd told me that a thousand times. But seeing her like this, chatting with these other girls, normal girls—the only thing that didn't fit here was... her wings. "How's your morning going?" Dylan asked me, ignoring the pop-culture bonanza surrounding us. I swallowed, savoring the availability of lots o' food. To those of you who may sneer at cafeteria fare, I say: Try Dumpster-diving for a month, and then let's see how happy you are with Monday Meatball Medley or whatever. "I'm at _school_ ," I said pointedly, and got that smile again, the one that seemed to suck the air out of my lungs. " _You_ seem to be doing well, though." I slanted my eyes at the girls and then looked back at him. He grinned. "Same old, same old." "Uh-huh. Being God's gift to girls everywhere is just your cross to bear." Dylan nudged my knee with his. "You think I'm God's gift?" He sounded horribly pleased, and I wanted to smack myself. "No, but at least _you_ do." I smiled and took a sip of juice. Dylan smiled wider and I felt a tiny thrill run down my spine. I knew I was courting danger, but this kind of easy almost flirtation was rapidly becoming addictive. "I couldn't believe it when Terry said that orange was the new black," Nudge chattered on next to me. "I know!" said maybe-Melinda. "I mean, _black_ is the new black, you know?" Nudge stabbed the air with a french fry. "Exactly! _Nothing_ needs to be the new black, because black will always, _always_ be the new black!" There was fervent agreement around the table. I had no idea what they were talking about. Black _what_? "Actually, it seems to me that _blind_ is the new black," Iggy said, apparently deciding to shake things up. "What?" a girl named Madison said. "I mean, I can't believe there are so many blind students! A whole school of them!" Silence. Nudge pressed her lips together; it had been going so well. I started working intently on my square of spice cake. "Um..." said Bethany. "I know why _I'm_ blind. Let's hear _your_ stories!" Iggy waved his hand, "accidentally" flinging peas all over the people sitting closest to him. Nudge's cheeks flushed, and she stared at me, like, _Stop him._ Oh, yeah, that could happen. No prob. He turned to Madison. "What about you? Were you born this way, or did something happen to you?" The people around the table looked at one another in uncomfortable silence. "I'm not blind," said Madison. Iggy pretended to look confused, then shook his head, the soul of compassionate understanding. "You've got to face up to it. You can't let it hold you back," he said gently. "Denial is not just a river in Egypt." "I'm really not blind," Madison said, looking confused. Nudge gritted her teeth and stared down at her food, mortified. Yep, we spread joy and sunshine wherever we go. # I TICKED OFF bird kids on my fingers. "Gazzy has Science Club today. If he blows something up, I will personally take a belt to him. Nudge is walking home, unwilling to be seen with any of us. And Iggy has soccer." "I saw him on the field yesterday," said Dylan. "He looked great." "He's always been good at it," I said. Somehow, Iggy's blindness had forced all of his other senses to overcompensate. His navigational skills and coordination were sometimes even superior to the rest of the flock's. "So can we fly home, or do we have to be normal some more?" "Oh, I have something better planned, sugar drop," Dylan said with a twinkle in his eye as he led me to the school's parking lot. "Call me that again and I will flay you alive," I promised, but I followed him to a large red motorcycle. "What's this?" "I'm borrowing it," Dylan said, swinging one leg over the saddle. He patted the seat behind him. "Hop on." I had been raised unburdened by the concept of "other people's property," so I hopped on. Dylan kicked the motorcycle into gear, and off we went. I don't know if you have ever been on a motorcycle (if your parents don't know, please do not nod now), but I must say: If I didn't have wings, and if motorcycles weren't, essentially, extremely cool death traps, I would want to ride on one all the time. It's about the closest approximation to flying there is. The wind whipping through your hair, the sense of freedom, the bugs slamming into your face—it's flying, but on the ground, burning gasoline and making a lot of noise. What's not to love? We didn't go straight home. I put my arms around Dylan's waist, leaned my head against his back, and closed my eyes. He felt warm and solid. I didn't have to do anything, _for once_ —I just sat there. It was almost scary. Because I wasn't totally in control of the situation. I felt the motorcycle slow, and then come to a rolling stop. Reluctantly, I opened my eyes. "Where are we?" I asked. Dylan climbed off the motorcycle and held it steady while I got off. He waved his hand at the view. We were on the coastal highway, with rocky cliffs on one side and the Oregon coast in front of us. The ocean looked gray-blue and choppy, and the air temperature had dropped about fifteen degrees. Seagulls wheeled above the waves, cawing, and I wanted to join them. I moved to the railing, ready to jump off. "Wait, Max." Suddenly, Dylan's dazzling smile was nowhere in sight. His face was solemn, his eyes a darker shade of teal. For a second I thought he'd spotted some kind of trouble far in the distance, across the cliffs. You could say Dylan didn't just have the eyesight of a hawk—he had the eyes of the Hubble Space Telescope. His gift for seeing faraway things, especially in space, was a little mutant DNA bonus from the mad scientist-slash-genetic engineer who created him. "I found this place the other day, when I was out flying," he said, shifting to a less guarded, more emotional tone. "I feel closer to the clouds here, more than anywhere else. I wanted to share it with you because... I feel closer to... to Angel here, too." My eyes flew to his face, my mouth partly open in shock. Angel. The youngest member of our flock. My littlest bird. I was assaulted with memories: Angel smiling sweetly at Total, her pale blond curls making a halo of fluff around her head. The depth in Angel's eyes when we witnessed disaster, way more knowing than any seven-year-old's should be. The way she'd get into my head, under my skin, inside my heart, always. And then— Angel disappearing in a cloud of smoke. I grimaced, thinking of Paris and the explosion. "We do not talk about that," I reminded him tightly. He gave a sad smile and gestured out at the vast ocean, the craggy cliffs behind us. No one was around—it was me and Dylan, water and rock and sky. And my bleeding, ripped-open heart. "You can't pretend she was never born," he said as I narrowed my eyes and pulled out my trusty standby: rage. I opened my mouth to snap at him, but he continued, gently, saying, "You can't pretend she never died." I actually gasped, drawing away from him in shock, feeling a sharp pain in my chest as if he'd plunged a dagger into me. _It'll be okay_ , Angel had said the last time I saw her. _I'll be with you always._ But it wasn't okay. She wasn't with us. She never would be again. "Shut up!" I croaked. Dylan put his hand on my shoulder, holding me as I tried to spin away. He pulled me to him firmly, cradling me against his hard chest, one hand on the back of my neck, the other on my back. "We all miss her, Max," he whispered against my hair. "We'll always miss her." And that was it. A horrible keening sound filled my ears, and it took me several seconds to realize it was coming from me. Then I was clutching Dylan's shirt, pressing my face against him, sobbing uncontrollably. He held me tightly, his cheek against my hair, stroking my back and whispering, "I know. I know. Let it out, Max. There's no one here but me and you. Just let it all out." I almost never cry. I keep my emotions on a supertight leash. They normally don't just burst out of me like that, but once they did, I sobbed and sobbed until my throat was raw and Dylan's shirt was wet from my tears. My baby was gone. After everything we had been through, after love and betrayal and fury and love and forgiveness, she was gone. Forever. She'd sacrificed herself to save thousands, and she would never, ever be back. And I hadn't let myself believe that, until now. # I DREW IN shuddering breaths, my sobs subsiding. I had needed to grieve over Angel. And I had a lot of other things to grieve about, too. I'd been abandoned by my mother, my half sister, my pseudo-father, and the boy I thought was my soul mate. And so finally, after all this time, I wailed my guts out. In a really loud, out-of-control, sloppy, wet way. All over Dylan. I pulled away from him awkwardly. I was thirsty and empty and feeling hollow, and imagining the possible humiliation resulting from the revolting scene I had just made was vomit-inducing. "Remember that time you bawled like a baby?" Dylan would say for years to come. "That was hysterical!" I just wanted to collapse on my bed with the covers over my head. Forever. But Dylan was still looking at my puffy face. "Remember how Angel saved that little kid from the hotel fire?" he asked, his eyes shining. I did. I could still picture her smile shining victoriously out of her dirty face, the boy clutched in her arms, her wings gray with smoke. Angel, rising from the ashes. I wiped my nose. "I'm done talking about her." Dylan nodded. He was silent for a moment, looking out over the ocean. His hair looked dusty in the afternoon sun. "I don't know what to do with the sadness," he said finally, sighing. I looked up at him, surprised at his directness. "Why do you keep talking about it, then?" I was too worn out to even get angry. "I don't know what else to do." He shrugged. "I have all these hard feelings inside, and I thought talking about them might help. And... I don't want to forget Angel. I'm scared that if we don't talk about her, it will be like she never existed." I nodded warily. I had my own hard feelings that I didn't know what to do with. They sat like a pile of rocks in my stomach. Building and building. "You're the strongest person I know, Max," said Dylan. "Yeah..." I picked at my nails, thinking about my meltdown. I had never been very good at receiving compliments, especially ones that seemed heartfelt. "Seriously. I'm learning how to be strong just from watching you." Dylan put his hands on my shoulders. "But I know not everyone can be strong all the time. I just wanted to tell you that if you ever need to _not_ be strong, you can lean on me. I can be strong enough for both of us—for a while, at least." He gave a slight grin. Dylan looked into my eyes with such naked trust I had to look away. Below, the waves smashed into the rocks, spraying a cool mist over everything, and I felt goose bumps rise on my arms. Fang always had my back—that is, until he didn't. He didn't have to say it aloud; I'd known it anyway. Dylan was so different. It was like he didn't know how to be guarded. His emotions were raw, on the surface for everyone to see, and the sarcastic wall that had protected me so efficiently in the past was slowly crumbling in the face of his honesty. I felt vulnerable, exposed, so out of my element. I shifted uncomfortably. "Can we fly now?" I asked, my throat dry. Dylan smiled, his face lighting up, his eyes crinkling at the corners. He stuck the motorcycle's keys under its seat and took my hand, and we climbed up on the guardrail. I took a deep breath, and together we jumped off. # THICK, HEAVY CLOUDS had rolled in, blocking the sun, and it felt like Dylan and I were the only two people on earth. Our wings took us high over the water, up and up until the cars on the highway looked like shiny beetles, bustling to and fro. We wheeled freely through the air, no destination in mind, copying the gulls, seeing dark schools of fish in the water below. My chest expanded again, after being all crumpled up from crying. I felt my heart beating hard, felt the cool mist against my skin, and I felt fresh and alive and somehow lighter. Like I'd dropped some of those hard, heavy rocks I'd been carrying around. Dylan was good for me, in some ways. I had to admit it. "What?" he asked, raising his voice over the wind. "What what?" "You were sort of smiling." I shook my head. "I don't know why." "You know, Max," he said after a few more minutes. We'd slowly turned in a huge circle and begun to head toward home. I looked at him, eyebrows raised. "You know I love you." I almost dropped right out of the sky. I literally forgot to flap my wings for a couple of seconds, and plummeted about fifteen feet before they started working on their own. "I know you were _programmed_ to love me," I said cautiously, rising back level with Dylan. "Maybe I was," he said. "I don't know. I just know I do. And I know that love has to go both ways. You might not love me now, but I hope you will, in time. I can wait. I'm not going anywhere." I said nothing, and we flew together wordlessly, higher and higher, as if we could touch the sky. # THERE WERE NO days. There were no nights. There were tubes and bright lights and indistinct voices. And pain. Always, always pain. When Angel was finally put into a kennel, she whimpered with relief. This had to be better than the crisp white sheets, the stretcher that meant scalpels and masks and gloved hands always reaching for her. She shuddered violently, thinking of those hands, and shrank into herself. She never wanted to be touched again. The kennel was meant for a large dog, but Angel still couldn't stand upright in it. She felt around in the cage, her hands brushing against the cool metal of the bars. She searched for a water bottle; her throat was sore from the feeding tube. She winced as she shifted her small body in the cramped space. She was covered with bruises, and her healing wounds stung. Angel could hear muffled voices in the hallway, echoes of footfalls on the linoleum floor, the squeak of rolling wheels—seemingly innocuous sounds that now haunted her dreams—but she didn't cry out. She was way past that. "Help!" she had shrieked at first, for days it seemed, as loud as she could. And later, when it was clear no help was coming, she had only croaked "Why?" as they probed and prodded, her voice a thin, wheezy rasp. But there were no answers, so she had stopped asking. Angel had always felt stronger and more capable than everyone—well, than Max—thought she was. But in the end, she was still just a little kid, with bones that could snap and a heart that could break. She was broken. And totally alone. A long, silent sob trapped in her chest, Angel curled up on the thin towel in the corner of the kennel and went to sleep. "Wake up!" a voice barked after what seemed only moments. So it wasn't over, then. Her heart raced in time to the familiar fear, the dread that made her whole body quiver, but Angel resisted. For several long, delicious moments she allowed herself to indulge the fantasy that it was Max calling her to wake. Even if they were on the run, even if Max was being bossy, even if... Well, anything would be better than the reality she would find when she opened her eyes. "Wake up! There's no sense pretending! Your brain waves show you're awake." Her blue eyes fluttered open just as a bucket of icy water was dumped on her head. Gasping, Angel scrambled farther into her corner, but she was a trapped animal, and she knew it. The back of her head stung unbearably from the icy water and she tentatively touched it with her fingers. A small section of hair had been shaved, and a neat line of small stitches made tiny ridges under her fingers. They'd operated on her brain. A pitiful cry escaped her lips. _Max_ , Angel thought frantically, overwhelmed with horror. _Max—help!_ # "LOOK HERE," the voice commanded. "Pay attention." Angel blinked water out of her eyes and squeezed her hair, feeling chilly rivulets trickling down her back. Outside her crate, the room went dark. Angel saw extremely well in the dark, but then a lit screen flickered on, several feet away. She saw a young child, a boy, with pale, almost white hair. He was lying on a table, very still, covered with a sheet. A crisp, white, sterile sheet. Angel shuddered involuntarily, the wounds on her body aching in response to the image. The camera panned to look down on the boy, and Angel saw that he was in an operating room. He had a mask over his nose and mouth, and his eyes were clamped open. Angel recognized the look in them. It was a feeling she knew well: pure, undiluted terror. Angel felt an icy coldness in her temples as the view zoomed in. There, on the little boy's neck, was the trio of freckles, right where she knew they'd be. _Iggy._ It was Iggy as a little kid. Before... Angel swallowed hard, her eyes trained on the large screen as gowned and masked doctors came in and shone spotlights onto Iggy's operating table. One doctor, his eyes hidden behind large magnifying glasses, spoke directly to the camera. "Today we're experimenting with a new technique, only recently developed. It involves a surgical stimulation of a certain area of the rods and cones in the backs of this hybrid's eyes. We estimate that the subject will have its night vision improved by at least four hundred percent." Then Iggy's panicked blue eyes filled the screen. Angel shook her head, horrified. She couldn't watch. They weren't really going to make her watch...? But the video continued, and she couldn't look away. She stared as the scalpel found its mark and plunged in as if slicing a boiled egg, as tweezers pinched and needles probed, as blood pooled and tubes suctioned it away. As they hacked into him, like butchers. She listened as Iggy's agonized moans grew more and more frenzied. They sounded visceral, verging on madness, louder and louder and louder. He was awake. The whole time. Angel shrank back into her crate and squeezed her own eyes shut, the screams echoing in her ears. She had just seen a film of the crazy whitecoats at the School making Iggy blind. "No!" she wailed, her voice joining Iggy's. _"No no no no."_ The movie flickered to a stop and the room's lights came back on. "That was thirteen years ago," someone said from out of view. "The techniques were unbelievably primitive, which no doubt caused the less than optimum results." _Less than optimum?_ Angel thought with rising hysteria. _You mean the total blindness? That result?_ Once again she tried to hack into someone's brain, the brain of even one person in this awful torture chamber. But it was like the room itself had a dampening field—she hadn't been able to read a single thought the whole time she'd been there. "But you see, Angel," the voice went on smoothly, "we've made tremendous progress since then. Those were the days of cavemen. The science, the technique, is vastly improved. This time, it will go beautifully." "No," Angel whispered again, her adrenaline surging and making her voice seem small, fuzzy. "No, please—" A gloved hand reached for the door of her crate. This time, they would operate on Angel. On her eyes. # "ARI, WHAT ARE you talking about?" Fang said. "We're on the same side, remember? You saved Max." "Times change." Ari smiled again and looked down the sight of his missile launcher, as if gauging how far away Fang was. Fang shifted his weight, primed to leap. "Having the same goal doesn't mean we're on the same side." "What—" Fang began, but he was cut off by a chorus of deep growls. Four more thugs climbed out of the truck to stand behind Ari, looking like a row of college linebackers. Their resemblance to Ari was freakish, surreal: They had the same glint in their eyes, the same unnatural, stretched-out features, the same wolfish undertones. Clones? Or just well-made copies? Fang didn't want to stick around long enough to find out. "Fang, who _are_ they?" Star hissed. She was standing beside Kate, her face even tenser than usual, and Holden was right behind them. Ratchet was glowering at these ugly strangers, smacking the tire iron against his palm. Maya stood silently at Fang's left wing—Fang remembered that she knew Ari. "Erasers," Fang answered quietly. "Human-wolf hybrids. Except they're supposed to be extinct." _So how was Ari alive?_ And more important: _Why was he suddenly evil again?_ Maya met Fang's eyes. _Fight or flight?_ "Enough talking," Ari said, almost lazily. "Let's play a game!" Fight. # BEFORE FANG HAD time to think, Ari fired a missile. Right at him. Instantly, Fang unfroze, his instincts going from shock to hyperdrive in zero point two seconds. "Duck and cover!" he barely had time to shout as he threw himself sideways off the van. The missile missed Fang by a hair, singeing his shirt as it shot past. And then— _boom!_ Their van exploded in a mushroom of flames, flying metal, and roiling black smoke. Kate shrieked as a shard of glass swiped across her cheek, leaving a thin line of blood, but the sound was just barely audible above the roar of the fireball. Fang jumped to his feet, ears ringing. The van was nothing but a few smoldering, smoking chunks scattered in a circle around the blast zone. Holden scrambled to his feet, dust-covered and wide-eyed, as Kate wiped blood from her cheek. Ratchet was hardly visible through the thick black smoke. "Man! Friggin' almost busted my ears!" "Never really liked that van anyway," called Star, a little shakily. She, unlike the rest, looked perfectly unharmed and clean—the ability to be forty yards away in the blink of an eye sure did come in handy. Fang's gang dropped into their battle positions, but they all looked a bit wigged out. Even Fang was tense with an apprehension he wasn't used to. Ari was a wild card, and even after all the training they'd done, even with their advanced abilities, he didn't trust any of the gang under pressure like he had the flock. Well, any of them except... Fang could make out Maya's shape walking toward him through the dust cloud, her wings outstretched, looking powerful and ethereal in silhouette. _We'll be okay_ , Fang thought. "Aw, I missed," Ari said in his rusty voice. He was still grinning wickedly, like a tiger cornering its prey. "Enough of the theatrics. Let's _do_ this thing, Fang. You and me. Let's make some history here, before your freaky friends get hurt." "Works for me," Fang snarled, but to his surprise, Maya's hand shot out in front of him. She stepped forward, putting herself between Ari and Fang. "Hey," she said to Fang. "Sorry—I got thrown. But listen: If we fight, we fight together. We're a team. Got it?" Fang nodded, knowing there was no use arguing. She was as stubborn as a mule. Like someone else he knew. "Can't ever just stay out of it, can you, Max?" Ari shook his head. "You're looking a bit rough, sis. The hair's a little _G.I. Jane_ , don't you think?" "Not Max. _Maya_ ," she said, running her fingers through her short pixie cut. Ari laughed, his yellow fangs glinting. "Oh, yeah, Max II. That explains it, then—the delayed reflexes, the bravado. The life of a clone, so difficult." Ari pouted in mock sympathy, and Maya's eyes narrowed. "We understand your pain, don't we, boys?" The row of Erasers behind him twitched impatiently, growling and muttering. "I have to say, though, Deux—as clones go, you seem like more of a cheap imitation. Did Fang pick you up in the discount aisle?" "I said, the name is _Maya_ ," she repeated, jaw clenched. "Same, same," Ari said, still smiling. "Fresh meat either way." And then, before Fang could even react, all heck broke loose. Maya crashed into Ari, her eyes furious and vengeful, knocking the missile launcher out of his grasp with one swift kick. Fang lunged toward them, protesting. Team or no team, Ari was _his_ fight. But in their adrenaline-boosted frenzy, Ari's goons leaped forward, driving Fang and the rest of the gang into defense mode, away from one another. Away from Ari and Maya. # FANG WAS BACK in his comfort zone—that is, beating the living pus out of freaking Erasers, as usual. _I have to get back there_ , Fang thought, trying to see through the wall of hulking bodies. Maya was hard core, but Fang had known Ari to be a vicious fighter, and this new version of Ari would likely be even tougher. After he finished off another Eraser, blood from the guy's nose spattering his black feathers, Fang pushed off the dusty ground and did an up- and-away. He hovered about fifty feet up, searching the scene. There, near the demolished van, landing blow after blow, was Maya, holding her own. Ari was no longer smiling. He was clearly sweating with the effort, and his face was furious. And surprised. Fang almost smiled. Maya was fearless and graceful and merciless. She was beautiful to watch. He scanned the road and spotted Holden backed into a corner with an Eraser. Fang frowned. The kid's technique was all off, and he looked terrified and in way over his head. The Eraser advanced on him, murder in his feral eyes. The Eraser tore into Holden's arm and raised his claw for the final blow, and Fang dove. The dive was short and lightning quick—the half-dazed Eraser never saw him coming. Fang stood up, looking around for Holden, and caught a glimpse of Ratchet wailing on some guy with the tire iron... right as Kate paused in her own fight and clipped Ratchet under the chin with her left hand, sending him reeling backward. "Kate!" Fang yelled sharply. "Watch your aim!" Ratchet was already standing back up, looking annoyed but ready to take on the next Eraser, when Star, appearing out of nowhere, spun him around just in time for Kate to land another bone-crunching blow to his chest. As Ratchet crumpled to the ground, the Eraser gave Kate a brief nod of acknowledgment. Fang's insides turned to ice as things clicked into place: how the convoy had found them, why the two girls had looked so freaked out. They hadn't been nervous about the fight. They'd been nervous about their betrayal. "Traitors," Fang hissed, advancing on them. Kate shook her head slowly, apologetic. Guilty. "Sorry, Fang, we wanted to help you. It's just that..." "Survival comes first," Star said simply. Before Fang could respond, two Erasers charged toward him, and everything was a blur of color and instincts. Fang, on autopilot, kicked and dodged, feeling hollow, anger driving him as he beat the freak out of the guys while Star and Kate just _watched_. With a last surge of adrenaline he crushed the windpipe of the final Eraser, and then it was over. Everything was eerily quiet without the sounds of battle. "Starfish," Fang called to Holden. "You all right?" "Yeah," the kid said, wincing as the cells in his arm multiplied, the deep gash closing before their eyes. Fang nodded. His side felt bruised, he had a possible cracked wing bone, his arms ached, and a gash on his forehead dripped blood into his eyes. It had felt so satisfying, sweating through his fury. _Hurting_ someone. But now that it was over, Fang still had to deal with _this_. Betrayal. # FANG STOOD FACE-TO-FACE with Star and Kate, fists clenched, breathing hard. His muscles stood out on his arms. He felt his agitation vibrating to his fingertips. Kate looked uneasy and shifted into a more defensive stance. She looked scared. Of him. Star, on the other hand, looked unrepentant. She looked him straight on, her blue eyes cold and determined. If he was going to attack, she was ready. Holden looked up at Fang, waiting for his cue. His eyes were wide with anticipation, but he remained loyal. He had Fang's back. _Was_ he going to attack? For one of the very few times in his life, Fang had no idea what to do. Should he scream, walk away, or finish them completely? The unasked question hung in the air between them, the tension building. Fang's face twitched. He was furious, but mostly he just felt disappointed. Only one other situation made him this stressed, this confused... this freaking _emotional_. He looked around. Where was she? Where was Maya? _And Ari?_ "Fang!" Holden grabbed his sleeve. "Up there!" He pointed at the sky. Fang looked up and felt his heart stop. Maya and Ari. Five hundred feet up. Battling to the death. # THEY HEARD HER scream pierce the air even from the ground, saw the bright arc of blood splash across the sky. And then she was falling. Fang felt dazed as he watched her floating down, a long sigh stretching out between them, arms and legs reaching lazily upward, feather-light, body pulling down. _Go_ , Fang's instincts shrieked at him, but time had stopped. He was frozen to the spot, and so was she. Suspended. A picture snapped, a painting hung against the endless wall of sky. _Still life of a tragedy_ , Fang thought. He felt a bright wave of distress, his heart thundering out of his chest, but he couldn't connect the feeling to the image in front of him. Her wings were silhouetted against the brilliant flame of sunlight. Fang knew the exact color of those wings, their span, their texture against his cheek. Hawk's wings, to match her sharp instincts, her hard looks. She looked soft now—softer than the air and the clouds around her. Tender. Cradled in blue. Fang was holding his breath. He could see her face now, her mouth open in a perfect _O_ , caught in mid-sentence, drawing in. To tell him everything that had never been said. That she'd still be there for him, like she always had. That he shouldn't have left her and the flock. That she loved him. Fang felt his will seeping out of him, crushed beneath the weight of this knowledge. The fall would kill them both. He blinked and she was moving again, her arms like a marionette's, in unlikely poses, twisting. A delicate dance, a swaying to music he could not hear. Down... and down. Her features came sharply into focus and Fang saw the fear there, her mouth protesting in a silent scream, the ragged ripple of wing tearing behind her, ruined. The blood in her hair, cut short. So it wouldn't get tangled in the wind. The sound caught up to Fang's ears, the shriek vibrating louder and louder, closer and closer as the ground rushed upward and all the light fell away from her and she was plummeting, as dark and heavy as a stone. Max—no, _Maya_ —was falling to her death. Fang surged upward. Racing gravity, he stretched out his arms toward Maya's free-falling body. He just barely managed to catch her, then sagged as her deadweight dragged him down. Hovering with Maya clutched in his arms, Fang felt his jaw tighten as he saw that her neck was covered in blood, which was streaming down her skin and onto her shirt. _No, no, no_ , his brain protested with growing distress. Ari's claws had sliced her up like deli meat. "Fang," Maya whispered. "You're okay," Fang said, as much to convince himself as Maya. "I've got you. You're okay." Scenes flashed in Fang's mind: Maya laughing easily. Maya asking if he was okay, her eyes soft, concerned. Maya after her haircut—happy, confident, ready for a fresh start. He hadn't wanted to admit it, but he had thought they could be each other's fresh start. He ground his teeth into his lips to keep from screaming. "Fang... I love you," Maya said, starting to cry. Tears trickled over her lovely cheeks, down her jaw, into the mutilated mess of her neck. The sound of wings filtered into his brain, but only vaguely, as if he were hearing it through a long tunnel. "I know," Fang whispered. Then he felt the wind shift behind him, felt the hairs on his neck rising. Before he could move, before he could react, Ari appeared, and with a final, murderous lunge, smashed his elbow into Maya's chest with crushing force. "No!" Fang screamed as Ari soared away from them. Still struggling to hold Maya up, Fang couldn't defend her, couldn't fight back. He could only clutch at her and watch it happen. Helpless. Fang landed as gently as he could. He fell to his knees, arranging Maya's head on his lap. "Crap," Ratchet said, awake again and limping over. "I saw Ari take a swipe at her, but I didn't think it was _that_ bad." "Get me something to stop the bleeding," Fang said tersely. Ratchet looked around, then grabbed Holden and yanked the boy's shirt off. He tossed it to Fang, who pressed the cloth to Maya's neck. He was aware of Star and Kate, unsure what to do, huddling together off to the side. They clearly hadn't been prepared for this. Fang would deal with them later. Ratchet and Holden leaned silently over him. They knew, just as Fang knew, that it was too late. "I'm sorry," Maya cried helplessly. She coughed and sputtered, her breath growing shallow. "Shh," Fang said. "Don't talk. Just focus on breathing. You're going to get through this. _We're_ going to get through this," he repeated. Maya's brown eyes struggled to focus on his. "Sorry I'm... not st-strong af... ter all." "Maya," he said quietly. "You _are_ strong. Stronger than anyone." "After Max," she said, trying to smile. Blood began to seep from beneath Holden's shirt and drip on the ground. Fang shook his head. "Not after Max. Right next to her. Equal." "Thank you," Maya whispered. Then her eyes seemed to focus on a spot just to one side of Fang's face, and her head lolled. Fang didn't move. He just sat there, staring at the dead girl. The dead Maya, the dead Max, the dead almost everything he cared about. He felt like a freight train was slamming into his chest, over and over again. Ratchet and Holden tensed beside Fang as footsteps approached. Ratchet said, "Fang? Wolfboy's back." Still Fang didn't move from his place on the ground, didn't stop cradling Maya's body. Ari's voice, gruff and taunting, cut through the fog. "Fang—sorry, man. Had to happen. Don't worry, though—she's a clone, right? Dime a dozen." Finally Fang looked up, his eyes swimming. "We'll finish this later," he said through clenched teeth. Ari grinned. "I'm counting on it," he said, turning. "C'mon, you weaklings, get up," he shouted at the injured Erasers. Many large bodies heaved themselves noisily toward the trucks. "Coward!" Ratchet hurled the dented, bloodied tire iron through the air. Ari stepped swiftly to the left, and the metal clanged against a truck. His laughter, grating and harsh, filled the empty desert battlefield. Then the engines roared and the entire convoy spun around and faded away in a cloud of dust. When they were gone, Fang passed his fingers over Maya's face, closing her eyes and brushing away some blood. He forced himself to lay Maya's already cooling body on the ground. As Fang looked down at her, he wanted to tear his own heart out. Ari would die for this. # AS SOON AS I walked into biology class, the nauseating smell of formaldehyde hit me smack in the face. _Hello, buttload of horrible memories!_ Clearly today was going to be even more nightmare-y than school usually was. "Hello, Max. Glad you could join us," Dr. Williams said. Frowning, I nodded and plopped down beside Dylan as jealous girls nearby prayed for my death. So I got sidetracked by the schmanciness of the bathrooms on the way here. Sue me. The smelly chemicals were already getting to me (read: making me want to run away screaming), and I could tell they were also bothering Iggy, who was sitting a couple tables over. His face was drawn and even paler than usual. Dr. Williams passed out packets of paper. "Today we'll be doing our first hands-on lab assignment," he said. "For some of you, this will be your first dissection. It's a very simple one, but if anyone feels sick, the trash can is right here. Please try to make it." Dissection. Oh, God. I glanced down at my packet and my stomach dropped. _Chicken Dissection Lab._ Of course. This was _my_ life, after all—if something could conceivably get worse, then by golly, it would get worse. We couldn't just dissect a frog, or an earthworm, or whatever. We had to dissect something with _wings_. The other students chattered around me, their reactions ranging from excited to grossed out. Iggy, Dylan, and I were the only silent ones. Dr. Williams began handing out plastic bags containing rubbery chicken carcasses. I fought back a wave of panic and nausea as I skimmed my info packet. Phrases like _Count the number of primary feathers_ and _Remove the heart_ and _Examine the air sacs_ popped out at me. _Please, if there's any justice at all in this screwed-up world,_ please _don't make me have a mental breakdown and start hyperventilating in front of my entire biology class._ Dr. Williams placed a plastic bag on our table, two feet from my nose. Dylan and I both stared at it, unwilling to touch it. "Okay, folks," Dr. Williams said merrily. "Get your goggles, your gloves, and your trays. The packet explains everything, but come to me if you have questions. Happy dissecting!" # I PUT ON my clear, dorktastic goggles automatically while Dylan fetched the dissecting tray. It was equipped with a scalpel, a small pair of scissors, three pokey, suspicious-looking tools, and a pair of tweezers. "So," I said, mentally smacking myself upside the head when my voice shook. "Ready to cut this thing open?" "We can leave, if you want," Dylan replied softly. "I don't want to do this any more than you do." I clenched my teeth and pulled my shoulders back, shaking my head. "No. Normal people do dissection labs. And we're normal people, remember?" He nodded, his aquamarine eyes fixed on me. I regretted my decision almost as soon as we set the chicken on the tray. It splayed out pathetically, headless and mostly featherless, with puckered pink skin. I felt the chill of goose bumps on my own flesh and shivered. The chicken's wings were small and had tiny tufts of down still stuck to them. White down. Like Angel's. "Step one," Dylan read aloud. His voice cracked and he cleared his throat. "Place chicken on its back. Grasp both legs and push down and away from the pelvis." In another time, I might have snickered immaturely at the word "pelvis." But at that moment, all I could do was numbly follow the instructions, while trying to block smells and memories. _It was bred for this_ , I reminded myself, holding the scalpel. Inside a claustrophobic metal cage, it had been fed scraps. It had been genetically manipulated for a satisfactory amount of plumpness and complacency. It had been bred with a smaller brain, too; it was too stupid to see how trapped it was. To see that this is how it would end up, amid the glint of scalpels, the _snick_ of blades sliding into flesh. I was stuck in an in-between place, not sure whether I was in biology class or back at the School. Student voices and whitecoat voices bounced around in my mind. Then Dr. Williams's face materialized all up in my grill. "Max, Dylan, how's it going so far?" I nodded, trying to slow my breathing—I hadn't realized I'd been hyperventilating. "I'm okay... really." I looked up at his face, at the four wrinkles on his forehead, his almost calculating hazel eyes. It was all somewhat... familiar. Alarm bells went off in my head, wailing, _Danger danger danger!_ My alarm bells were not to be taken lightly. Was it possible that Dr. Williams was a whitecoat? "Actually, I feel a bit sick," I said brusquely. "Come on, Dylan. Iggy!" Iggy twitched on his stool and turned in the direction of my voice. "C'mon, Ig," I repeated, ignoring Dylan's curious glance. "Time to go." "Max, the boys seem fine," Dr. Williams said. Concerned or threatening, _concerned or threatening_? It was a question I had to ask myself way too often. "No, I feel sick, too," Dylan said. _Good boy._ Iggy wove through the maze of lab tables. "Gonna barf," he informed Dr. Williams. "Gotta go." I strode toward the door, itching to hightail it out of there. "Oh, no, you don't, Maximum," said Dr. Williams in a steely voice. _And here we go._ I sighed. I leaned forward onto the balls of my feet, ready to spring into action. Dylan moved ever so slightly, placing himself a bit in front of me and in a good fight position. I felt Iggy tense up. Tapping his forearm twice, I breathed, "Little over six feet. Bit of a belly. Dead center." Nobody but Iggy—and maybe Dylan—would be able to hear me. Ig inclined his chin the tiniest bit. He understood. Dr. Williams shuffled past the cardboard box of chicken bags to his desk, where he brought out some Post-its and started scribbling. I watched him the entire time. If he charged, I'd drag Iggy and Dylan to the left, roll over the empty lab table, and shoot out the door. If he yanked a gun out of his geeky teacher pants, we'd dive behind the table, chuck some scalpels for good luck, and then shoot out the door. "So what's the story, Doctor?" I asked Dr. Williams, crossing my arms. Everyone in the classroom was staring at us now. "Wait, I know—your plan is to make my life miserable? Or possibly destroy us?" Dr. Williams smiled thinly. "What do you mean, Max? I just don't want you to get in trouble for walking out of class." He held out three hall passes. Well, that was... unexpected. I narrowed my eyes at him, but he didn't falter. "Let's go, boys." I shrugged and took the passes, and we walked out of the classroom. My alarm bells never stopped ringing. # "MAX'S LIFE IS in danger." Dylan's breath quickened. Okay, now Dr. Williams had his attention. "But you can keep her safe, Dylan. All you have to do is cooperate with us." After they'd fled the disastrous dissection lab, Dylan had realized that he'd left one of his textbooks behind, so he had gone back to get it. Big mistake. The other students were already gone, leaving only the biology teacher behind. Now Dylan was alone in the lab with him and the chicken carcasses, and it looked like he was, as Max would say, in deep, deep sneakers. Dylan leaned against the table and frowned at the teacher. "What do you want?" he said in a hostile voice he hoped sounded as tough as Max's. He fingered a scalpel that one of the other kids had left behind, but it didn't make him feel any more secure. Dr. Williams smiled, making wrinkles appear around his mouth. "I'm not your enemy, Dylan. I have vital information for you, straight from Dr. Gunther-Hagen himself." "That's impossible," Dylan said, his muscles tensing even more at the mention of the brilliant, diabolical man who had engineered his creation. The man who'd given him his life, and introduced him to Max. "Dr. Gunther-Hagen is dead." "Oh, no, he's very much alive," promised Dr. Williams. "I've seen him myself." Dylan stared at Dr. Williams but didn't respond. He had seen how Max looked at the biology teacher—with suspicion, distrust, and revulsion—and he didn't trust this man for an instant. "And Dr. Gunther-Hagen has a special project for you," Dr. Williams continued. "A... mission, if you will." "What sort of mission?" Dylan asked doubtfully. "A mission it is vital you keep secret from Max if you value her safety." Dylan opened his mouth to protest, but Dr. Williams quickly cut him off. "It involves Fang." Dylan shifted uncomfortably at the sound of the unwelcome name, feeling more and more boxed in among the stacks of laminated papers, bins of educational videos, dissection tools, and models of the various stages of mitosis. "Fang is a far bigger threat than you realize—a bigger threat than any of us realized." Dr. Williams moved closer, seeming to delight in Dylan's discomfort. He watched him gravely. "I'm sharing this information with you because we know you are good, Dylan, that you can be trusted. We _can_ trust you, can't we, Dylan?" Dylan frowned. He did not like the turn this conversation was taking. Not at all. But at the mention of a secret, especially one about Fang, Dylan couldn't help leaning closer. His breath quickened. "Fang's DNA, as it turns out, is different.... _Dangerous._ Dangerous in a way that bad people might use for their own selfish means. You wouldn't want to help the bad people, would you, Dylan?" Dylan crossed his arms over his chest. "You can't expect me to buy this without an explanation." As if to emphasize the delicacy of the information, in a hushed voice Dr. Williams described tests, experiments, and discoveries that boggled the mind. Dylan had certainly seen, felt, and heard about a lot of strange twists and turns of science in his few short years on the planet—not the least of which was being genetically enhanced to be able to heal wounds with his own saliva—but his mind was whirring a mile a minute at this strange, fascinating information he was learning about Fang's DNA. It could be the key to the most important medical discovery in human history.... But he wasn't even sure he believed it. And he definitely resented Dr. Williams's condescending tone. "So you see, Dylan, it's very important that we _contain the threat_. That's where you come in. We need you to capture Fang, to _bring him to us_. You're stronger than Fang, Dylan," the doctor said, touching his arm. It was a compliment, but Dylan flinched. "Superior," the teacher continued. "You were _designed_ for this. And you'd be doing a great service to the world, of course," he added, almost as an afterthought. Dylan's eyes drifted to one of the chickens, still splayed open on the dissection table, its wings pinned open. They wanted to run more tests. On Fang. Dylan thought back to what Max had said about tests in her early life—about dog kennels and needles and whitecoats and drugs. He shook his head. Regardless of his history with Max's ex, and regardless of any threat Fang's DNA might pose, Dylan didn't hate him _that_ much. "No," Dylan said, already heading out of this room that was full of lies and bribes and the smell of formaldehyde. He didn't need to hear any more. "Find someone else to be your headhunter. You can tell Gunther-Hagen to stick his mission up his—" "Ah, ah, ah," Dr. Williams interrupted before Dylan had reached the door. "One more little tidbit, Dylan," Dr. Williams called after him, holding up one finger. "If you don't accept this mission, well, we'll have to kill Max." # ANGEL'S EYES FLEW open and she gasped for air, scrabbling at the sides of her cage in terror. She took a slow, deep breath. It was just a dream. Angel slumped against the plastic wall of the dog crate, feeling icky and shaky and sore all over. In the time she'd been held captive, she had been electrified, operated on, beaten, scorched, and worked to exhaustion. But this nightmare was worse than any of it. It hadn't been real... had it? Every time she closed her eyes, images from the dream plastered the inside of her brain: Max, her neck covered in blood, dropping like a rock out of the sky... her brown eyes dulling with death as her skin grew pale... But Max wasn't dead, of course. Dead Max was the biggest oxymoron in history. Right? Angel felt a rising panic. Her dreams, her visions, were almost never wrong. Except when she thought Fang would die. That hadn't happened... yet. She bit her lip, staring at the roof of her cage through half-lidded eyes, trying to make a connection. And then, like an image appearing through the fog, Fang materialized. Joy, pure and powerful, surged inside her—until Angel realized that Fang wasn't there. She was seeing him in another dreamlike vision. He was standing in a sea of red dust and blue sky, covered in blood and dirt and grime, but he didn't look like Fang, exactly. He looked ferocious and crazed, a mad dog about to attack. _Unhinged._ "She's dead," Fang said, and Angel drew in a sharp breath, her whole body trembling. She hadn't dared to think it could really be true. Fang's face twisted as he tried to control his anguish. He took a step toward two girls Angel recognized from Fang's gang: Star and Kate. "Maya died because of you," he snarled. Realization hit Angel like a ton of C4 bricks. Maya. Max II. Relief, and then horrible guilt, surged through her: Max was alive. It was _Maya_ who was dead. "We didn't know," Kate said, weeping, mascara running down her smooth brown cheeks. Kate was superstrong, Angel remembered, but she didn't look strong now. "Ari wasn't supposed to—" Her voice caught as she cried, but Fang's jaw was tensed, his features hard and calculating, his hands balled into fists. Angel watched in dread. She knew that look. When crossed, Fang was deadly. _Get out of there_ , she thought at the girls. Star put an arm around her friend, and her usually harsh features softened. "We're sorry, Fang, but Maya... wasn't our fault. She was our friend." Fang's laugh was harsh, his sneer horrifying. "Liar!" he shouted, towering over her. "Like I was your friend? You hated her," he spat, his eyes flashing. Star shifted uncomfortably and tucked a stray piece of blond hair behind her ear, her elflike face tightening. "I never wanted her dead," she said quietly. "Please, Fang," Kate hedged, sensing he was about to snap. "We were afraid. There's just too much danger following you. Jeb didn't tell us they'd try to kill—" "How do you know Jeb?" Fang asked, his voice low and murderous. A vein pulsed in his temple as he absorbed the flare of shock at hearing Jeb Batchelder's name. Jeb, the man who'd once taken care of the flock like a father, but who'd turned out to be just another traitor. "How is he involved in this?" "He said he'd keep us safe," Star shot back, her blue eyes accusing. "Which is more than you could do." Fang's growl was fierce and guttural as he lunged for Star's throat like a wounded animal taking a last stand. "Fang, don't!" Holden pleaded, his voice cracking. Ratchet had grabbed Fang's arms. "Chill, man. Just chill. They're not worth it." "You should know better than anyone that survival comes first," Star said smugly, but she cowered as Fang surged against Ratchet's grasp, gnashing his teeth. Angel knew that Ratchet couldn't hold Fang back if he really wanted to kill Star and Kate. As angry as he was, he was _choosing_ to spare them. "Traitors!" Fang shrieked after the girls as they took off down the desert road. "Go on, run. Get out of my sight! If I ever see your faces again I'll tear you apart with my bare hands." Then the vision ended, leaving Angel with the image of Fang's furious eyes, an ocean of hurt behind them. She blinked rapidly as the desert scene melted away, leaving her with a dull ache in her chest. Max was alive, at least, but everything else seemed to be falling apart. Angel hunched into the emptiness of her dog crate, the thick smell of chemicals surrounding her and pain throbbing in every part of her body. She missed the flock so much. If only Fang or Max were here with her. # "THAT IS MESSED up," Ratchet said angrily, standing over Fang. "You're not kicking us to the curb now, when we still gotta get back at that fanged freak. No way, man." Fang nodded, staring into the smoldering embers of their campfire. He was aching all over, and his shirt was still covered in Maya's blood. "Sorry." "Is this about Star and Kate?" Ratchet demanded. "You think we're like them? That I'd snitch? You _know_ I don't roll like that." Even with his aggressive front, Fang could hear the real hurt in Ratchet's voice. "Look at these battle scars." Ratchet pulled up his sleeve, and his dark skin gleamed in the firelight. His arm was covered in slashes and bruises. "For _you_." "It's not that," Fang said. "I just can't... do this. Besides Star and Kate, Maya's dead, and... Look, there's nothing left. Fang's gang was a stupid fantasy. I'm just better on my own." A fleeting thought of the flock made his chest tighten. "No man is an island," Holden said with an awkward laugh, but Fang didn't react. "Shut up, Starfish," Ratchet said halfheartedly, kicking an empty can into the darkness in frustration. Holden brushed his sandy hair out of his face and pulled absentmindedly at the chunk of new skin on his earlobe, which had already grown back after one of the Erasers had bitten it off. After a minute, he said in a small voice, "Where are we supposed to go now?" Fang sighed. "Go home." "We don't have _homes_ to go back to!" Ratchet exploded. "My guys saw me go off with you. You think they'll take me back? What've I got? _Nothing._ " "I can't go back, either," Holden said softly. "My parents don't want me around. They're... they're _scared_ of me." "I know. I'm sorry. I don't know what to tell you." Fang pinched the bridge of his nose. He was exhausted. Maybe more exhausted than he'd ever been. He was tired of making plans, of solving problems. He didn't know how Max had stood it for so long. "You'll figure it out." "So that's it." Ratchet's voice was cold. "After all we've been through, you're just saying, 'So long, it's been fun'?" "Sorry," said Fang. "But it actually hasn't been that fun." And then he stood up and limped away into the desert night. # COOL FINGERS PRESSED against Angel's forehead. Someone was taking the bandages off her eyes. She didn't even struggle; she just lay there limply. There was no point fighting it anymore. "Hey, sweetie," the someone said, and Angel gasped—she knew that voice. She'd heard that voice so many times. Jeb. Jeb here, in the School, taking off the bandages from the operation. _"You."_ Angel cringed away from his hands, fury coursing through her. "Don't touch me!" she spat. "You deserted us. Again. I'm here because of _you_." "I know, sweetheart," Jeb said. "I'm so sorry, Angel. I can't explain to you how sorry I am. You have to let me explain—" "No," Angel growled, and felt his hands twitch; he was startled. "I don't care. You don't get to explain after _this_." She touched her tender face. "Sweetheart..." "Don't call me that ever again," she cried. "I said I don't care—I don't care about any of it. About your excuses. About you. About the rest of the human race." She was seething, and her voice was harsh and icy even to her own ears. "All people do is hurt one another," she continued bitterly. "So let them all die. Let the doomsday, or whatever they're calling it now, happen. _I don't care._ " Jeb brushed her dirty hair away from her face, her curls damp with sweat, but Angel clawed at his fingers. "Angel, please listen to me. I'll make everything okay again, no one will hurt you—" " _I said shut up!_ " she shrieked. Her small body was shaking. "You just couldn't stop at Iggy, could you, Jeb?" "What do you mean?" Jeb asked. He sounded on the verge of horror. "What do you think I mean?" asked Angel, her voice rising with hysteria. She felt clumsily for the sides of her cage. "I'm _blind_." # FANG LEANED AGAINST the cold, rough tombstone. It was twilight, and the sky above the graveyard was a pale indigo. The trees rustled with a slight breeze, but no birds sang, no crickets chirped. Fang was completely alone. Blood trickled slowly from the wound on his wing, where the bone had cracked and punctured the skin as he'd flown up to catch Maya. At the time, he hadn't even noticed the pain. It was pulsing dully now, and he was letting it bleed. Pain from somewhere other than his heart was a welcome change. He deserved the pain, Fang told himself. Everything was his fault. If he had paid more attention in that battle with the henchgoons, if he had kept tabs on Maya the entire time, she wouldn't have fought Ari in the air. She wouldn't have died in Fang's arms. She would still be alive today, warm and happy and Maxish and not Maxish, having his back when things got too real. Fang stared up at the moon, only barely visible in the murky dusk. Things had gotten too real. First Angel. Then Maya. Both innocent, both dead. All his fault. He was a murderer. He let his head drop into his hands, and shut his eyes tight. At least Ratchet and Holden were okay now—without Fang and the danger that came with him, they'd be all right. Fang could not be trusted as a leader; that much was horribly obvious. How could he save the world if he couldn't even protect the few people he loved? Swallowing, Fang looked up, around the graveyard. Tombstone after tombstone, death after death, epitaph after epitaph, summing up a life, or a worldview, in a few words. What would his gravestone say, he wondered, assuming he wasn't left to rot in the open air? FANG: GREW UP IN A DOG CRATE. FELL IN LOVE. SCREWED IT UP. FAILED AT LIFE. Wait a second. Something caught his eye. Fang scrambled to his feet and crossed to the tombstone that read JULIE EVANS, 1955–2010 in two strides. He knelt before it, reaching out and tracing the epitaph. YOU HAVEN'T FAILED UNTIL YOU QUIT TRYING. A sign from the universe? Fang's brain being so pathetic that it was making up coincidences? Either way, he _couldn't_ quit yet. Fang had a role in this—whatever it was—and now that he'd lost two people, he wouldn't lose any more. Fang touched the engraved words one more time, then kicked off from the grass and soared into the darkening sky. # FANG STARED AT his warped, distorted reflection. He was standing in Millennium Park, Chicago, in front of the huge stainless-steel sculpture nicknamed "The Bean." Around his reflection curved the city skyline, clear blue sky and tall majestic buildings. This place was one of the many stops he'd made in the past few days. He was newly motivated, as if the words on the gravestone had injected him with pure determination. Fang was trying to understand the 99% Plan. His wing was still messed up, so he'd taken buses and trains—had even hitchhiked—all over the country, from South Florida, thick with gray fog, to the smooth golden plains of Oklahoma. He had seen the vivid colors of the Arizona sunset. He had watched small waves lap the shores of Lake Erie. Every place he had visited had held rumors and evidence. All over America, people were stirring restlessly in anticipation. You could feel the energy in the air, building to the breaking point. It was like the calm before the storm. But this was not a storm of revolution, like so many others in history. This was a darker, more violent storm—twisted, raging. It was a storm of desolation. There had been dozens of demonstrations, some of which turned into senseless riots. Celebrities were updating their Twitter profiles en masse, writing things like "Earth is mine, 1 more for 99." Slack-jawed Plan members were milling around outside hospital maternity wards wearing sheets scrawled with such slogans as LESS IS MORE. END REPRODUCTION NOW. The brutal stoning of a homeless amputee ("the Plan does not allow for the weak") was just one example of the escalating violence. There were large meetings in every city, held in universities and government buildings, in which "rational" lectures were led by smiling, serenely confident "experts," discussing the benefits of "selection." All of which, to Fang's utter disgust, the news outlets covered with a mix of excited panic and restrained approval. _They wouldn't be so approving_ , Fang thought, _if they really understood the extent of the 99% Plan._ Because through eavesdropping—and, okay, a couple of bribes—Fang had confirmed what he'd feared: These people, the remnants of the Doomsday Group and the By-Half Plan, wanted to reduce the earth to only the enhanced. That is, to exterminate the human race. Fang shook his head in revulsion, still unable to comprehend it. The same crazies from the past had somehow become _even crazier_. That was no surprise. But the American people were actually going along with it. Fang's fists clenched as he thought of all of the places he'd seen, the millions of people struggling through their individual lives, their loves.... All that beauty. All that history. And all these people, so eager to destroy it. # Book Two # [AND SO IT BEGINS](toc.html#toc-part002) # ANGEL HEARD JEB'S breath catch in horror. "They didn't," he said hollowly. "Not you, too. Not your eyes." "You're just upset because you wrecked your perfect little specimen," Angel spat, shoving away his hands and retreating farther into her dog crate. She still ached all over. Jeb clutched the door of the cage, shuddering so hard that he rattled the metal grid. "Oh, Angel..." "Save it." "It's like Ari all over again," he said brokenly. "So many failures... so many mistakes. You can't imagine the remorse I feel, Angel...." _It's your own fault_ , Angel thought, but she was almost surprised to hear tears in his voice. She couldn't remember Jeb ever crying, no matter what happened. "I was such a bad father to him," continued Jeb dejectedly. Angel bristled. Ari had been a disaster, that was for sure, but he was dead. Angel was the one who was here; _she_ was the one whose eyes had been ruined. His apology had been meaningless, but this little heart-to-heart about Ari was straight-up insulting. And he wouldn't shut up. "After Ari died, I just... I had to try again. I had to give myself another chance at being a father, at caring for a son. That's why I worked so closely with Dr. Gunther-Hagen." _Wait, what?_ Angel sat up straight inside her crate, her attention snapping back to Jeb. She forgot her anger for a moment. "You were creating another Ari?" "I swore this time I wouldn't fail. I would be a good father...." Jeb's voice caught in his throat. "And he would be a good son. I would retire from my work with the School and care for him with all my heart." And despite _everything_ , Angel couldn't help but feel the tiniest twinge of pity. Here Jeb was, a fully grown man, sobbing over his dead son. "You have to understand, Angel," Jeb pleaded. "I had only the best in mind. Just one new Ari. Then it would end." "But it didn't end," Angel whispered, thinking of the flying mutants they'd battled for months. "Well, of course there were many less-than-perfect attempts," Jeb conceded. "But Dr. Gunther-Hagen is an incredibly brilliant geneticist. With his help, I made Ari bigger and better than ever before, seamless and strong. Finally, I had my son back." Jeb wasn't crying anymore. He sounded almost triumphant. Triumphant, and something else. Angel felt the dread building in her stomach. "The not-Aris were useful, too," Jeb said. "Not as sons, but as warriors, designed for one mission, and one mission only." "Mission?" When he spoke, Angel could hear the cold serenity in his tone. "To eliminate Fang." # _"WHAT?"_ ANGEL FELT her skull prickle all over and her hands go numb. The air around her felt like it was vibrating, and she rested her head against the plastic wall of the dog crate, breathing deeply. With darkness consuming her vision, she couldn't see Jeb's face, but she could picture it clearly: the laugh lines around his mouth, a bit of stubble on his jawline, and his eyes—intelligent eyes that she had once known so well, that she had trusted, that even Max had trusted. The eyes that seemed well meaning, even when he was screwing everything up. She must've misunderstood him. "Wait— _what?_ " she said again, shaking her head to clear it. "Eliminate Fang... as in, _kill Fang_?" "That's what the 99% Plan is all about," Jeb said simply. He sounded calm. Creepily, eerily calm. The calm that comes with absolute certainty. It was terrifying. "Isn't 99% about _sparing_ the mutants?" Angel tried to keep her voice as calm as Jeb's, though her body was shaking all over. "How can that mean killing Fang?" "It's about the good of the planet versus the good of the people, Angel," he explained in an indulgent tone, as if they were talking about why she needed to share with others or conserve water. "You know I love Fang like another son." It was true—she had thought he did. Angel instantly regretted pitying him earlier. "Then how could you do this?" Angel asked, her voice rising. "I'll forgive you, Jeb," she said suddenly. She touched her eyelids again, choking back tears. "I'll forgive you, and everything that happened with Ari won't matter anymore. You can turn it all around. Just don't do this." She was gripping the bars of her cage, pleading with him. Jeb was silent for so long that Angel held her breath, a twinge of hope swelling in her. Then he sighed heavily. "No. He's too dangerous now. If he remains alive, his life will become a living hell." "But _why_?" Angel demanded. "Hans will see to it. Remember back in Dr. Gunther-Hagen's lab, when Fang almost died?" She nodded. It was one of her worst memories, even worse than the ones from when she was really little, in the School. "As a result of those tests, Hans has recently discovered something _truly extraordinary_ about Fang's DNA." "What kind of discovery?" Angel asked bleakly. Jeb had no answers, no explanations—only more vague justifications. She felt empty. "Something amazing," Jeb replied with such bright enthusiasm that Angel wanted to hit him. They were talking about the reason for Fang's _death_. "Something that would change the world." Suddenly, the soft padding sound of footsteps reached Angel's ears. Someone was coming toward them. "Yes, Angel, something that would change the world," a cool female voice said. "And now we need to find out if you, sweetie, have the same... _defect_." Angel felt like she was going to throw up. She knew that voice. Dr. Martinez, Max's mom, was at the School. # "REMEMBER, FIRST IMPRESSIONS are _key_ ," Total told me sagely. I stared. "Total, there is no first impression. I've been _living_ with the guy for like three months, for Pete's sake." He flapped his little black wings and sniffed. "Well, _excuse me_ for trying to help with your—might I remind you—first-ever date with Dylan." Rolling my eyes, I attempted to get a brush through my ratty hair for the umpteenth time. "It's not even a date." I sighed. "Dylan and I are _chaperoning_ Nudge and Sloan." "I bet Nudge would accept my advice graciously." "Perfect! So go talk to Nudge, then!" Total whined. "But unlike you, she already knows the ins and outs of being a normal teenager. You're the dysfunctional one here." I scowled. "Fine. Give me advice." "Ask nicely." _"Total."_ "Sheesh, no need to get all snippy," he said, pouting as effectively as a Scottish terrier can pout. "Just remember: No one likes a self-absorbed person. Always direct the conversation back to your date." "I already know everything about my... about Dylan," I said. I sighed again and wound my hair into a lopsided bun, then tried to jam in a couple of the chopstick-y things that Nudge uses for her hair. Welcome to the glamorous life of Maximum Ride, ladies and gentlemen. "Also, personal hygiene is a _must_ ," Total continued. We both looked at my messy hair, my stained jeans, my beat-up sneakers. "I'll get Nudge to choose an outfit for you," he muttered. I stared at my reflection in the mirror, trying not to panic. Do I need to repeat how awful I am at this—this normal girl stuff? No. I don't believe I do. But Sloan was a fifteen-year-old boy. I don't care how nice the guy might be, that's a walking hormonal disaster waiting to happen, in my book. There was no way I was just going to sit there and let him whisk Nudge away by herself, so to keep it from being horribly awkward, Dylan and I were double- _whatevering_ with them. _Kill me now._ "So what movie are you crazy kids seeing, anyway?" Total asked fondly. _"Blood City III: The Massacre."_ I'd read the summary of it online, and frankly, it sounded like the directors had just decided to film my life. "Perfect!" Total crowed, wagging his tail. "A horror movie! You can cling to Dylan during all the scary parts." Flabbergasted, I gaped at him. "First of all, sexist pig much?" I said. "I don't buy into the whole damsel-in-distress thing, especially when I've saved Dylan's feathery butt more times than he can count. Second of all, no. Just... no." Total ignored me and hopped up onto the counter and opened the medicine cabinet with his nose, taking out a little white box and pushing it toward me. "What's that?" I asked warily. Total winked. "Breath mints." # _"NOOOO!"_ ON THE screen, a woman's eyes bugged almost out of her head, and I tried not to scream. Tried not to scream in exasperation, I mean. The serial killer was right in front of her, wide open! Clearly, instead of weeping like a moron, she should be lunging forward and administering a swift uppercut to his chin. Then this entire pointless ordeal would be over with, and I could go home. Okay. I'll stop whining. It wasn't _that_ bad, sitting there in the movie theater next to Dylan. We were in the row directly behind Nudge and Sloan—partly so we wouldn't get separated, partly so I could knock Sloan unconscious if he tried anything—and, to be completely honest, I was feeling pretty relaxed. In a completely nervous, freaked-out way, of course. Because as soon as the words AND NOW... YOUR FEATURE PRESENTATION had flickered across the screen, Dylan had tentatively reached out and taken my hand. And I hadn't stopped him. So that was the situation: dark theater, warm hands, terrible blood-drenched movie, and so much tension between me and Dylan that it felt like my brain was about to short-circuit. Basically, I wasn't sure whether to just go with it and have fun (like a human) or panic and get the heck out of this pitch-black enclosed space (like a bird kid). So far, the human way was winning, but the jury was still out. To absolutely no one's surprise, the stupid bug-eyed lady got stabbed, and wailed dramatically. I turned to the side and made a face at Dylan. "Well, you can't blame her," he whispered, and his eyes flashed like blue coins in the dim half-light. "She hasn't exactly been trained for fights to the death." "Oh, come on! She still totally just sat there and let herself get stabbed," I protested. "In my humble opinion, she deserved it." He snickered quietly. "You may be the only person who's rooting for the serial killer." We smiled at each other, and that was when my usual harshness came slamming back into me with a jolt, making me bite my lip and focus on the movie again. _No time for blushing and admiring; make sure Nudge is doing okay! Check for escape routes!_ Sometimes my survival skills really get in the way of things. I stayed completely still through the rest of the movie, even when Dylan's thumb began tracing fiery circles on my palm, even when my heart started pounding so loudly I thought people six rows away could probably hear it. _Get it together_ , I told myself. _Be calm. Be Zen. You are Buddha._ Except I highly doubt that Buddha would be experiencing the same tingles down his spine that I was. And because of Dylan! _Someone, anyone, just put me in a straitjacket and be done with it._ Finally, the screen went black and the end credits started rolling. I shot to my feet, dropping Dylan's hand like a hot potato. "Okay, well, that was fun! Let's head home now!" "No way," Nudge said, frowning. "It's only nine o'clock." "Yeah," said Sloan. He nudged Nudge—no pun intended—and gave her a little smirk. "Let's you and me go back to my place." I choked, not sure whether to be horrified or revolted or amused. For one thing, if this guy thought there was even a _slim_ chance that I'd let him get his hands all over my Nudge, he was sorely mistaken. For another thing, gross. For a third thing, what "place"? Didn't this kid have _parents_? I mean, true, _we_ didn't, but we weren't exactly the norm. "No, I think we'll be going home now," I growled, grabbing Dylan's wrist and practically pushing him out into the aisle. "C'mon, Nudge." Nudge sulked, but she followed obediently, with a glowering Sloan right behind her. He probably hated me, which I cared absolutely zero about. He wouldn't be the first one. As soon as we stepped out of the theater and into the cool night air, I let out a sigh of relief. No matter how many amazingly attractive guys held my hand, no matter how many dates I went on, I would always, _always_ prefer to be out in open space, with room for flying. Unless, of course, that space was filled with three hulking figures. "We've been waiting for you guys," said Ari. # FOR A FEW moments, I couldn't even speak. All I could do was stare dumbly at the person who'd died in my arms. _Twice._ Ari. And he wasn't alone. Two big, snarling Erasers flanked him, looking oddly similar to their ringleader. "How are you... _alive_?" I asked shakily. Sloan visibly tensed at my words, and I remembered that, while undoubtedly a sleazy moron, he was still a relatively innocent human. If this turned into a fight, it would be bad. "I'm not a zombie," Ari said in his gruff voice. "Just a better version of myself." I tensed, my hands twitching. The previous versions hadn't been particularly pleasant. Ari chuckled. "Don't look so nervous, Max. I didn't come on this friendly little visit to see you, anyway." He looked pointedly at Dylan. " 'Sup, Dyl." "Do I know you?" Dylan cocked his head, confused and understandably wary. "Max? Who is this?" This weird man-wolf-child? I didn't really know how to answer that. Ari and I had been mortal enemies—his first death had been caused by me accidentally breaking his neck in a New York subway tunnel—and then we'd been kind of friends. And then he'd died. What was I supposed to make of this new Ari? When in doubt, play it safe. I narrowed my eyes. "Yes, Ari, tell us. Who are you this time? Good? Evil? Still deciding?" "Relaaax, sis. We're buds. My third coming is in peace. Actually, I already did you a favor." His wolfy grin just sent more adrenaline hurtling through me. "What kind of favor?" Ari crossed his arms proudly. "I killed your clone." " _Clone?_ " Sloan said shrilly, but we all ignored him. My stomach clenched. "You what?" I snarled, but I knew it was true even before Ari elaborated. " 'Fraid so," he said, smirking. "A scratch, a smash, wham, bam, Max II is dead—just like you always wanted." I swallowed. Admittedly, I'd flirted with the idea, but not for _real_. "Anyway, on to business," Ari said lightly before I could respond. He looked again at Dylan, who, taking a cue from me, had assumed a hostile stance. "Jeb wanted me to tell you not to worry about Dr. G.-H. and your little mission." "Jeb?" Dylan asked, clearly confused. "Jeb!" I exclaimed, my voice rising. "What does Jeb have to do with—" "We've got the situation covered," Ari said with finality, his eyes boring into Dylan's. I scowled. His smile was playful, but in his eyes there was a definite threat. "What does he mean, Dylan?" I demanded impatiently. Dylan shook his head, but he adjusted his stance almost imperceptibly. He seemed to be deciding whether or not to spring. "Someone had better tell me what's going on," I snapped, ready to fight both of them. _"Now."_ "What I mean is that I'll be defanging your buddy Fang." Ari finally looked at me, smiling cheerfully. Nudge gasped. " _What?_ " I exclaimed, heat rising to my cheeks even as my blood ran cold. "And I just stopped by to make sure I wouldn't have to add Dylan to the list while I'm at it," Ari continued calmly. "Maxy here can tell you I'm a bit hard to keep down." He flashed a conspiratorial grin. "So cease and desist, bud. Cease and desist." We all regarded one another suspiciously, and I tensed with growing fury and confusion. Ari wanted to kill Fang? And he was warning Dylan about it, even though Dylan _hated_ Fang? And somehow Jeb was involved? "Who's this Fang guy, and what do you mean, 'defang'?" Sloan asked nervously, a little slow on the uptake. "Like, you're gonna knock his teeth out?" Ari turned toward him and cracked his knuckles. "Naw, kid," he said. "I mean like I'm gonna tear his heart out through his chest." "That's it," I snapped, but as I lunged forward, Ari and his posse unfurled their wings, as if choreographed, and kicked off from the ground, hard. I began to shrug off my jacket to do the same, but Dylan reached out and put his hand on my shoulder. "You can't take him right now," Dylan murmured in my ear. "Too many people around." I eyed Sloan, who was stammering "Wh-what the..." next to a horrified Nudge, along with a small group of onlookers who were pointing and taking pictures. I ground my teeth, but nodded and took a deep breath, unclenching my fists. Fang could take care of himself, I reminded myself. He'd be _fine_. "Nice chatting with you guys," called Ari from above. "Remember what I said, Dylan. Cease and desist." And with that, he rose into the darkness and was gone. # I WAS JUST rolling into my third hour of sleeplessness when the door to my room creaked open. I was on guard instantly, bolting upright and wrapping one hand around my bedside lamp. Sound extreme? Not when you've been ambushed in your sleep as many times as I have. "Who's there?" I whispered. "Nudge?" She had been utterly devastated over stupid Sloan, crying for at least forty minutes after he had called her a freak and hightailed it out of the parking lot. I wouldn't be surprised if she wanted yet more comforting. Even if I wasn't necessarily the best comforter in the world. "No, it's me." Very recognizable voice. Completely unexplainable, what he was doing here, but recognizable. I put the lamp down and flicked it on. Standing in the doorway was Dylan, looking tired and rumpled and sheepish. "What the heck are you doing in my room?" I asked, incredulous. "It's past midnight. I'm _sleeping_." _Well, trying to._ We hadn't talked after Ari's little visit. I'd been too freaked out by his news about Fang, and too preoccupied with Nudge's tears, and then I'd stalked off to my room to try to make sense of things. No luck there. Dylan shuffled awkwardly. "I... was wondering... if there was any way I could... stay in here tonight." He mumbled the last words, but I still got them. I made a sound reminiscent of a dying cat. _"What?"_ "I hate being alone at night," he muttered while I gaped. "I know it's stupid and lame, but I mean—I'm not like you. I haven't been alive for fifteen years." The truth of that statement hit me harder than it should have. It was just so easy to forget that Dylan had been created only two years ago when he looked my age. "A lot's been happening lately," he went on in a rush. "Usually I'd just deal with it, but it's a lot to absorb, and I was lying there in bed thinking about all the screwed-up things that Ari guy said, and... I don't know." Yeah, sounded a bit like my evening. He looked up at me hopefully. "So can I stay in here? Just for tonight? On the floor or something." I hesitated a second more, then sighed heavily and gave a tiny nod. Relief crossed his male-model face. He came in, dragging his quilt behind him like a little kid, and closed the door quietly. "Thanks." He looked embarrassed to be needing something, to be this vulnerable. I could have eviscerated him just then, but I hadn't. Because I am a freaking _princess_ about other people's feelings. "No prob," I said. "Pull up a patch of floor." He shook the quilt out and lay down with a lithe grace, his smooth muscles rippling. I swallowed, trying not to think of how those arms had brushed against mine in the theater. He tucked his wings behind him as he lay on his side—none of us were back sleepers, for obvious reasons. With one hand he reached back and pulled the quilt over him. He looked big and strong and vulnerable and really, really... appealing. I flicked off the light and threw my pillow down to him. It landed on his face. "Thanks," he said again, pulling the pillow off and bunching it up under his head. "This is just for tonight." "Better be," I muttered, then drifted back to the thoughts that had been eating away at me. Everything that Ari had said had been growing larger in the quiet of the night. "Dylan?" I said after a few minutes. "Hmm?" "What did Ari mean, about 'cease and desist'? Why would he come looking for you if you'd never even met him before?" Dylan didn't answer for such a long time that I thought he'd fallen asleep. Finally, he sighed. "I don't understand any of it. I never understand why anyone involves me in anything." I rolled my eyes. I had little patience for self-pity, and if I'd had another pillow, I would've chucked that at him, too. "He said not to worry about Dr. Gunther-Hagen," I pressed, my voice sounding small and shrill in my ears. "Maybe he meant you shouldn't worry about being my perfect other half, like Hansy said. Maybe he meant you should stop pursuing me." "Maybe," he said quietly, and my heart thundered in my chest. I was glad I couldn't see his face in the darkness. "But I can't, Max. You know I can't." We were quiet again, each of us listening to the other's breathing. Finally, Dylan exhaled, long and slow. "Good night, Max." I stared at the ceiling, willing my thoughts away from his body, his breath. "Good night, Dylan." # FANG | DYLAN ---|--- Knows me better than anyone (both a positive and a negative). | Practically just met me (less blackmail material). Can completely trust him (probably). | Seems trustworthy (so far). Helps me stay tough. | Helps me admit I can't always be tough. Doesn't care about social skills. Like me. | A freaking social butterfly. Complements my antisocial behavior. Has eyes that seem to see inside me. Not good. | Has eyes that make me forget myself. Not good. Is capable of bringing the meaning of "irritating" to whole new levels. | Is capable of... pretty much the same thing. Almost like a brother (ack). | Not like a brother. At all. In any way. Closed off. | Makes darn sure that I know every single emotion going through his head. I don't know how to act around him anymore. | Easy to be around. Never told me he loved me. (Writing it in a letter right before he deserted me doesn't count. Coward.) | Loves me. And told me so. Right to my face. Gulp. Intense. Powerful. Moves in a way that makes me ache to touch him. | Strong. Beautiful. Looks at me in a way that makes me ache to... scratch that. Still having dreams about the way he kissed me. | Ditto. Don't know where he is right now. Because he freaking left. | Is right here with me. Now. Always. IT WAS A pretty complete list. The kind of list one makes when one cannot fall asleep because one's thoughts keep swirling through one's brain like a bunch of sparrows on crack. I put down my notebook, rolled over, and gazed at the floor. Dylan had rolled over onto his other side and was facing the opposite wall, his quilt balled up at his feet. He was a turbulent sleeper. Unlike Fang, who was quiet and self-contained. I started to add that to the list, but then thought, _Who cares?_ I frowned at Dylan's sprawled limbs. He couldn't possibly be comfortable. He was probably cold. "Hey... you cold down there?" I whispered, leaning over the edge of the bed. He didn't answer. Seeing as how he was asleep and all. I watched his breathing, slow and steady, the shadow of his abdominal muscles rising and falling under his bunched-up T-shirt. I tried to slow my own breath, but it thundered quick and ragged in my ears. Before I knew what I was doing, I was out of bed with my own comforter. I felt sorry for him. Yeah, that was it. Really sorry for him. As anyone would. The floor was freezing against my bare feet. I padded over to Dylan and carefully lay down next to him. He shifted, coughing, and I froze. After two long minutes, satisfied that he was still asleep, I curled myself into him, drawing my comforter over us both. I felt the warmth of his body against mine, his breath on the back of my neck, making the tiny hairs rise. We fit like two puzzle pieces. Just like we were supposed to. The whole designed-to-be-my-perfect-other-half thing... Gah. But you know what? Just this once, I was going to shove away all my angst and confusion and fear and just focus on the present. Which happened to be very warm. Maddeningly warm. My whole body felt tingly. With that thought in mind, I pressed myself closer against Dylan's sleeping form and closed my eyes, drifting into the sweetest sleep I'd had in a long, long time. I wasn't sure I ever wanted to wake up. # THE NEXT DAY at school was, predictably, a complete horror show. Not for me (for once), but for Nudge, who'd been publicly spurned and ridiculed by Sloan, in front of all of the popular girls. In less than a minute, this new gossip was all over Facebook and Twitter. About eight hours later I was rapping my knuckles against the door to Nudge's room. As soon as we'd gotten home from school she had gone in there and locked the door behind her, and she didn't come out for dinner. I couldn't blame her—things had only gotten worse after Sloan's scaredy-cat retreat. God, I should've unleashed a can of whup-ass on him. "Nudge? Come on, open the door. Let's make popcorn." "Go away," came Nudge's weak voice. "Don't wanna talk about it." "We don't have to talk about it," I said. _Please, no—no more talking about it, I beg you._ "I just want to make sure you're okay. Open up, will you? We can make hot chocolate." After a few moments of silence, I heard her trudge across the room. The door opened. Nudge's face was stained with the tears she'd been holding in all day; rivers of mascara ran down her cheeks. Her big brown eyes were puffy and bloodshot. I had no idea what to do. I'd already offered popcorn and hot chocolate. What else was there? "It's just getting worse and worse," moaned Nudge. "First it was just stupid gossip. Now I'm an outcast. They all think I'm some kind of circus sideshow. As usual." "Come here," I murmured, putting my arms around her. "I know it's a drag to have everyone at school treat us like lepers"—to put it mildly—"but they're just gullible, prejudiced jerks. Typical Avian-American prejudice." I eased her head onto my shoulder, which I should have lined with paper towels first. "I'm really sorry Sloan was such a butthead," I said soothingly. "But sweetie, he's so unworthy. You deserve better than that. You deserve someone who's going to love you, wings and all." I'd hardly ever seen such sadness on her face. "That's easy for you to say. You have _two_ guys who love you." She looked up at me, and I didn't know what to say to her. "I don't have _anyone_." I swallowed nervously. Guiltily. "That's not true. You have _us_ ," I blurted out, knowing full well how lame that was. The flock was awesome and all, but it just can't be compared to the rapture of being loved, held, adored. In that... _different_ way. I quickly shook off the pleasurable shiver that shot down my spine as I remembered spending the night on the floor next to Dylan. "Listen. Soon we'll blow this Popsicle stand and move on, and then you'll never have to deal with any of them ever again. Until we get rich and famous, and then you can have fun spurning them when they beg for your autograph." I smiled, pulling her close, but Nudge wasn't amused. "I don't _want_ to move on," she cried, pulling out of my arms. "Can't you see that? I don't want to 'spurn' them!" She made air quotes with her fingers, glaring at me. How had I become the enemy here, exactly? "I just want to—" Her voice broke, and she drew in a trembling breath. "I just want to be _liked_ by them, Max!" And then Nudge burst into tears. Again. Crap. "Oh, sweetie," I said helplessly, uncomprehending. I had spent very little energy in my life trying to be liked by anyone. "Come here. Come sit down," I said, taking her hand and tugging her toward the bed. Then I saw that the entire thing was covered with crumpled-up pieces of paper. A pair of scissors was lying on top of a stack of teen magazines, all of which had been mangled and cut to pieces. "Nudge? What's this?" Nudge blew her nose miserably and gestured at a pile of blocky, badly cutout shapes. "Those are for my scrapbook." I picked up one of the shapes. It was a photo of a pretty teenage model, smiling brightly at the camera, wearing some sort of sparkly outfit with furry boots. "Blech," I said, and put the photo down. The next photo was another pretty model. So was the next one. And the next. "What kind of scrapbook are you making, exactly?" I asked Nudge cautiously. Her bottom lip quivered. "I want to be like them. Like those girls." I raised my eyebrows. "You want to be a model?" "No." She sighed dramatically, rolling her eyes. "I want to not be a _freak_." "Nudge, normal is way overrated...." I began. Déjà vu. "Oh, yeah, it's superlame to just want to have friends, to just want to be kissed, like everyone else." She laughed bitterly. "You sound like the whitecoats. Being lab experiments doesn't make us better, Max. We aren't _enhanced_ , we're _mutants_." Wow. I had to remind myself that this was not the sweet Nudge I knew. This was a love-scorned girl who had just been through a day of despicable bullying. I was lucky she wasn't actually breathing fire. "And if we were normal, there wouldn't be people trying to kill us," she pointed out. "Well, probably," I admitted. "But I _guarantee_ you people at school would still do mean things to nice kids for no reason. That's just the way life works." Nudge shook her head. "No. You know what? There's only one answer to all our problems." This didn't sound good. "What is it?" I asked warily. She snatched the scissors off the bed and looked so utterly reckless that it sent me into a panic. "Nudge!" I gasped. But Nudge turned from me and eyed a poster on the wall—a publicity poster of the whole flock, from our days as a flying sideshow—and then, lightning-quick, she let the scissors fly with as much skill and fury as she'd displayed battling Erasers. With a hollow thud, the blades struck the image of Nudge's wing and embedded themselves deep in the wall. I swallowed, my throat suddenly dry. My own wings twitched under my shirt. Then she clutched one of her normal-girl photos to her chest, her eyes fierce with determination. "The only answer to all our problems is getting rid of our wings," she said. "Removing them forever. I'm gonna do it someday, Max. I swear it." # FANG OPENED HIS eyes blearily. Above him was nothing but the clear night sky, dotted with millions of tiny glittering stars. It was beautiful. It was quiet and calm, and yet for some reason he'd woken up. He sat up, quickly scanning his surroundings for anything threatening, anything that might have made some sort of noise. Nothing. He still found it weird, nowadays, to wake up alone. Until this past year, waking up had always meant being flung into the noise and chaos of the flock. The flock. Fang had thought that it would get easier, being away from them, as time went on. He'd thought wrong. He'd thought that they'd be fine—even better off—without him, and that it would be easier for him to pursue whatever mission he had if he didn't have to worry about them. Now he wasn't sure. And then there was the gang. Fang sighed and lay back down, making hardly a sound on the dew-dampened grass. Why had he ever thought that would work? Why had he tried? The gang had gotten Maya _killed_. Fang swallowed and closed his eyes. Maya was dead. And though Ari kept demonstrating a freaky, jack-in-the-box ability to come back from the dead, Fang was pretty sure Maya was gone for good. And the others—he'd really let them down. Fang frowned and pulled his jacket tighter around himself, turning onto his other side. He wasn't used to letting people down. He was used to coming through for people. He'd thought being on his own meant that he could make all the decisions by himself, that he didn't need to rely on Max to do all the thinking. The bad thing was that he had no one to discuss decisions with, no one to bounce ideas off of. _Admit it, you idiot—it's more than that. You miss her_ , Fang thought. He sighed and rolled onto his back, restless. He was exhausted, thinking about it all. But not exhausted enough to fall back to sleep. _She doesn't need you_ , he reminded himself. _She has the Winged Wonder by her side. Maybe being on your own is just too hard?_ No, he couldn't think tha— _Fang._ Fang jerked, startled, and peered into the dark trees and shrubs around him. _Fang, nobody's there._ Oh, man. The voice—or rather Voice—wasn't coming from around him. It was coming from _inside_ him. Not again. He had to wonder—was this the same Voice Max got? Where did it come from? Why was it appearing in his brain _now_? Sure, all of them had heard the Voice at one time or another. But Fang definitely didn't want this to become an everyday thing. _Okay, what is it?_ Fang thought. _What do you want?_ _It's time to go, Fang_ , the Voice replied. _She does need you now, more than ever._ _Who needs me?_ he asked, but he already knew the answer. _Go home to Max._ # "IS SHE IN trouble? Are the others okay?" Fang demanded aloud, sitting up, alone in the darkness. _What's going on?_ he screamed inside his head. But the Voice stayed silent, in that incredibly annoying way it had. It was gone. For how long, he didn't know. _Go home to Max._ He had no idea if something was really wrong, but he couldn't exactly ignore the Voice, either. When Max heard her Voice, she pretty much always listened to it. His Voice was saying that Max needed him more than ever. He pretended he didn't feel the way his heart was speeding up with excitement and anxiety, just thinking about going back. No doubt his replacement would still be there, being all Dylan-rific and glaring at Fang with narrowed eyes. Well, too bad. What choice did Fang have? None. He would've liked to have just taken off right then, raced back to the flock. To Max. To see that she was all right. But Fang's wing had been bothering him more and more, and he definitely wasn't in flying shape yet. So he'd be patient. He'd find the nearest town and then get on the Internet. He would do some research before he went racing back to the person he kept trying to leave. Two hours later the sun was just beginning to rise, and Fang was seated at a computer in an Internet cafe. He sipped from a Styrofoam cup of coffee as the Google home page loaded. Then he typed in two words: _Maximum Ride_. # INSTANTLY, RESULTS POPPED up on the screen—1,704,890 of them in 0.43 seconds. The very first one was an article titled "Winged Children Attend Private School!" Oh, great. Looked like more of that successful "keep a low profile" stuff was going on. Fang clicked the link and began to read. As it turned out, the article was a piece from the private school's own online newspaper, the _Newton News_. It spewed out a bunch of glorified info about the flock, accompanied by a hilariously cheesy photo of them posed around the school's marquee, beneath a banner welcoming "Maxine and Co." Fang almost snorted—and then he saw that Dylan had his arm casually thrown around Max. It was surprising how much that hurt. Especially on top of the news that Gazzy had blurted out in Paris—that Dylan had been "designed" for Max, and that they were eventually supposed to go out and create little Maxes and Dylans. The concept was still impossible to swallow. Still tasted like crap in his throat. Fang logged off the computer and dumped his half-finished coffee in the trash. It may have been corny and lame, but the _Newton News_ article had given him one thing: the exact location of the flock. His Voice had told him to go to Max, even though it sure didn't seem like she needed him, all safe in her cushy new digs, with her new boyfriend. Didn't the Voice know how much it hurt Fang to see her? Didn't it know how much he hurt her every time he left? Maybe it did. Maybe that didn't matter. Maybe something bigger than just the drama of Max and Fang was happening. At any rate, he knew he had to listen to his Voice. He had to go back to Max. Whether she wanted him there or not. # FANG DIDN'T WANT to admit to the little surge of exhilaration he was feeling at the idea of actually going back to the flock. _Home._ He had tried to put Max out of his head for so long, but for him, "home" would always mean wherever Max was. It was still barely light. It galled him that he couldn't fly, and instead actually had to hike out to where the main highway passed the town. He shook his head, thinking of Ari and his cronies. He wouldn't be surprised if the price on his own head was so high that it had infiltrated the backwoods of Middle America, too—Fang knew any driver on the road could be a threat, and it was incredibly stupid for him to hitchhike. But with his painful wing, what choice did he have? He was in the middle of No and Where, and he had no hope of catching a plane or a bus—or even of stealing a car—in this place. He had to get back to Max, so hitching it was. After an hour and a half spent trudging along with his thumb in the air, Fang's head snapped up at the sound of wheels far down the road. A yellow convertible was speeding down the highway, music blaring. This time, the car pulled to a slow stop just ahead of him, and he jogged up to it. Three beefy-looking guys peered out of the convertible at him, and Fang felt a twinge of anxiety. _This is stupid_ , a voice inside him said, and he couldn't tell if it was _the_ Voice or just his own rational thought. "Need a ride?" the driver asked gruffly over the metal music thundering out of the speakers. Fang glanced down the road. Not a single other car in sight. "You heading west?" he asked the driver, frowning. "Yeah." Fang sighed. The next city was at least twenty miles. It was now or never. "Then yeah, thanks," he said, hopping into the backseat. Before he'd even sat down, the driver jammed the pedal to the floor. Fang surged backward into the seat, his wing throbbing. "Hey, watch it!" Fang snapped irritably, but the driver just stared straight ahead with a tight-lipped grin. The guy in the passenger seat and the guy beside Fang both stared at him intently, their muscles bulging in their tight T-shirts, their faces twisted into weird expressions. They looked... hungry. Almost like—Fang's mind balked at the possibility—Erasers? Or was he just seeing things? It was hard to tell. He didn't trust his own judgment anymore. After Star and Kate's betrayal, everyone seemed suspect. He stared into the pockmarked face next to him, at the thick neck running up to a crew cut. No. They didn't have the right amount of feral wolfishness marring their features to be Erasers. These guys were definitely human. Ugly as all get-out, but human. So why were they acting so funny? Maybe they were just 'roid heads, Fang thought—crazed on testosterone. He was just being paranoid, that was all. _It's called_ careful _, you moron_ , he imagined Max chiding him. _Always trust your instincts. Paranoia is our way of life._ But Fang's wing hurt, and he was tired, and at the moment there wasn't a better option than these shady characters. Shady _human_ characters, who he could surely take if it came down to it. Barely five minutes later, the convertible skidded to a stop. "Wow! A scenic overlook!" the driver shouted with over-the-top enthusiasm. "Whattaya say, boys? Should we get a closer look?" Fang's eyes snapped open. Something was off. These guys didn't exactly seem like the postcard type. # THE THREE GUYS hopped out of the car and strode toward the signs warning pedestrians to keep back from the railing. "Check out this wicked cliff, fellas," the driver said to his two grinning buddies. They laughed as if he'd just told the most hilarious joke they'd ever heard. "Hey, kid," he called to Fang, "why don't you come over here? I think you'll really wanna see this. You know, up close and personal." Fang, leaning against the convertible, shook his head. "Nah, I think I'm fine right here, thanks." He assumed a more defensive position and crossed his arms, but even that small gesture made him wince as his wing bone bent awkwardly. What was _wrong_ with him? The driver grinned. "How's that wing, Fang? Must be giving you some real trouble if you're stooping to hitchhiking. Really slumming it." "I'm sorry, do I know you?" Fang asked as casually as possible, but he eyed the trio warily. His instinct had been right. They knew who he was, and they were out to get him. But he could take these guys. If he could fight Erasers, he could definitely handle a few juiced-up punks. "We're not important, Fang," the driver said soothingly, still looking starved with those hollow eyes. "We're just part of the Plan. But _everybody_ knows _you_." He took several steps toward Fang. "You'll be the first, after all." "Let me guess," Fang said, his dark eyes narrowing. "The first to die." They charged him then, and relying on instinct rather than thinking, Fang snapped out his wings, his mind calculating rapidly. He'd do a quick up- and-away and jump behind them. He would knock their heads together, leave them sprawled on the asphalt, and beat it out of there. But that's not what happened at all. Instead, with that careless wing snap, his injured wing bone ground against itself. Fang groaned in agony and involuntarily hunched over, scrunching his eyes shut as the pain vibrated through him. And that's all it took. In the next second they were on him, wrenching his arms backward and digging their elbows into his neck. The driver was violently twisting his hurt wing behind him, and he saw black spots at the same time he felt his knees buckle. Fang swore through clenched teeth as they started to drag him. He cursed these guys, cursed being alone, cursed the Voice for putting him in this position. This was a perfect storm of crap, all flying through the same fan, right at him. The three of them worked together to pull Fang to the stone ledge beyond the safety barrier. He felt a singing panic in his veins as he neared the edge of the cliff. This was usually where he would show up to save someone, or someone would show up to save him. But no one was coming—that was horribly clear. He was more alone than he'd ever been in his life. The three of them heaved Fang up onto the ledge, kicking and swearing, realizing with growing horror exactly what would happen if he didn't escape _right now_. He gave another sudden jerk, surging against their grips with all of his strength, and... they let go. Suddenly, he was free. Free- _falling_ , that is, hurled into empty space, toward the crashing waves of Lake Michigan, broken wing and all. Right off the edge of the cliff. # ANGEL SCREAMED FOR what felt like eons, until her own wordless howl hurt her head so much that she shut up. Her throat was raw, her eyes like sandpaper and still unseeing. She'd had another horribly real nightmare—this time, _Fang_ was the one who was dead. She'd seen him falling, falling.... Just like she'd seen Maya. And now Maya was dead. Angel winced, pressing fingers to her throbbing temples. She lived her own nightmare while she was awake, and she lived others' nightmares when she slept. There was no escape. No escape, ever... _Fang._ Angel concentrated, but she couldn't figure out the ending. She wanted to see, _needed_ to see what happened next, even if it was as bad as she feared it was. But she couldn't. In her vision, Fang was in a different place than last time. Instead of an empty red desert, the scene had been misty and chilly looking. Instead of the two girls from his gang, there had been three guys there, guys she didn't recognize but instinctively hated. There had been a car. A sunshine-yellow convertible. And there had been a cliff, dropping sharply and hopelessly down. Angel felt tears prick her eyes as she relived the last part of the vision. What stuck with her most was the way they'd smiled, those three guys. They'd been beaming like lunatics as they hurled Fang over, leaning over the ledge to watch him fall. Angel had waited impatiently for Fang to spread his wings and soar away—grinning triumphantly at the evil humans who'd thought they could hurt a _bird kid_ by tossing him into the open air. _Ha, ha, morons! Eat my wind!_ But... he hadn't. Hadn't smiled, hadn't taunted them. _Hadn't_ spread his wings and soared away. He'd just dropped, his body twisting and turning awkwardly in the air. He'd looked broken. Angel had screamed herself awake from the nightmare right before Fang hit the ground. _But maybe..._ A tiny part of her whispered, even as she tried to block it out. _Maybe it hadn't been a nightmare after all. Maybe it had been a... vision._ No. No way. She squeezed her eyes shut. "It was a _nightmare_ ," she said aloud. "It wasn't real." _Like now_ , she thought. Like the nightmare she was in the middle of living. Right then a screeching, grating sound filled Angel's ears, like fingernails on a chalkboard. "Not real, not real," she whispered, even as she shrank back into the shadows of her dog crate. Moments later, the door to her crate swung open. She pulled herself against the back wall as tightly as she could, ready to come out kicking and punching and screaming. She expected to feel human hands clenching her, but the sensation was cold, hard, and flat—terrifyingly mechanical. Two large metal paddles had reached in with an awful, gear-grinding sound. They practically filled the crate—there was no way to avoid them. Angel ducked high and low, but eventually the paddles closed in on her, clamping onto her body firmly, leaving her no room to writhe or wiggle free. With more metallic grinding, the paddles began to retreat, dragging Angel out of the dog crate roughly. Then she found herself suspended in midair, held up by what must have been two warehouse cargo-moving forceps. She shouted and twisted this way and that as she moved through empty air. Then she was dumped unceremoniously on a hard surface. She felt the crisp sheets crinkle against her legs and almost wept with defeat. An operating table. Again. She was too exhausted to struggle. What was the point? They would find a way to make her cooperate. She had no more tears left, so she lay dry-eyed as her arms and legs were clamped to the sides of the table. "This is for your own good," someone told her—a whitecoat whose voice she didn't recognize. "We need to make sure there's no way you can escape these tests." Angel's heart clenched. More tests. What could they possibly do now? Hadn't they already taken samples of skin, bone, blood, and feathers? How could they not know every square inch of her, down to the cellular level? Another pair of cold metal forceps moved along her shoulder blades. They reached under her back, then forcibly unfurled her wings, pulling them out from beneath her. Her wings, too, were clamped to the operating table. She tried to fight the nausea, but felt bile rising in her throat. They'd never done this before. Never. A whole new level of fear streaked through Angel's body. She realized what was coming right before it actually happened. Small snipping noises filtered into her brain, followed by a pinching sensation at her primary feathers. "Done," the whitecoat said. "Good little mutant." He left the lab, his footsteps fading away as the door closed, leaving Angel clamped to the operating table. She remained silent the entire time, mute with shock and horror. They'd clipped her wings. # _EVERYTHING IS ABOUT to change_ , the Voice said. _Prepare yourselves._ Every single member of the flock heard it. _Your task is to record what happens._ Nudge yelped and dropped the bottle of glue, leaving a glittery blue stain on her scrapbook. "What—" she began, but was interrupted by the Voice. _Write, blog, take videos on a cell phone—it doesn't matter. Just make sure you record everything, down to the last detail. Everything. You have to record it all—for the future._ A Voice in her head. Another huge clue that she was a freak. Nudge wanted to cry, wanted to scream at the Voice to leave her alone, to let her at least pretend to be kind of normal! Nudge clenched her jaw and determinedly went back to making her scrapbook of normal, wingless girls. _Nudge, this is about the future. In the future, you_ will _be normal. In the future, you might even get sick of feeling average. But right now, the world needs you._ The Voice sounded unusually gentle. _This task is the most important thing you will ever do for humankind. So get up, grab your phone, and start keeping a log—for the future._ Nudge hesitated. This felt really urgent. She didn't want any part of this. But she knew one thing: Max never went against the Voice. Nudge sighed, her shoulders slumping. There would be no normalcy today. "Okay," Nudge said, defeated. "Okay." _Don't let Max out of your sight._ Iggy and the Gasman, in separate rooms, both sat up, listening. The Voice. They'd heard it only once or twice before. They were hearing it now. Like before, it seemed important, vital, that they do what it said. _You must protect Max at any cost—even your own lives_ , the Voice said. _She must survive to lead. The calm is over. The storm is on the way, and the skies will break open with its force. Do you understand?_ _Not really_ , Gazzy thought, peering outside at the blameless blue sky. No menacing dark clouds, no swarms of locusts, no angry mobs. But he knew the Voice was right about one thing—he needed Max as a leader, and if her life was in danger, he was absolutely willing to protect her from weather or whitecoats or whatever else came along. Gazzy stood up, ready to go find her, then hesitated. _Don't let Max out of your sight._ Did the Voice really mean never _ever_ let her out of his sight, no matter what? Surely Max would need bathroom breaks? What had the Voice said? Protect her with his own life! Well, of course, and that sounded like they would definitely need explosives before too long. But... In the kitchen, Iggy was holding a mixer blade as cake batter dripped, unnoticed, onto his shirt. He had to protect Max? Even at the cost of his own life? He cocked his head, listening intently. He could hear nothing out of the ordinary—no vehicles or choppers on their way, no one shouting alarms. Total wasn't even barking, not that he usually did. But for some reason the Voice needed his help. Right in the middle of this cake. "Okay. She'll survive without my help—she's too stubborn to die," Iggy muttered. "But I'll protect her anyway." _Good._ _Harden your heart._ _Why, hello there, Voice_ , I thought snidely. _It's nice to see you, too. How's tricks?_ _There's no time for jokes, Maximum. Time has run out. The end is here, Max. Now._ I stopped slashing wing holes in the back of a hoodie and frowned. _The end? Like the apocalypse? No offense, but if I had a nickel for every time I'd heard that_ — _This is no time to be getting soft, to let your guard down, Max. You're not as paranoid as you used to be. You're not as strong._ _Hey, I am_ just _as paranoid as I ever was_ , I thought defensively. _Our life here just happens to be on the calm and peaceful side of the spectrum. For once._ _Listen very closely, Max. Your task, at the end, is to harden your heart._ _Harden my heart? Like,_ further _? Isn't that what everyone has always complained about with me? Now it's a_ good _thing?_ _Lives will be lost. More than you can imagine. In order to survive, you must harden yourself against their suffering. Lose the softness. Become the fearless leader again._ I scowled at the implication that I'd ever been less than a "fearless leader," but I had to admit, I was rattled—as much by the Voice, whose word I'd always taken as gospel, saying that the end was finally here as by the Voice, who had told me I had to save the world in the first place, telling me to put myself first. My mind recoiled at the confusion, and at the Voice's hardness. Its certainty. I waited for the Voice to say something else, but it was silent—apparently my brain was only mine again. As messed up as that sounds. Dread gnawing at my insides, I pondered my task: to harden my heart. Come what may. # _EVERYTHING IS ABOUT to change._ Dylan paused the video game he was playing. He looked around, but no one was near him. _Prepare yourselves._ Was this his... Voice? He knew Max, and possibly the other members of the flock, had heard it before, but this was totally new to him. _Um... what do you want?_ he thought. For a second, he was almost excited. It was like he was one of them—even more like Max—now that he had a Voice, too. But his excitement quickly went cold. _You have a task ahead of you, Dylan. One that only you can perform. One that you must perform. Do you understand?_ This sounded familiar. Dylan fought a wave of nausea as he remembered Dr. Williams describing the other task he had to perform—bringing Fang in for a life of torture. Now this weird Voice in his head was demanding something else of him that he supposedly couldn't refuse.... _What is it?_ Dylan thought with dread. The answer wasn't anything he would have predicted. _You must fully win Max's heart. The survival of the world depends on it._ Dylan groaned and dropped his head into his hands. "Like I haven't been trying!" he said aloud, exasperated _. Is that all? Sure you don't have any dragons I can slay instead?_ A nice, solid, physical goal. That was what he needed. He was pretty confident about his physical abilities—flying skills, fighting technique, speed, strength. But Max's heart... Max was an enigma wrapped in a puzzle wrapped in a cipher. Or something. He'd been trying to win her over ever since he'd joined the flock. Every once in a while, it felt like he was making headway. Dylan's face flushed as he remembered the few mind-blowing kisses they'd shared. But then she would back off again, and he would be left wondering what he'd done wrong, and if he would ever, _ever_ get it right. Now the Voice, the not-to-be-ignored Voice, was saying he had to somehow step up his game and actually win Max's heart. For the sake of the entire world. Dylan felt panicky. It wasn't like winning Max's heart was taking one for the team. It was the only thing he'd ever wanted. But until now, he'd never been afraid of what would happen if he failed. # _GOING ON A dream date is not exactly "hardening your heart," Max_ , I thought to myself uneasily, remembering the Voice's creepy warning. If being closed off were an Olympic sport, I'd have more gold medals than I could carry. But this whole heart-hardening gig simply was not happening. Not now. Not tonight. Because, despite my usual reaction to all things girly (eye roll, look of disgust, general feeling of nausea), tonight I was positively giddy and swooning. I couldn't help it—I had seriously underestimated the effect a little romance can have on a girl. Dream date. Unlike the general population, my idea of a dream date would once have been simply defined as not eating roasted lizard or Dumpster scraps for dinner. But my first (second? Did the one at the movies count?) "date" with Dylan was certainly more than that. Much, much more, in fact. I stared up at the sight before me, jaw on the ground and eyes bugging. See, when Dylan came up to me after school and said "Follow me," I thought, _What the heck? I'll just go ahead and follow the guy, let him show me whatever fascinating new discovery he's made._ I had expected him to demonstrate that he could fly backward or show me a cool rock formation he'd found—something like that. Let me tell you: I was not expecting _this_. "H-how did you...?" I stuttered. We were nestled within the branches of a huge fir tree, about thirty feet up. I felt the warmth of Dylan's hand on my lower back, steadying me as I leaned backward and gaped up, still trying to take in all the amazing details of the house. _My_ house. "I've been building it ever since we got here," Dylan said, smiling shyly at my speechless astonishment. "I went exploring the first day and found this tree, and I knew you liked tree houses...." I grinned dopily at his perfect face, his soft, anxious eyes. _I knew you liked tree houses._ Dylan had taken the time to listen to what I liked, had been making notes about things that made me happy. The guy had actually been _paying attention_. And this... this was more than a tree house. It was like the Swiss Family Robinson tree house, Oregon edition. It had a floor, walls, windows, a roof. All of it was beautifully constructed out of branches and planks, and sort of camouflaged with leafy twigs and vines. From the ground, it would blend with the rest of the tree canopy. But from up here, on this branch, it was stunning. I saw a doorway covered with a green cloth curtain. "Come on," Dylan said, taking my hand. Together we leaped the fifteen feet from the branch to the balcony that ran around three sides of the tree house. Dylan held open the door curtain and the warm glow of candlelight flowed out into the deepening dusk. That's right—candlelight. The whole shebang. I swallowed and stepped inside. When Dylan dropped the curtain, it shut out the rest of the world. Dylan and I were alone, out here in the mountain woods, a five-minute flight away from Newton and the rest of the flock. Dylan looked at my face intently, as if trying to read my expression. I felt the flush creeping up my cheeks, my heart getting all loud and poundy. The combination of the violet dusk and the yellow candlelight made his features even more unbelievably gorgeous. I turned away from him and walked around the space, running my fingers over the gleaming wood, seeing the notched joints, the clever design. It wasn't huge inside—maybe eight feet by eight feet. But it was cozy, and plenty big enough. _For what?_ I wondered. "I stole the supplies from woodworking class," Dylan said, answering my unasked question. "Do you like it?" "I _love_ it," I murmured, with more ache in my voice than I'd intended. "It's so th—" I stopped and sniffed the air. "So th...? _So th_ what?" "Do I smell... food?" "You do indeed," said Dylan. "Roast chicken, pasta, buttery garlic bread, and—" " _Chocolate cake?_ " I moaned. There was a short, square table in the middle of the room, set up with two pillows to sit on. To the left was a low shelf holding everything my hypersensitive-when-it-comes-to-sniffing-out-all-edible-things nose had caught, plus more. Dylan's face lit up with another grin, and he made a sweeping gesture for me to sit on one of the pillows. I sank down, starting to wonder if this was just an elaborate dream my traitorous subconscious had concocted. No one had ever done anything like this for me before. No one had ever gone to so much trouble for me. It was... unnerving. I looked up at Dylan and felt—what? Gratitude. Gratitude and pure happiness. Right there, in that moment, _he_ seemed too amazing to be real. Dylan sat down on the other side of the table and passed me a plate—a _real_ plate, not, like, a paper one—and a glass of sparkling cider. It was so prim and proper I almost— _almost_ —wished I was wearing a dress or something. "Eat dinner with me?" Dylan asked shyly. I could feel the heat of the candle between us as the reflection of its flame flickered gorgeously in his eyes. "Heck yeah," I said as normally as possible, ignoring the fact that my heart was rumbling even more than my stomach. "Pass the chicken." We spent the next few minutes in silence as we worked our way through the delicious dishes in a way that only calorie-starved mutants avoiding sticky emotions and heightened sexual tension could. I was on my last bite of my third piece of chocolate cake when Dylan leaned toward the window and stuck his head out into the night. He whistled, low and long, like a Native American signal or something. _Wha?_ I thought. And then Iggy appeared in the doorway, carrying a silver platter and—get this—wearing a bow tie. I kid you not. Okay, the bow tie was worn over a ratty, laundry-deficient T-shirt, but still. "Iggy?" I said, stating the obvious. I shifted awkwardly, eyeing the candlelight and suddenly relieved that I was still in my plain old jeans after all. I imagined the flock gathering later, singing "Maaax has a boyyy-friiiiend" in chorus. I guess our date wasn't as private as I'd thought. I didn't know how I felt about that. "Thanks, man," Dylan said, striding over and taking the platter. "You know you weren't required to wear a bow tie...." "Sometimes a man just has to suit up," Iggy replied. He crossed his pale arms and puffed out his chest proudly. "This was one of those times." "And I appreciate it." Dylan nodded, obscuring the mysterious new platter from my sight. "Thanks again. You remember the next part of the mission?" "Mission Entertain Gazzy and Nudge So They Don't Get Bored and Cause Major Property Damage or Worse is well under way. You and Max are good to go, dude." "Good to go where?" I demanded, but Iggy just wiggled his eyebrows at me. With one last salute and a tweak of his bow tie, which he had gotten from God knows where, Iggy ducked through the door curtain and flew off into the dark night. Dylan came back to sit across the table from me. He set the platter between us and took off the lid, revealing neat piles of graham crackers, chocolate bars, and marshmallows. "I've always wanted to try to make s'mores with a candle. Shall we?" "You've thought of everything, haven't you?" I said, simultaneously reaching for a marshmallow and popping a graham cracker in my mouth. "Well, I tried." Dylan smiled. Then his expression grew slightly more serious. "I swear I'll win your heart in the end, Max." I coughed out graham cracker crumbs. My cheeks flushed and I tucked a piece of hair behind my ear. Suddenly I felt squirmy and smoldering and turbulent inside, like a million hot coals had been poured into my stomach. But to be honest, it wasn't such a bad feeling. # "I DON'T THINK the candle-marshmallow thing is working," I said. "I've been holding mine over the flame for, like, a billion years now, and it's barely browning." The air was soft and cool and smelled like rosemary and pine sap and smoke from the candles. Outside the tree house, it was a pitch-black night. Inside it was all cozy, golden light, flickering shadows on the walls. I practically had to stop myself from hyperventilating from the sheer _romance_ of it all. "We might be forced to eat raw s'mores," Dylan agreed solemnly, but I saw the crinkles at the corners of his eyes when he looked at me. That was when I realized just how close we were sitting. "You know, some people really like raw s'mores," I mumbled, licking my lips. And then, before I could talk myself out of it, I dropped my marshmallow on the table, leaned forward, and kissed Dylan. Right on the mouth. On purpose. Yes. You read it here first. For a second he was startled, but then he responded, bringing his hands up to cup my face. His lips moved against mine slowly, gently, softly. It was a quiet kiss. A tentative kiss. An innocent, feathery, earth-shatteringly _right_ kiss. And I wanted more. I edged closer to him and wrapped my arms around his neck, tangling my fingers in his dark blond hair. I tasted the chocolate from the s'mores on his tongue, and our mouths moved together almost like a duel, a graceful and elegant kata— "Aaagh! My eyes!" Dylan and I froze for an instant, and then sprang apart as if electrified. "That was Nudge's surprised squawk," I said. My voice was hoarse and I cleared my throat, my mind reeling over what I'd just been doing, what I'd just been feeling. My face was hot, my hands were trembling, and my lips were all tingly. "Nudge? Is something wrong?" Dylan said, instantly on the alert. Slowly Nudge's face edged around the green cloth curtain. "Um, sorry." She coughed, looking at me in fascination. "Nothing's wrong. I was just surprised. 'Cause I, uh, fell. Off a branch. Er... pretend I was never here." I stood up, mortified, but also angry. It had been hard enough to take the leap to kiss Dylan without having the entire world know about it. "Were you spying on me? On us?" I asked, narrowing my eyes. "I'm not the only one!" she protested sheepishly. "It's not what you think! Look, hold on." Nudge ducked outside for a moment and called out, "Gazzy! Ig! Get in here—the jig is up!" " 'The jig is up'?" I repeated. "Gazzy? Iggy?" Dylan came to stand next to me, his hand warm on my back. I suppressed the memory of what we had been doing a minute earlier, and crossed my arms over my chest. "Way to be a traitor, Nudge," I heard Gazzy say. Then both he and Iggy (who was still wearing his bow tie) entered the tree house behind Nudge. The three of them stood there, fidgeting and looking anywhere but at me and Dylan. I went for the classic interrogation technique: Hit the weakest link first. Nudge had never been good at lying to me. "Nudge," I said, pointing, "explain what's going on. I thought you guys were at home. _Obviously._ " She squirmed. " _Nudge_ ," I pressed. Leader Max was back in business. Romancey Max had been squashed for the time being. "Um," she said, moving her hands out from behind her back. She was holding some sort of box-type thing, silver and black.... A video camera. A freaking video camera. I gaped. I felt like my face had spontaneously burst into flames at the same time as my legs had melted into a puddle. "Were you _filming_ us?" Nudge nodded uncomfortably. I strode forward to plant myself right in front of the three conniving little thugs, nearly hissing in rage. "Why on _earth_ would you _film_ that?" "YouTube?" Iggy suggested totally unhelpfully, and I had to actually mentally count to ten to restrain myself. "I'm s'posed to record everything," Nudge mumbled. "What? Why? What are you _talking_ about?" She didn't answer. I rounded on Iggy and the Gasman. "And you! What were you two doing?" "Sitting in the trees outside," Gazzy replied in a small voice. Good to know I hadn't completely lost my touch. "Making sure." "Making. Sure. Of. What." "Um... that you were safe?" he squeaked. I made a half-shrieking, half-choking sound. "Since when can I not take care of myself? I was with Dylan, for Pete's sake! We were"—I faltered slightly but kept on truckin'—"eating dinner! What were you three _thinking_?" They all remained silent. "I can't _believe_ you," I spat. "Give me the video camera, Nudge." Nudge didn't move. "Nudge. Camera. _Now._ " "I can't!" she cried, putting it behind her back again. "It's my job! I have to!" That was when I really lost it. I snarled and, without thinking, shot out my foot in a sideways kick. Luckily, I didn't kick Dylan, Iggy, Gazzy, or Nudge. Unluckily, I kicked the table. Which had candles on it. It all happened before I could even blink. The tall tapers fell sideways, and hot wax ran across the table and onto the floor. Instantly the wax ignited, sending trails of flame through the tree house. The fire zipped along seams in the wood at lightning speed. Then it sparked at the spiky needles of the fir tree, which were poking in through one of the windows, and in the next instant the dried twigs and vines overhead caught. " _Crap_ ," I said in miserable awe, as suddenly we were caught in a living torch, the tree going up in flames all around us. Well, let's just assume I said "crap." "Everybody out!" Dylan shouted, and the five of us jumped through the doorway, one after another, unfurling our wings and flapping until we were all hovering in the cold mountain air above the forest. I looked at Dylan and felt utterly helpless as we both watched his beautiful creation go up in flames—the tree house he'd spent who knows how many hours to make, just for me. A perfect gift for a perfect evening, and I'd destroyed it. "I'm so sorry, Dylan," I whispered miserably, my voice breaking. "It was beautiful. I didn't mean to. It was the most beautiful thing I've ever seen." He gave a little smile at that, the rise and fall of his wings in perfect timing with mine. "No," he said softly. "You're the most beautiful thing I've ever seen." My heart surged and I started to smile, but just then the tree gave a terrific crack, as the fire hissed its way through the wood. And as I watched the thick plume of smoke billowing upward, I heard the echo of the Voice's words in my head, and I couldn't shake the icy feeling that the burning tree was some sort of horrible omen. # YOU'D THINK THAT would be enough excitement for one evening—the pinnacle of romance in my life, my unintended destruction of same—but no. I was awakened in the middle of the night by wailing alarms that made me bolt upright in my bed. Don't ask me how Iggy and the Gasman got the supplies to make the alarms, or when they rigged the entire house; I've been asking myself those same dang questions our whole lives together, and I still don't know the answers. I jumped out of bed, wide-eyed and ready to rumble. Out in the hall, Gazzy stumbled out of his bedroom. "Whuzzappenin'?" he mumbled. His blond hair was scruffy with bedhead. "We under attack?" He stifled a huge yawn. "I don't know. Maybe," I replied tightly. "Head count! Iggy? Nudge? Total? And Dylan?" _Note to self: Stop blushing at any mention of Dylan. Total giveaway._ "Yeah, yeah," Iggy said irritably, making his way to us with unerring accuracy. Nudge was behind him, rubbing sleep out of her eyes. Iggy pulled a small black remote from the pocket of his sweatpants and clicked a button. The alarms instantly went silent. Dylan arrived just then, looking like a freaking pajama model. We glanced at each other briefly before I chickened out and looked away. You know your life is sad when possibly being under attack is more appealing than facing the guy you made out with just a few hours earlier. Thankfully, that was when Total showed up to make the little midnight powwow complete, so I had a good distraction. "I was right in the middle of a dream about my lovely lady," Total growled, flopping down on the floor with his head on his paws. "This better be good. Is it the whitecoats? Erasers? Flyboys? Mr. Chu monster things? Land sharks? Mini-Godzillas?" I rolled my eyes. "Don't know. Iggy, where were the alarms set up? What were they rigged for?" "They're around the perimeter," Iggy said, shrugging. "Nothing small would set them off, like a squirrel. It's something big." Nudge dropped down and crawled to a window, where she rose a tiny bit and peered out, squinting. "It's too dark. I can't see anything." "Okay, everyone—get ready for whatever it is," I said grimly. "Let's wait thirty seconds, and then we'll hit the sky to do recon." "Fine," said Iggy. "I'll get some firearms." He headed down the hall. At the window, Nudge frowned and squinted harder, cupping her hands around her eyes to get a better view of the darkness outside. I dropped and crawled over to her. "See something?" "Yeah," she murmured. "Seven o'clock." She pointed carefully. "See that shadow? I think someone's out there, walking toward the house." "Who is it?" Gazzy asked, also dropping down. "Is it Jeb?" "No, it's—" Nudge's breath hitched in her throat. "That doesn't make sense. Oh, my gosh. _It couldn't be._ " "What?" I asked, already mentally preparing a defense, an attack, a plan to escape. I pressed my face against the cool glass of the window, but even with my raptor vision, I couldn't pinpoint what Nudge was seeing. "Couldn't be _what_? Or _who_?" Nudge drew back and faced us, looking utterly shocked. "It's _Fang_." # THE WIND HAD been knocked out of me as surely as if Nudge had socked me in the gut. "Fang?" I asked weakly, peering out the window again. "What do you mean, _Fang_? It can't be. He's walking." The strangled sound of my voice vibrated in my ears. "I saw his face when he passed through a beam of moonlight," answered Nudge. "It's either Fang or a perfect clone." A clone. Yeah, that was it. A clone like Ari, sent as a decoy by some whitecoat trying to sabotage us. _It can't be the real Fang_ , I told myself—Fang was _gone_. I let my breath out, relieved at the idea of fighting some potential threat rather than dealing with the possibilities of what Fang's return would mean. "Why is he limping?" Gazzy asked, squinting through the blinds. "He's _limping_?" I remained still for a split second longer, then rose and practically threw myself down the hallway with the flock on my heels. Gazzy flung open the front door and flicked on the porch light. I sucked in my breath, and my heart nearly exploded. The figure that blinked up at us from ten yards away was absolutely, unmistakably Fang. I gasped at the state he was in. He looked as if he could barely stand. His face was grayish and drawn, his shoulders hunched. His clothes were filthy. One arm hung uselessly by his side, and one wing was caked with dried blood. He looked like the living dead. " _Fang!_ " Nudge shrieked, and, ignoring all the rules I'd taught her about the million possibilities of danger, bounded off the porch in a blur of pink nightgown. She reached him in one leap, ignoring his obvious injuries and jumping into his arms. I stepped out onto the porch, scanning the area for threats, but there was obviously no point. It was the real Fang, all right. Nothing else could explain why I felt so tingly and weird all over. The hairs on the back of my neck prickled, and I realized Dylan was standing right behind me. His fingers reached out to hold me at my waist, and I tried to subtly move away. But subtlety has never been my strong suit, and Dylan sighed loudly. "Fang!" Iggy whooped. He and the Gasman followed Nudge off the porch, and the three guys exchanged those weird half-hug frat-boy things where they pat one another on the back. Even Total ran forward, putting his front paws against Fang's leg, wagging his tail. "Go on," Dylan told me. "You know you want to." His voice was bitter, so different from the gentle tone he'd used in the tree house. I could hear the implication in that tone and resented it, even as I felt myself moving from the doorway. Fang detached himself from Nudge and looked up. Our eyes met, and just like that, my legs hurtled me forward and suddenly I was hugging him tightly. Fang's uninjured arm went around my shoulders. "You came back," I whispered, hating the longing in my voice. "Did you think I wouldn't?" he asked with a half smile that was infuriating and devastating and revealed nothing and everything at the same time. A smile I had known all my life. Fang felt... familiar. Warm—as warm as Dylan had felt, just a few short hours earlier in the tree house. As I buried my face in Fang's dirty, bloodied hair, I felt Dylan's eyes boring into my back, and tried to swallow my guilt. # FOOD HAS ALWAYS been our number one solution for any awkward situation, so Iggy had the bright idea of whipping up a Welcome Back cake for Fang. This was undoubtedly to save us from the semi-uncomfortable silence that followed once I finally managed to peel myself from Fang's grimy, sweaty body. It may shock you to learn that Dylan decided to skip Fang's Welcome Back party. Said he had homework. But I could _feel_ his glowering energy radiating through the house while the rest of us were making fake conversation in the kitchen, pretending that the newest member of the flock didn't exist. I avoided trying to figure out the who, what, where, when, how, and _why_ of Fang's return by forcing Iggy to let _me_ bake the cake—maybe a first—and then serving it up. Almost without thinking, I scraped the icing off Fang's slice of cake before I put it in front of him (he'd never been a fan of icing) and plopped a quart of chocolate milk down for him to chug out of the carton, like he always used to do. Like he was still a little kid. He looked up at me with a dull smirk. "Been taking home ec?" My face turned red. Was he disgusted, like I didn't know him anymore? Or did he think it was sweet, like I'd _always_ known him, and always would? I'd been pacing around the kitchen, avoiding eye contact with him, for forty-five minutes. Now I finally planted myself across the table from him and stared intently at his beaten face. His hair had grown shaggy and long, and he'd aged several years in a matter of months. He'd become a man. At first the thought made me a little sad. And then it kind of scared me. But then it actually... _excited_ me, somehow. _And what have you become, Maximum Ride?_ I thought. Definitely _not_ a woman. And definitely not a savior. Barely a leader, anymore. Basically, I was nothing. "So... no offense, man, but why're you here?" Iggy asked, his mouth fully loaded with cake, spraying us all with chocolate crumbs. "Shouldn't you be with your gang?" Fang shoved a hunk of cake into his mouth. He glanced at Iggy and shrugged. Fang was giving us the silent treatment, just like old times. "I'm just looking for some answers, man," pressed Iggy. "The gang is done," Fang answered shortly, taking a swig of the chocolate milk. A shadow passed over his face, and I remembered what Ari had said about Maya. "So, how's Dylan doing?" Dylan, the elephant in the room (well, in the living room). The rest of the flock stared at me expectantly. Iggy whistled, and Gazzy made kissing noises. "Out!" I yelled at them. They scrambled away, taking the rest of the cake with them. "Dylan's fine," I told him, as nonchalantly as possible. "Doing well on his flying and fighting techniques, adjusting in the community, you know..." "Uh-huh." Fang stared at me, his dark eyes focusing on me intently, a tight little smile on his lips. "You look... different, Max. Lighter, or happier, or something." _Or something._ "Is that supposed to be a compliment?" I snorted dismissively, but inside, my stomach leaped a little. Was he trying to say I looked _good_? Maybe even... _pretty_? "I guess Dylan was just what the doctor ordered," Fang went on, unlocking his eyes from mine abruptly and stabbing his fork into his cake. "Yeah, right. The insane Dr. Gunther-Hagen, that is. I really trust the guy." I coughed. "Anyway, thanks, but... you actually look a little like roadkill, and I'm pretty freaking worried. What _happened_?" He gave me a penetrating stare that made me shiver—not unpleasantly—from my neck to my toes. "Basically, I came back from the dead, Max. And I'm ready to move on now. End of story." As if it wasn't bad enough that my evening with Dylan in the tree house had pretty much filled my every thought up until about an hour ago, now that Fang was back I was having flashbacks of kisses with _him_. The different memories kept swirling through my head like a swarm of tadpoles in a muddy pond, twisting into darker and darker masses of shapes until I couldn't tell which way was up. Or which intensely beautiful winged boy I was fantasizing about. # FANG AND DYLAN stood across from each other, both silent, arms crossed. Dylan shifted his weight, rubbed absently at his temple. It wasn't like he was facing the mostly-ex-but-it-was-confusing boyfriend of the girl he loved or anything. "You wanted to talk to me about something?" Dylan asked finally, cursing the anxiety he heard in his own voice and envying the expression on Fang's face—that cool blankness that gave nothing away. "Yeah," Fang replied quietly, yet with so much hostility in the single word that Dylan was taken by surprise. The time away from the flock had left Fang leaner, more angular. Add in the amount of still healing bruises and cuts on his face and the pissed-off scowl, and Fang looked downright menacing. Not that Dylan couldn't take him in a fight, if it came to that. He totally could. But still. An ideal situation, this wasn't. "So...?" Dylan said after another long minute of uncomfortable silence. "Talk." "I heard you've been sleeping in Max's room," Fang said, his dark eyes narrowing. _Ohhhh. So that's what this is about_ , Dylan thought. _Note to self: There is a reason Max calls Nudge "the Vortex of Friendly, Chattery, Bambi-Eyed Doom." She sees, hears, and_ talks about _all._ "Yeah, and?" Dylan said, feigning as much boredom as he could muster. He even picked at his fingernails. "And"—Fang leaned forward—"that's not necessary." Dylan put up his hands. "Look, you don't need to get all alpha on me, man." Regardless of his history with Fang, he wasn't about to actually fight him there, in the middle of the house. Especially not after all the headway he'd made with Max. "I just like to sleep there. There's nothing going on," Dylan said, and instantly wished he hadn't. "Oh, nothing's going on?" Fang barked out a laugh that made Dylan flush with humiliation. "No kidding, Casanova. You don't need to tell me that much—Max has standards, after all." Dylan opened his mouth to protest, to tell this jerk exactly what kind of standards Max had, to blurt out every detail about the scene in the tree house—Max's mouth, Max's skin, Max's soft feathers under his hands. But in that instant Dylan also saw what would follow—the hurt on Max's face, the accusation—and stopped short. "Look, maybe you think you're protecting her or something," Fang continued. "Who knows? But she's safe here, with all of us around her. She doesn't need you curled up at the foot of her bed like a lovesick dog." Dylan clamped his lips shut and tried to talk himself out of decking Fang. _Not worth it_ , he told himself. "So you can stop _protecting_ her," Fang said. "I'm back now. The flock is together again." He faltered for a split second, and Dylan knew exactly which person had just crossed his mind—a small blond person with white wings. "Max is fine." Now it was Dylan's turn to laugh. He looked at Fang coolly. "Excuse me? You're back now, so automatically everything's good again? Who do you think you're kidding? Things got worse the moment you came crawling back through that door." "What's that supposed to mean?" demanded Fang. "Worse for you, you mean, now that your little dream world is ending?" Dylan ignored that. "You're supposedly doing this all for Max, right?" he challenged. Fang nodded, leaning back against the doorjamb. "Well, sorry to break it to you, but by coming back, all you've done is put Max in more danger." Dylan sighed and sat on the edge of his bed, resting his elbows on his knees. Silence. Then: "What?" Dylan looked at Fang with a level gaze. "Haven't you noticed that, like, the entire world is hunting you?" he asked. Fang shifted. "They're after all of us. They always have been," Fang said quietly, but he was frowning. "You seriously don't know? You're the one they want, not _Max_ , not the rest of the flock!" Dylan was shouting now. "It's _you_ , Fang. It's your DNA they're after." "You're joking." "I'm not." " _My_ DNA?" Fang laughed, but it sounded tinny and hollow to Dylan's ears. "My DNA is, like, Generation _Zero_." "Well, fifty-fourth, actually," Dylan said. "But apparently they discovered something that has every whitecoat in the world after you." "Who did? I don't believe you," Fang spat, but the uncertainty in his eyes—the fear—betrayed him. "What kind of discovery could they possibly make about me that I wouldn't know?" Dylan let out a breath. "I... can't tell you." Fang pushed off the doorjamb and crossed the bedroom in two strides. He stood in front of Dylan, fists clenched, the veins in his neck straining. "You can't tell me? And why is that? Because you're making this up? Because a little bird told you? Because you're on their side?" "I'm on the side of Max surviving," Dylan shot back. "I didn't make this up. But I can't tell you the details unless—" "Unless what?" Fang's voice was tight. "Unless you swear to leave... and never come back." They stared at each other, black eyes locked onto blue, night and day. "I can't swear that," Fang said in a low voice. Dylan's jaw clenched. "Then I can't be held accountable for anything I do to you. You're putting her in danger. You're putting everyone in danger. Don't you even care?" "My Voice said to be with Max," answered Fang. "I'm never leaving her again." # "PAWS OFF, BUCKO," I barked, slapping the Gasman's hands away from my slice of pie. "You already ate an entire half of the pie. Your pie privileges have been revoked." "Paws off?" Total said, looking up from his plate. "I resent that. You're saying that all pie stealers have paws? Is that it?" "Chillax," I told Total. I'd forgotten he was sitting there. "It's just a turn of phrase." "Hmph," said Total. "And you," I said, turning back to Gazzy. "Step. Away. From. The. Pie." "Poop," Gazzy mumbled. "Dylan wouldn't give me any of his, either. Neither would Nudge. Or Iggy." "And what have we learned from this experience?" I asked, raising one eyebrow. Gazzy shuffled. "Um... everyone but me needs to work on their sharing skills?" "No," I said patiently. "We learned that if you eat half a pie, you get your pie privileges taken away. Capiche?" I am such a good not-mom. The Gasman started to say something else but was cut off by the sudden appearance of Fang, who had entered the living room like a freaking shadow. Just like old times. I glanced at Fang and was startled by how pale he was. His normally inexpressive face looked taut, and his lips were pressed into a thin white line. "What's wrong?" I said immediately, getting ready to do a head count. "Is everyone okay?" Fang hesitated. "Can you come with me?" I took one last bite of pie, then followed Fang down the hallway, past Nudge's room, Iggy's room, Gazzy's, mine, Dylan's, and Total's. (Yes, the dog got his own room.) Fang opened the door to the guest room and led me inside. His laptop was open and running on the bed, and I saw the page for his blog pulled up on the screen. "Wait, this is about your _blog_?" I exclaimed, one part relieved and two parts annoyed that he'd gotten me all worked up for nothing. "From your face, I thought we were gearing up for Armageddon!" He sat and motioned to the laptop. "Read the comment on top." Great. Probably another Fang fan-girl (Fang-irl?) gushing about how incredibly _guh-orrrrr-geous_ he was. I sighed and sat down next to him on the bed. What? My heart stopped. I couldn't breathe. Feeling completely numb—I refused to get my hopes up—I clicked on the image that came with the comment. Fang and I were both silent, waiting with bated breath, as the image loaded. It was a blurry, grainy photo, maybe taken on an old cell phone. The background was dark and murky, with a couple of blocky shadows that looked a bit like hospital equipment. I ignored that and focused on the foreground, which had better lighting. Better lighting that revealed a chunk of limp blond ringlets. A clump of dirty white feathers. A small, pale hand—the same hand I'd held a million times throughout the years. "Oh, my God," I breathed. "Oh, my God." Fang leaned toward the computer screen, gazing at the photo. "So you think it's really her?" he asked softly. I caught the faint undercurrents of insane, wild, un-Fanglike excitement. "Yeah," I squeaked, hardly believing I was saying it. "Yes," I said louder, looking into his eyes and seeing my own certainty reflected there. "Fang, I think that's Angel." _"What?"_ It wasn't Fang who'd spoken. The two of us turned to the doorway to see Nudge and Gazzy staring at us. Gazzy was holding the second pie, and Nudge was carrying two forks. Under different circumstances, I'd have whooped their conniving, thieving little behinds. But right now, all I could do was frantically process plans, ideas, possibilities, while I tried to contain the enormous hopeful smile that was threatening to take over my face. "Angel," said Fang. "Angel might be alive." The Gasman gasped and dropped the pie, which splattered all over the floor. None of us even flinched. _"What?"_ he said again. "Look," I choked out, and he and Nudge hurried over to the bed. I watched as they read this Mazin Nourahmed person's comment and studied the photo. "Trap?" Nudge asked immediately. _That's my girl._ "Maybe," I replied. Then I regretfully added: "Probably." "Do we care?" That was Gazzy. I knew how much he wanted to see his little sister again—under any circumstances. Fang and I glanced at each other, then answered at the same time: "No." The four of us sat there for a few more moments, just letting the news sink in. Then Gazzy hollered, "Iggy! Dylan! Fang's room! _Now!_ " " _Oh, my God!_ " Nudge yelled, bouncing on her heels in excitement. "Oh, my God, _Angel_!" "Did I hear 'Angel'?" Dylan asked, poking his head around the door. "What?" Iggy demanded, coming on Dylan's heels and skidding to a stop in the hallway. Gazzy read the blog comment aloud. As before, we were all quiet for a bit as Iggy and Dylan processed the information. And then—without any warning—we all leaped up, screaming and yelling and hugging until our voices and arms gave out. Nudge was sobbing; Gazzy kept chanting "My sister's alive! My sister's alive!" over and over; Iggy was laughing maniacally; Dylan stayed next to me, grinning, while I acted like my usual stoic, leaderly self (read: sobbing just as hard as Nudge). And in the middle of all of us, Fang was smiling with an abandon that I'd never seen him show before. For the first time in my life, I saw tears in Fang's eyes. He squeezed my hand, and I knew right then that regardless of traps, regardless of risks, everything was going to be all right. The flock was about to be complete again. Our baby was coming home. # THE VERY NEXT morning, all six of us—Gazzy, Nudge, Iggy, Fang, Dylan, and I—got up bright and early to leave on the first rescue mission in... how many months? Three? Four? Man, that might have been the longest period of time without a rescue since Jeb had whisked us away from the School. Impressive. We didn't bother telling the principal or teachers at Newton the small, insignificant fact that their precious bird kids were leaving on an impromptu trip to California, possibly never to return. After all, I've said it before and I'll say it again: We've spent our entire, unglamorous lives not being controlled by grown-ups. Why start now? "Okeydokey," I said to myself, stuffing another bag of beef jerky into a backpack. "Provisions, check. Clothes, check. Enough explosives to pose a legitimate threat to multiple small countries"—I eyed the duffel bags that Gazzy and Iggy had packed—"check. Destination"—I glanced at the printed-out sheet with a marked map, courtesy of Mazin Nourahmed the Helpful (and Possibly Evil?) Blog Commenter—"check." Six backpacks were laid out before me, for six bird kids. Usually I'd have to pack one for Total, too, but following my recommendation, he'd agreed to stay behind for this one. I'd arranged for him to stay with Akila. If this mission didn't go well, I didn't want his canine ladyfriend to end up a widow. "Ready?" Fang asked, sliding his arms through the straps of his backpack and giving me a warm, excited, anxious look—a look that betrayed way more emotion than I was used to seeing Fang display. "Yup. Let's bust this joint," I said. Nudge and Gazzy exchanged smiles—we all had the same feeling about this mission. _Just like old times._ Except, of course, this wasn't old times, or just any mission. It was Angel. And it was probably a trap. And even if we did somehow manage to find her, she might not be as okay as we were all desperately hoping she was. A lot can happen to a seven-year-old girl all alone at a School. I let out a long breath, my hands shaking as I fumbled with my bag's zipper. _Stay positive. She is_ alive. "It's okay," said a familiar voice beside me. Dylan. "We'll find her." I turned to face him. He looked serious and sincere. A lump suddenly formed in my throat, and I wanted to hug him. But Fang was right behind me, so I just nodded, knowing that Dylan understood, and praying hard that he was right. I hoisted my backpack into the proper position for flight, looking over my shoulder at Fang as I did so. We exchanged a brief look, I did a silent head count, and then he said, "Okay! Everybody ready?" " _Ready!_ " the flock shouted in unison. Then, with Fang leading the way, we all kicked off the ground and soared into the bright blue sky. _Please be okay, Angel. We're coming._ # IT WAS THE beginning of the end, but not the end that Angel expected. When she awoke, her lungs were screaming. She thought she saw a blurry flash, and then the image of a giant, belching fireball exploding behind her damaged eyes, and she cried out in terror. Another vision of the apocalypse. It had to be. There was nothing else that sent hot panic surging through her like that. The very essence of chaos, fire and brimstone. The violent sound of the earth being savagely reclaimed for nature. _It wasn't supposed to be like this_ , Angel thought. _When the end comes, I'm supposed to be with Max. With my flock. When we die, we will be together._ She had just sucked in a ragged, hot breath of stinking smoke when she realized she was still in the lab, clamped to the table, her limbs splayed out as if she were a butterfly on display. For a fleeting second the surrounding madness was drowned out by the deafeningly quiet memory of the whisper-sound of her feathers drifting to the lab floor, the endless flow of tears running down her face. After that, she'd passed out. Now she coughed weakly into her shoulder, but she couldn't seem to take in enough oxygen as she choked on the smoke that was forcing itself under the door and into the room where she lay, alone. Outside the door she heard muffled shouts and frantic footsteps. "It's time!" Angel was able to make out a woman's voice yelling. "It's really happening!" Somewhere an alarm was triggered, and the high, plaintive cry drowned out much of the chaos. The door of the lab burst open then, and someone was banging through cupboards while someone else rifled through papers and clanged metal objects around. They were ignoring Angel completely. "Help," she croaked. "Dr. Martinez?" "Take everything!" a voice Angel didn't recognize commanded to someone else. "The 99% Plan is in effect!" For the first time since the operation, Angel became dimly aware of being able to see movement, but she didn't have time to wonder about what was happening to her eyesight. She was wired to survive, and focused on trying to decipher who was in the room with her, and what they were doing. She fumbled wildly, trying to figure out how she might unlock her clamps, anything to free herself. But Angel could only make out blurred fractions of light, movements masked in smoke. "Help," she said again, coughing. But no one answered, and the footsteps were already fading away. And then, over the wail of the alarm, she couldn't hear any more voices. Beyond the wall of smoke, she couldn't breathe. _No!_ her brain shouted, rebelling against the inevitable. _No, I will not die like this, alone in smoky darkness. Not after the hell I have been through._ She began to fight then, really fight, even though every single muscle and bone in her body ached. "You can't leave me here!" Angel screeched with fury and despair to the empty walls around her. "I'm human, do you hear me? It _hurts_!" She sobbed as she thrashed against the clamps and felt the cords digging into her flesh. But no matter how hard she struggled, she was trapped. Smoke filled Angel's lungs and she hacked wildly, gasping. The sound of the alarm seemed to ricochet around her brain. _It's over_ , she thought with a sense of crushing defeat. Images of a giant, unstoppable wave gathering speed tormented her as she started to lose consciousness. _For once, the freaks were right: It's the end._ # Book Three # THE END # "HOW MUCH LONGER?" Gazzy asked breathlessly, catching a small updraft and banking left till he was flying next to me. He was grinning, but his face was lined with strain, and he looked more determined than I'd ever seen him. "Just a little bit more," I said. Less than five hours after leaving Oregon, we had begun to near the facility, which, according to our source, was in Death Valley—so close to the School that Jeb had taken us from that I almost had a memory-induced panic attack. "Days? Hours? Minutes?" Gazzy pressed. "In fifteen minutes we should be within a mile radius. Then we find the place, touch down, do some recon." "And then find Angel," he said fervently. "And spring her out of there. And do serious damage to whoever's had her." I winced. "Gaz..." "I know, I know," the Gasman said. "Could be a trap, she might not be there, I get it. But still. She could be alive, Max!" "Yeah, sweetie," I said, grinning. "She could be." I happened to look over and meet Dylan's eyes, which were as blue as the sky we were flying in. He hadn't said much this morning. Actually, he hadn't been saying all that much since Fang had returned. Mr. Discuss Everything was suddenly how Fang used to be. Meanwhile, Fang was now talking and emoting and expressing more than ever before. It was like the two of them had switched personalities. "Yo, up ahead!" Fang said suddenly. "I see something!" Nudge nodded excitedly. "It looks like a cluster of buildings!" We all—well, except Iggy—concentrated on the ground, letting our raptor vision focus in on what indeed appeared to be a cluster of buildings, some of which were made of boring gray and black stone, others of brick and gleaming one-way glass. The buildings were arranged in the shape of a _T_ , and to be honest, they looked like they could hold pretty much _anything_ institutional and uninteresting. A coat-hanger factory. Whatever. Except for the fact that they were in the middle of nowhere, with no cities, towns, or even houses in sight. And their location corresponded perfectly with the map we'd been given online. "This is it," Fang muttered. "Circle down." As we drifted back down to earth, Dylan moved closer to me. "Ready to beat up some whitecoats?" he said over the noise of the wind. "Always," I said. And I was glad he was with me. The six of us landed among a sea of small desert shrubs and immediately sank down to their height, keeping low. Then we got in a huddle to go over the plan for the umpteenth time. "Okay, so first Max and I scout the place," said Fang. "Look for possible cracks in the armor, etc. If we don't come back within a half hour—" "We fly to Badwater Basin," Iggy interrupted. "Then we wait for three days. Then, if you're still not back—" "We absolutely _do not_ barge in there and attempt to rescue you," Nudge deadpanned, repeating the words I'd drilled into all of them over and over again. "We act like sensible, self-preserving mutants and head back to Oregon." "Good," I said. "Anybody have a problem with the plan?" They all shook their heads no. Except Dylan. I knew he wanted to go with me, knew he was miffed, or peeved, or maybe even furious that I'd asked him to stay with the others. He'd bought my explanation—that they would need another good fighter with them, and that Dylan, out of all of us, was the least well known to the inner circle of crazed maniacs who seemed to chase us everywhere we went. He'd bought it. But he wasn't happy about it. I looked at Fang. "You ready?" He nodded, his eyes burning into mine, reading me, knowing my needs and my history and, it seemed, even my thoughts. We'd just bent our knees and were about to take off together when Iggy yelled, "Wait!" We all turned to him, instantly on the alert. "Fire," he warned. "I smell smoke." "Smoke?" I glanced around, not seeing or smelling anything other than the undisturbed buildings and the clear, sunny day. "From where?" Wordlessly, he pointed in the direction of the facility we were about to break into, and then the breeze changed and I smelled it, too: smoke. Lots of it. Little did we know then that the 99% Plan was in effect... just a little bit ahead of schedule. # THE SMOKE LED us right to the burning building, which was eerily hushed, with only the crackling sound of dying flames, and no signs of life anywhere at first glance. No panicked refugees, no firefighters—just a red-hot shell. When the fire had finally died down enough for us to safely explore the inside of the smoking facility, we stepped gingerly through the wreckage. Everything was horribly, deathly silent. My intestines sank down to my shoes. Marks from the fire had streaked the walls—or what remained of them—with gray and black. The stench of smoke permeated the dry air completely, scorched metal lay heaped where foundations used to be, and machinery that I recognized as mutant-testing equipment lay blackened and twisted in the rubble. I swallowed. _Time to be a leader, Max._ "Okay, everybody," I said, coughing against the thick air. "Search everything." There was a huge crash then, as part of the floor above us gave way and a large piece of lab equipment fell through near to where we stood. Gazzy giggled nervously, at home in the destruction despite the underlying worry on his face. "But _be careful_ ," I continued. "The roof could collapse at any second. Pay special attention to the part that wasn't destroyed—the eastern side. Angel could be in there." Maybe. Hopefully. God, if she was in the section of buildings we were standing in... _Well, I would still want to find her_ , I thought grimly. _Still want to take her body home._ Carefully we picked our way toward the far side—the eastern side—through a doorway that had been stripped of its actual door. I nearly threw up when I stepped over a partially melted plastic Kanine Kamper. Were we too late? Had we come this close only to miss saving Angel from a horrible death by—what, minutes? My heart was shriveling, but I kept picking my way through the demolished building, opening every door, trudging down passages that led to the smell of fire and combustibles and sickening chemicals. And fear. It hung in the air, thicker than smoke. I don't want to describe the sick things we saw, experiments on... some kind of life-form... that had clearly failed. Everything that might have been alive was now dead from smoke inhalation, including a couple of whitecoats. "How did the whole thing go up so quickly?" Dylan asked me. We were in the process of searching a lab that was filled with large machinery and operating tables. The sights made me physically ill. "I've been trying to work it out. It ate through the brick in, what? Ten minutes? And it was a scientific laboratory. Didn't they have some kind of fire-safety procedure?" "Maybe they didn't _want_ to stop it," Fang answered from across the room. He gestured at a utility closet, at a pile of overturned metal jugs inside. They reeked of gas fumes. I heard Nudge gasp from another doorway and ran to her side, my adrenaline rushing. "Max, why are they in a circle like that?" she whispered, her bottom lip quivering. A strangled moan escaped my lips when I saw what she had found: the still smoking bodies in the lab, dozens of them, slumped against one another, arranged in a circle, just like Nudge had said. Like they'd been sitting down to tea, or a game of telephone. Like they'd died en masse. My throat was dry and my mind was whirring. We'd tried to get inside when we'd first seen the smoke, but the doors had all been bolted. What had seemed like an abandoned building had been packed with people. What had seemed like an accident reeked of purposeful destruction. We'd been there for the fire. We'd watched the whole thing happen. No one had run outside. I shivered, understanding the horrific implications. They'd _wanted_ to die like this. This place was making my soul hurt. "Max." It was Dylan who'd spoken. He was down the hall. "Yeah?" I forced the word out of my mouth, peeled my gaze away from the awful sight of the bodies before me. "Did you find something?" "I... I think so." His tone was hollow. I swallowed. I couldn't bear to find definitive evidence that we'd lost Angel. Not again. Not after we'd had so much hope. Reluctantly, I came up beside Dylan. My eyes followed his gaze to the slick metal operating table in front of him. There were four clamps on it, in the corners, for restraining limbs. Caught in one of the clamps were two soft, downy, white feathers. "No," I choked out, my knees buckling. Faintly, I heard the flock gathering behind me: Nudge's intake of breath, Gazzy's moan of pain, Iggy's hiss, and Fang's teeth gnashing together. But I couldn't stop staring, horrified, at the feathers in the clamp. You'd think it couldn't get any worse, after that. But it did, of course. Because right then, we heard the sweet, sociopathic voice that would give us all nightmares for the rest of our lives. "May I help you?" # IT TOOK ME about zero point three seconds to recognize the man standing before us: Mark. The once manic leader of the Doomsday Group. Someone I hadn't seen since Paris, since Angel disappeared. I was pretty sure he was responsible for that whole bloody nightmare. "Hello, children," Mark said languidly. His entire body was covered with horrible burns, and his clothes were scorched and torn to the point of falling apart. " _You_ ," Gazzy spat. His voice was shaking. "You're the one from the tunnels! _You hurt me and my sister!_ " We were all glaring daggers at Mark, but despite his burns and the excruciating pain he must've been in, his expression was one of dreamy bliss, and that was what truly scared me, what made the hair on my arms stand up and my blood run cold. Angry people I can deal with; I can handle rage with a quick fight. Insane people are much more terrifying. They're totally unpredictable. "Just say the word," Fang said to me under his breath. My hands clenched into fists as I prepared to kill the man who had taken Angel from us, to tear him limb from limb. Dylan readied himself beside me. "I'm not a threat, children," Mark said, still wearing that crazed, happy expression of his. He took a step forward and the six of us stepped back instinctively. "This was all for you. At last, it's begun." Mark paused, looking bemusedly around at the destruction, at the burned wreckage, as if not really understanding what had happened. "It's begun," he repeated. Another beatific smile. "My work here is done. I've saved the planet. Saved it, protected it for the select few. And you, my friends, will benefit." "What are you _talking_ about?" I demanded. If there's anything worse than a psychopath, it's one who thinks he's doing his evil deeds for a good reason. "How has all this"—I waved my arm to encompass our surroundings—"saved the planet? How was what you did in Paris _protecting the planet_?" I was shrieking in his face, rage dripping from my every word. His eyes were peaceful. "You'll see," he assured me. He glanced down at his burned arms, the flesh flayed open and raw. He didn't seem to be feeling anything. He looked up, his eyes coming to rest on one shattered window. Its wire-embedded glass had been twisted outward by some explosive force. Mark examined it: a novelty. Then he turned back to us. "You'll see," he repeated. "The contagion has been unleashed. Now all will come to pass. And you'll thank me for it." "Not likely," I said, advancing toward him. "The only contagion I'm aware of is you and your insane cult. Now, if you don't tell us where you took—" "Take care of the earth, my children," Mark interrupted, still smiling. And then he threw himself out the window. We have lightning-fast reflexes, but none of us got to him in time—it had happened so fast, with no warning. Horrified, we ran to the window and looked out. We weren't up very high, but he'd landed on a pile of broken concrete. Shafts of rusty rebar stuck up at different angles, one of them directly through Mark's throat. He still had that pleasant smile on his face, but his eyes stared blankly into nothing. "Unhhh," Nudge groaned, and then vomited on the floor at my feet. As I rubbed her back, I felt warm hands on my shoulders, and for a second I couldn't tell if it was Dylan or Fang. Then Fang moved into my line of sight, scowling. It was Dylan who stood behind me. I stared down at Mark's body and felt bile rising in my own throat. "Well, that's... that," I said shakily, moving away from the window. "So, we continue searching for Angel?" Dylan asked quietly. I nodded. "We _always_ continue searching for Angel." # WE SEARCHED THE whole place, and my heart sank lower with every empty room. Not that the rooms were actually empty. They were full of the stuff of nightmares: bloodstained operating tables, cabinets full of horrifying tools, jars of specimens that made my stomach turn. Only Iggy would avoid having these appalling images seared into his brain. The rest of us would carry them forever, like scars. Nudge reached out and took my hand, held it tightly as we looked at another huge jar holding a preserved experiment _. Oh, God._ "Evil. So evil," I muttered, feeling heartsick. This had to be where Angel had been kept captive, ever since Paris. I didn't say anything to the others, but a black fog was starting to shroud my aching heart. How could she have survived this? And if she had survived it, how would she ever recover? Not just physically, but emotionally. We'd already been through more than anyone should have to go through. What if she'd finally been pushed over the edge? What if she could never come back? After yet another horrifying sight made me gag, I leaned against the wall and rubbed my eyes, which stung from the lingering smoke and chemical fumes. My throat was scratchy and dry, and it ached from the effort of suppressing my cries of shock and horror. "She's not here," Gazzy said tonelessly, sitting down on a broken beam. "Or if she's here, she's part of the ashes." His voice broke. "Let's start over again, from the first building," Dylan said, squeezing Gazzy's shoulder. He sounded tired but determined. "No," said Fang. "We should take to the sky, do recon, and see if they left tracks—whoever escaped, I mean. She could be with them." "You think some people escaped?" Nudge's face was drawn. Fang nodded. "Someone always escapes." This had all been for nothing. My baby was still gone. _Don't give up, Max._ My Voice was very, very faint. It had never before sounded like it was talking to me from as far away as the moon; I almost thought I'd imagined it. Then I saw something through the dust on the floor. I pushed aside some charred beams and uncovered a metal trapdoor, maybe two feet by two feet and padlocked from the outside. "Nudge?" I whispered. Closing her eyes, she swept her sensitive fingers over the lock several times. I didn't know how or why she could affect metal with her touch, but I was glad she could. Her fingers trembled with both effort and emotion, and we all clung to the hope that there might be one more place we hadn't looked. The lock sprang open in her hand, and we yanked the doors open. A narrow metal staircase led down into darkness. I went down first, my senses screaming with alertness. It took my eyes a couple of seconds to adjust to the lack of light, but at my first quick scan, we seemed to be in a small room. An _empty_ room. I felt a terrible pain in my chest as my heart constricted with grief. There was nowhere else to look. Angel was either dead or being rushed to another secret facility, and I knew she wouldn't be able to withstand this torture until we could find her again. The tears I had been holding back during our search suddenly started streaming down my face. I couldn't breathe. I wanted to fly out of there and never come back. Let the world take care of itself from now on. I was done. As I turned to rush out, my eyes fell on a small back room, behind the stairs we had just come down. I reached the doorway in two strides. A feathery, dirty heap was strapped to a table in one cold corner. "Angel?" I whispered, not letting myself believe it could be her. We knew there were other winged kids out there. It would be too good to be true.... I took a few more steps toward the figure, and then collapsed to the floor beside it. I knew that face, that hair, no matter how wrecked they had become. Trust me, it's impossible to describe the rush that happens when your whole soul shifts, in an instant, from despair and loss to realizing that maybe it was all just a horrible lie, a nightmare—that hope is truly _alive_. "Angel!" I cried, sobbing and stroking matted curls away from her grimy face, while Fang immediately started dismantling the clamps. " _Angel!_ We're right here. We came to get you. Angel—wake up!" I gently cradled her head, which lolled back. Was it really her? Or just... her body? I got no response. As soon as Fang was finished with the clamps I gathered her up, and it felt like I was holding Styrofoam. There was hardly anything there, as if she hadn't eaten since Paris. Numerous puncture wounds dotted both arms. How many times could my baby be torn from me and survive it? The massive tsunami wave of joy I'd felt moments earlier was already rushing back out to sea. "Angel, please," I begged, cuddling her close. "Please be okay. We're all here now. Max, Fang, Iggy, Nudge, Gazzy, Dylan... we're all right here. You're safe. We're all together. Please, sweetie, please wake up." My words were coming in gasps. Then—had I imagined it? Had her too-thin, too-light body shifted? She made a tiny sound. Her eyelids fluttered. "She's alive!" Gazzy's voice was hushed but thrilled. A fierce joy swelled inside me. She was _alive_! She really was! And she was going to stay that way, at least while I was on this planet. No matter what, I would never, ever let her out of my sight. We would never be separated again. # MY BRAIN WAS on a drunken loop of joy, disbelief, shock, ecstasy. _This is really my Angel, my own Angel...._ The others crowded around and tried to touch and embrace her, so they, too, could truly believe what I was still trying to absorb. But I wouldn't let go of her. "We need to get her out of here," Dylan instructed, gently pushing his way in close to help me lift her body. I hardly registered Fang's irritated look. Nothing in the world mattered to me at that moment except keeping my little girl safe with me. I stood up and carried Angel upstairs, into the light. Someone had padlocked her in that underground room—there would have been no way for her to get out. Someone had left her there to die. "Max?" Her voice was barely a breath. "Yes, sweetie," I said, trying not to leak tears on her. "I'm here. We're going to get you somewhere safe, get you all patched up, good as new." Her small head shook. "I'll never be as good as new," she whispered weakly. "They messed up my eyes. They clipped my wings." _"What?"_ "I'll never fly again," she whimpered sadly. Tears slowly streaked the dirt on her face. Quickly I traced down her primary feathers to her flight feathers, fanning them gently in my hand. They looked fine. "No, your feathers are okay," I reassured her, understanding the kind of crazy confusion the whitecoats' drugs could cause. "You'll be fine—I promise. You'll be flying in no time. We'll take care of you." Her eyes opened slightly and she looked into the sky, past my head. "They experimented on my eyes, Max." A cold fist grabbed my heart and yanked. "What?" "Like Iggy," she confirmed, and I was seized with fresh horror. "Jeb was here—he said it was for my own good." Her voice was weak—it was hard to make out what she was saying. "Tell me, Angel," I said urgently, pulling Gazzy to my side. "Who is standing right next to me? _Tell me._ Don't tell me you're blind." "I—I—" She blinked. And blinked again. We were all holding our breath. "My brother... Gazzy..." She breathed. "Is that you?" Gazzy threw his arms around her and sobbed. "Everything is kind of a blur," Angel whispered as Gazzy pulled away. "Shh, sweetie," I said. "Don't try to talk. You're waking up from a drug-induced nightmare. We'll make sure you're okay. We're going to take you home now." Again she shook her head, opened her eyes. She peered up at me anxiously, her eyes not quite focusing. "Max, your mom was there. I saw her. Dr. Martinez. She's... she's one of them." I looked up to see the flock recoiling in shock. "No, sweetie," I said, my mind reeling. "You've been hallucinating. Your feathers are fine, and my mom isn't one of the baddies. It was all just weird hallucinations." Angel shook her head. "No. Your mom was there. She helped them. Dr. Martinez is on their side." # I TRIED TO keep my emotions under control as we flew home, but sometimes I could barely see through the tears. Angel weighed so little that it was no problem for Dylan, Iggy, Fang, and me to take turns carrying her on the flight. We also picked up Total on the return trip. I knew he'd want to see Angel right away, and I was right—I'd never heard him bark so wildly with joy. As soon as Angel was settled—cleaned up and in fresh clothes, but still pale and worn out—I left her sleeping peacefully, with Nudge and Gazzy in charge and Total curled up at her side. I needed to be alone in the woods for a minute to get my emotions under control—otherwise I'd be a crying mess when Angel was finally ready to talk about what had happened. So it wasn't necessarily the best timing when Fang crept up quietly behind me, just like he always used to, and scared the stuffing out of me. "We need to talk. About you. And me." I could feel the heat rising to my cheeks. "There _is_ no you and me, per your instructions," I said, my jaw clenching. "I don't know about that," he said. "Oh, please. You _left_ ," I said accusingly. " _Twice_ , actually. You threw any _us_ we had in my face! Then you decided to get all hot and heavy with Maya." That last part came out before I could stop it, and I cringed, remembering what Ari had said. "Maya's dead," Fang said tensely, confirming what I already knew. I winced at the grief in his voice. "And this isn't about her. It's about the connection you and I have—will _always_ have, no matter what." I opened my mouth to retort, but nothing came out, so Fang forged right on, breaking my heart with his honesty. "I heard a Voice, Max," he said, gripping my arm, pulling me closer, "and it told me I needed to come home to you. Even though I had to practically _walk_ the whole way. Even though I was close to dying. I came back. To you. And I wanted to tell you—maybe I never told you very clearly before..." My heart was racing so fast I thought I was having a heart attack. "I wanted to tell you that I—" "Stop!" I cried, putting my hands over my ears. "Just _don't_ , okay?" But Fang looked determined, and there was only one thing to do when he looked like that. I took off. If I pour on the speed, I can hit almost three hundred miles per hour while flying—faster than any recombinant life-form I've ever heard about. Faster than anyone. Except Fang. I was probably already a couple of miles away, still sniveling and cursing, when I felt a hand grab my sneaker. He stayed with me, matching me stroke for stroke without releasing his death grip on my ankle. Finally it was too hard to stay balanced, so I put on the brakes. I banked steeply and whirled around to face him. "Fang, I can't hear this right now!" I shouted, tears streaming down my face. "My life is hard and confusing enough without you making it harder! Everything's just really, you know, _complicated_ , and..." I trailed off, thinking of the complicated things in my life. The other complicated _someone_. "I'm not trying to make it harder or more confusing," Fang said quietly, smiling that lopsided smile of his. Warm emotion showed in his black eyes, and for a minute I actually had to concentrate on staying airborne. "I'm trying to tell you what you already know. I just... _need_ you. We need each other." "But _I_ just can't do _this_." I flailed my arms around, indicating whatever _this_ was—encompassing everything. "With you. Not now, not _today_ , not after everything we've been through with Angel, so..." I swallowed, trying to ignore my stupid heart. "Just don't say any more," I whispered. "Please." But if I could hear the catch in my voice, I knew Fang had picked up on it, too. He had moved closer. We were nose to nose now, our wings almost overlapping as each stroke took us up ten feet, then down again. We'd been flying together our whole lives, and keeping in perfect rhythm was second nature to us. My arms were crossed over my chest, my elbows almost brushing against him, and Fang reached out and held my arms, below my shoulders. He let his thumbs brush against my skin, slowly. I shivered. Fang's touch was so familiar. How many times had he done this? Old times and new all jumbled together. Emotions and memories became indecipherable. The only thing I knew was that we'd grown and changed. It was almost like he was a new Fang. I felt almost like a new Max. Could we still... fit together? "Max." He said my name like it was a life raft. Like it was a religion. His warm fingers stroked up and down my arms. "What?" I whispered. Or had I even said it aloud? I didn't know what to do, so I stared into his eyes for the answer. And I let them rest there. I didn't want to be the first to look away. I reached out and put my hands on his shoulders, felt his strong, light bones under his skin. I remembered what he had carved into a cactus once. > MAX + FANG—4EVER. # TEARS POURED DOWN Dylan's face. He dashed them away angrily with the back of his hand, flapping his wings powerfully and putting as much distance between himself and _them_ as he could. He'd been in a tree a good half mile away from them—not _spying_ , just... _seeing_. Seeing his past going up in flames, his future crumbling into dust. He wasn't about to stick around to watch Max and Fang finally have their little private reunion party. He'd thought what he and Max had was starting to grow into something... real. She'd let him sleep in her room. And that night in the tree house... He remembered the feel of Max's skin under his fingertips, her wildly tangled hair brushing against his cheek, the look she gave him just before their lips met.... He could live and die inside that single look. Dylan shook his head, flapped his wings harder. Faster. He took the next turn too tightly and lost control, dropping hundreds of feet before he could level himself. He saw the forest ahead. Tall trees, growing thickly together. He narrowed his eyes and dove down. He wove crazily in and out of the trees, at top speed. He scared birds, startled a group of deer, and still he went as fast as possible, so fast that the wind would dry his tears. Again and again he flipped sideways to fit through narrow openings. His sneakers smacked against tree trunks. Bark raked the skin on his hands and face raw. Branches caught at his feathers, and he felt some get yanked out, but he didn't even wince. It felt good, the pain. He wanted more. All this time he'd tried to be good. He'd followed the rules—or at least the rules _Max_ had set. He had learned to fly and to fight, had followed her lead. He had given her space, and then pressed a little closer when she seemed to want it. He'd done everything he was supposed to, _when_ he was supposed to. He had thought if he could just be _perfect_ , Max would love him. But she loved Fang instead. _Fang_ , who seemed to break every rule in the book. Dylan set his jaw. _Fine_ , he thought. _She wants a bad boy like Fang, I can do that._ _Bam!_ He brought his feet down, hard, on the roof of a car that was driving toward town, making a huge dent. _Bam! Bam! Bam!_ Three more cars suffered the same fate. Dylan felt a rush of thrill and fear: This was the best he'd felt since Fang had come back. On the next car, Dylan dropped down even lower. _Snap!_ One quick kick took the side mirror right off. _Crash!_ A rear windshield was smashed to smithereens. It was an incredible feeling of power, a power he'd never felt before. He rose a bit and banked sideways dramatically, hearing car horns honking, people shouting. He wheeled around the store on the corner, then swooped down and grabbed the store's banner with one hand, ripping it from where it had hung across the sidewalk. It landed on a car driving underneath it, causing the driver to lose control and crash into a telephone pole. But Dylan was already halfway down the street, ripping street signs from their posts and hurling them like Frisbees. People were yelling at him now. A baseball whistled past his head. He could hear sirens behind him. Over and over, he dropped down suddenly, kicked over a mailbox, a trash can, a trellis. But the pain in his chest was returning. He reached up and ripped the electrical wires strung along the street from their poles. Sparks shot everywhere as the live wires fell to the ground, igniting the bulging trash bags that lined the curb. At last Dylan realized he was weeping again. He could hardly see. What was happening to him? Nothing was making sense—least of all his behavior. He rose gracefully, powerfully into the air, leaving behind a roiling fire that was beginning to streak through a destroyed neighborhood. _This isn't the answer, Dylan_ , said his Voice. _You know what your job is_. _You know what you have to do._ Dylan shook his head, as if he could shake the Voice loose, make it go away forever. A thought flitted through his brain like the light fingers of a practiced thief. He turned around slowly and tasted bile in his throat. No. He _couldn't_. Could he? It was the answer to so many of his problems. What he _couldn't_ do was what the science teacher had demanded on that awful day in the lab at school—he couldn't turn Fang over for the whitecoats to experiment on, no matter how much he hated him at that moment. He would never condemn anyone to such a fate. But if he didn't turn Fang in, someone else would. And if what Dr. Williams had said was true, they would hurt—possibly kill—Max as a result. He couldn't let that happen. Dylan's mind spun. Maybe this awful thought... maybe this was the _right_ thing to do in the end. It would spare Fang from a horrible life of tests and scalpels and torture. It would save Max's life. She would be grateful; maybe she'd even come to love him for it... someday. Dylan swallowed. The Voice was right. He _did_ know what he had to do. He had known all along. He had to kill Fang. # "OH, MY GOD, it's Dylan." My head swiveled sharply at Gazzy's words and I practically ran to where he sat on the couch. He was pointing at the TV screen. "What 'oh, my God'?" I demanded. "What 'Dylan'?" "He's... he's... gone wacko," said Gazzy. I turned my attention to the news broadcast, which was showing a grainy, shaky cell phone video... of a bird kid rampaging through town. My mouth dropped open as I saw _Dylan_ —and he was totally, prosecutably recognizable as Dylan—smashing windows, ripping down signs, kicking cars, knocking over mailboxes. "It doesn't seem like him at all," said Gazzy. "He's always so laid back. Maybe it's, like, a clone or something?" he offered. "No," I murmured, anxiously watching the screen. "No, I think it's really him." But why was he on this insane destructive streak? What had happened since I last saw him? I tried to think when that was.... He'd been with me all day, right up until— _oh_. Suddenly it all became horribly clear, and my stomach clenched. Dylan had been near the door when I'd gone outside to be alone. He must have seen Fang follow me, which meant he'd seen Fang and me fly off, out of earshot of the house. What else had he seen? "This is all my fault," I muttered, grabbing my jacket. "I'm going to find him." Before Gazzy could say anything, I'd leaped off our balcony and was streaking toward town. # I WAS AT the edge of town before I realized that I had no idea what I was going to say to Dylan when I found him. Dylan had had my back when I didn't really have anyone else, and he was the last person in the world I wanted to hurt. He was... Well, he was a great guy, and I knew exactly how much he cared about me. He'd worn his heart on his wing, and he deserved honesty from me in return. But what could I say to him? What could I offer him? What could I promise? How could I know what to say when I hardly even knew what to _feel_ these days? _God help me._ I kept myself high enough in the sky so that people wouldn't necessarily spot me right away. But I could still see everything, and I almost skidded to a halt when I saw firsthand the damage Dylan had done. The town was in chaos. It looked like a tornado had streaked through, wrecking everything in its path. There were dented cars stopped on Main Street, store owners talking angrily to police, people sweeping up glass and reattaching signs. It was like Dylan had woken up today and decided to play Godzilla. I let out a slow breath, understanding the implication: The measure of damage that Dylan had caused was probably about equal to the amount of pain he might be in right now. Because of me. My heart in my throat, I kept scanning the streets, but what I didn't see was Dylan. I went high, way high, to give myself a broader view, but saw not a feather. I scanned treetops, the roofs of buildings, other places suitable for hiding out and seething, but he had disappeared. And when he came back— _if_ he came back—how would things be then? Would he still be the sweet, vulnerable Dylan I had begrudgingly come to rely on, to even _like_? To _more than_ like. I couldn't admit to myself just what that feeling was, but it was something that had started to work its way deep inside me. I'd been trying for so long to ignore his adoring looks, to distance myself and push him away. So if I'd finally succeeded, why did it hurt so much? # _HE'S HOME._ That was my first thought when I was rudely jolted out of a restless sleep that night. For the second time in just a couple of weeks, Iggy's alarm system was sending wails and automated warning messages through the house in the middle of the night. _Be angry_ , I told myself as I bolted from my bed. _He shouldn't have taken off like that, shouldn't have caused all that damage. You're furious._ But I couldn't stop the feelings of relief and elation that swept through me as I headed for the door. "What is it? Who's attacking us?" Gazzy yelled from his room. "Should I bring the bombs?" "Max?" Angel whimpered, stumbling out of my way sleepily as I rounded the corner and ran down the hall. "It's okay, Angel. Everything's fine. Don't worry, guys," I yelled over my shoulder as I started to unbolt the locks. "Iggy! Cut the alarm! It's just Dyl—" I breathlessly threw open the door, and a sea of glowing red eyes peered at me out of the frigid darkness. Behind me, Nudge sucked in a breath—there were _a lot_ of eyes, and they were feral, bloodthirsty: Erasers. I swallowed, my words dying on my lips. " _Of course_ ," I muttered, trying not to show how overwhelmed I was by the sheer numbers, how unprepared I'd just been caught. I had _opened the door_ to these mongrels, without any weapon or plan. I had practically invited them in. I cleared my throat and stepped right out onto the porch. I could hear breathing and shuffling in the darkness, animal sounds that sent chills down my spine. You'd think I would be used to it by now. "So," I said loudly, "is there a specific reason you flea-bitten wolves are attacking? Or is it just my lucky day?" "Just your lucky day, sis." I knew that voice: bitter, deep, like a bunch of rocks being rattled in a can. _Ari._ The crowd of Erasers parted so he could walk through, and he stopped just ten feet from the bottom of the stairs. My stomach turned somersaults—somehow he looked even bigger and wolfier. Maybe he had been "enhanced" some more. "This is the end, Max," Ari said, stepping into the beam of the porch light and showing his yellow fangs. "I promise." "I stopped believing your promises a long time ago," I said. I felt just a tiny bit sad, remembering the cute kid he had once been. My half brother. The other Erasers were moving forward now, ever so slowly. Every single one of them was staring fixedly in the same direction. At the same person. And it wasn't me. "We're here for _you_ , Fang," Ari said, looking into the hallway behind me and grinning toothily as he cracked his meaty, hairy knuckles. "We're here to kill you, and trust me—this is one fight you bird kids can't win." Fang came out to stand beside me, his fists clenched, his face tight with anger. "I wouldn't bet on that." "Your funeral," Ari said, shrugging. He held up one hairy fist, ready to give the signal to his army. I tensed, settling my weight as I prepared to leap off the porch. I didn't know if these Erasers could fly, but regardless, I was not going to start this fight on my feet. I was ready. I'd been ready for this for a long time. And my plan was to ignore any and all pain until every Eraser was gone. But you know, things can always, always, take a turn for the worse. "Just say the word, _Dad_ ," Ari called out. So there you go. # OUT OF THE shadows stepped the one, the only, the despicable Jeb. And get this—he was actually wearing a white lab coat. And a small frown. "Wait, Ari," Jeb said firmly. "I need to explain things first." For a moment, I thought Ari was going to ignore the command and just attack us anyway—that was what he would have done just a few months earlier. He hated and resented Jeb as much as he did us. But after a moment's hesitation, he nodded and slowly lowered his fist, though he never took his rabid eyes from Fang's face. Jeb moved closer to the porch. I kept my face expressionless, staying in battle mode. My muscles were coiled, my heart was pumping, and every sense was hyperalert. I knew that my flock—even Angel, who was still so fragile—was ready, just like I'd trained 'em to be. Just like Jeb had trained me. "Max, Fang," Jeb said, sounding urgent, "I need you to understand." Behind him, Ari shifted, and all of the red Eraser eyes in the darkness shifted along with him. They were muttering now, and I heard twigs snapping as they moved around impatiently. I had no idea how long Ari or Jeb could keep them in check. "Save it," I said, crossing my arms over my chest. "We don't need to listen to any more of your lies." "No, but you _do_ need to know the truth, Max. The truth about why Fang must die." I laughed coldly. "That actually sounds like something we absolutely don't need to hear," I replied. "It sounds totally irrelevant, actually. Because Fang isn't going to die. You may have created us, Jeb, but you do _not_ get to decide when we die. The only expiration date that's approaching is yours, the second you try to get any closer to him." I saw the rest of the flock out of the corner of my eye, moving to stand next to me on the porch in support. Iggy stepped protectively in front of Fang and crossed his arms. "Max, you don't understand." Jeb looked up at me. "I don't _want_ Fang to die, any more than you do. But he _needs_ to. If the earth is going to survive, _Fang must die_." Fang stepped forward from the shadows and let out a long breath. "Go on," he said, watching Jeb steadily. I reached out and took his hand, holding it tight. "When you were in Dr. Gunther-Hagen's lab," began Jeb, "he took samples of your tissue, did all sorts of tests on you, on your skin and muscles and organs. And eventually he made an amazing discovery. Fang, your DNA is _indestructible_. Infinitely regenerative." "We all heal quickly," I ground out. "No, Max, sweetie." Jeb shook his head slowly, ignoring the look on my face at the word "sweetie." "Fang is different. _His_ DNA holds science's key to _immortality_." Okay, I did not see _that_ coming. # "I'M SO SORRY," Jeb said sincerely. "But now you understand why Fang must be eliminated." I scowled at him. "No, actually, I can't say I do." "If my DNA is so special, wouldn't that make me useful to keep alive?" asked Fang dryly. "For _science_?" "Yes," Jeb agreed. "And that's exactly why Hans wants you alive—for that very reason. He intends to lock you up in his lab and put you into a permanent vegetative state. You understand what that means, don't you? You would be just a body, unable to move, think, eat, talk. A body that Hans intends to perform live experiments on _forever_." I stared at Jeb in shock. Imagining Fang like that made me want to throw up. Jeb paused, looking positively misty-eyed. "I myself would end your life right now, to save you from that endless nightmare. I created you, Fang. I could never let you endure that." "He wouldn't have to endure anything," I said briskly, my mind racing. "We'd protect him. And if you loved us, you would, too. Take him somewhere safe. Somewhere Dr. Hans would never find him. We're good at running from idiots—as you well know, Jeb." Jeb coughed and looked at the ground. When he looked back at me, his eyes were pleading, but apologetic. "It's not just Dr. Hans, Max. News travels fast in the world of science. Believe me, if I know of the discovery, many others do as well. And for something of this magnitude... They would come looking, more and more. You couldn't protect Fang forever"—his lips curled into a sad smile—"and I'm afraid that's how long you'd need to. What happens when you die, Maximum? Have you considered that? Who will protect Fang then?" I clenched my fists but didn't answer. My mouth was dry, and I felt empty and hollow. "I can take care of myself," Fang muttered. "Especially if I'm immortal." Jeb shook his head sadly. "I'm afraid you're not immortal, Fang. We've determined that your DNA holds the secret to the pursuit of immortality. There's a difference. You're a critical link in the next great step in human evolution." He cleared his throat. "But this is not just about you, kiddo. This is bigger. It's about saving the whole world." Jeb looked at me. "It's what you've been preparing for all this time, Max." "Wait— _what?_ " Fang and I said at the same time. My mind reeled as I tried to get a handle on this scenario. And Ari and the Erasers were having a harder time than I was—they were clearly bored out of their pea-sized minds and were visibly salivating, shivering with anticipation as they waited anxiously to tear into Fang. Behind me, Nudge, Iggy, Gazzy, and Angel shifted their feet and unfurled their wings in case things got ugly in a hurry. It looked like they might. Jeb went on, "Immortality might sound like a good thing, but as soon as it can be genetically engineered, we'll have a disaster on our hands. If people live forever, their numbers will increase exponentially—like a cancer metastasizing across the earth," Jeb said earnestly. "This is why I truly believe in the 99% Plan. The planet only has a chance if we take _people_ out of the equation." "Oh, come _on_ ," I scoffed, but Jeb was looking at Ari, who was moving toward his army of Erasers. "It's okay," Fang said to me, trying to look reassuring. "They can't hurt me. I already cheated death once. I was pretty much resurrected after I was thrown from the cliff." "Lose your God complex, my friend," Ari sneered. "When we get through with you, there won't be anything left to resurrect." "I created you, Fang. I created a... well, a monster," Jeb said. "And now it's my duty to destroy you, before Dr. Hans and those like him can torture you forever. Before your DNA can destroy our planet. I'm so sorry, Fang!" He nodded at Ari: _Take him out._ # _BOOM!_ I whipped around and saw that Gazzy had produced a bunch of homemade bombs—yes, from his _pajamas_ —and started hurling them into the crowd. There were three fast explosions, and each one took out at least six Erasers. _That's my boy_ , I thought proudly— —and that thought cost me, because at that moment a huge, hard fist collided with my jawbone, rattling my brain and smashing my teeth together painfully. I rose into the air, fast, moving on instinct. As I took off I spit blood down on the crowd and moved my jaw to make sure it wasn't broken. I shook my head to clear it. A hundred to six—by far the worst odds we'd ever faced. But I wasn't going down easily, and neither was Fang—I'd make sure of that. I set my aching teeth and dive-bombed the mass of writhing, hairy bodies. "Max, _duck_!" I obeyed the order instantly. A bird kid streaked past me and rammed the Eraser I'd been aiming for. I had one startled second to glimpse sun-blond hair. Caribbean-blue eyes flashed at me and then turned their focus back to the battle. _"Dylan!"_ I half shrieked as I slammed my cupped hands over an Eraser's ears. His eardrums burst, and he howled in agony. "What the—Are you _insane_?" "Later!" he yelled back. "I'm sorry!" _So am I_ , I thought, and then grabbed an Eraser's thick wrist and twisted, snapping it and stopping the Eraser before it got to Nudge. But three more were already after her. And three more were coming for _me_. I dodged them and did a quick spin to get my arm around one of their necks. Suddenly I heard a loud roar: Ari had Fang in a choke hold. Fang's wings were pinned against his body, and Ari outweighed him by about a hundred pounds. I headed toward them but as I did a claw raked my leg, making me gasp, and then several paws grabbed my ankle and pulled me downward. My sneakers hit dirt, and then I was whaling, punching, chopping, and kicking faster and harder than I ever had before. I had to: This fight mattered more than any other fight. Fang's life hung in the balance. It was do or die for real this time. Possibly both. I dimly heard another battle cry and from the corner of my eye saw Dylan drop onto Ari, deflecting him away from Fang—a move that made my heart hurt. Dylan soared upward, into the black sky, and Ari roared ferociously, following him with hatred in his eyes. My breath caught in my throat: This would be a fight to the death. I knew it would. # MY IRRATIONAL DESIRE to join Dylan in combat with Ari was interrupted when a heavy hand on my shoulder made me spin, ready to attack. Jeb quickly held up his hands. "Don't _touch_ me!" I spat. His face fell, and in that moment, a thousand different memories flickered through my brain: Jeb taking care of us when we were little. Jeb leaving us. Jeb's face outlined by the fluorescent lights of the School. Jeb taking Angel, Jeb hurting us. Jeb trying to kill Fang. _Harden your heart._ I put my fists up and narrowed my eyes. "Max, please—just accept this." I still knew that voice so well. "Fang has to die. One man sacrificed for the greater good—it's the right thing to do, sweetie." _Sweetie._ " _Don't—you—ever—freaking—call—me—that!_ " I yelled, and then I kicked Jeb, the man who'd raised me, in the chest, hard enough that I heard multiple ribs cracking. "Ohh," he moaned in surprise. He staggered backward, and then his face went white and he collapsed in a dead faint on the porch, his head hitting the ground with a thud. I aImost felt bad, almost moved to help him. Almost. Then I reminded myself that he wanted Fang dead. I turned from Jeb's limp body and jumped right back into the fray without a second glance. There were probably about forty Erasers left, plus Ari. We'd made huge progress, but the six of us were at our breaking point. All of us were bloodied, with black eyes, broken noses, split lips. My arms ached from punching and being punched, and the spot on my leg where the Eraser had clawed me was burning and hurting so badly that I couldn't put weight on it. There was no way we could last much longer. Iggy was above me, with four Erasers circling him. It looked like he might have a broken ankle, which was preventing him from kicking out at them. All he could do was keep them away from the rest of us and hope to get in a lucky swing. Gazzy was trying to keep the Erasers away from the house and distract the ones that were after Iggy, but one of his wings was slightly crumpled, and he couldn't get off the ground. Several Erasers had him pinned up against a tree at edge of the woods. Nudge was screaming like a madwoman, pounding her sneaker into the face of an Eraser who held her by the ankle. But two more were coming up on her from behind. I didn't know who to help first. And I had at least ten Erasers taking turns diving at me. As I smashed my fist into another one of their disgusting faces, I realized that I had just gotten Angel back... but I might be about to lose someone else. Or everyone else. # CRIES AND GRUNTS overhead caught my attention. Dylan and Ari were both bloody and bruised, like the rest of us, and I couldn't even tell who was winning. Dylan quickly landed five lightning-quick kicks to Ari's stomach, making him double over and wheeze. But Ari straightened almost immediately and swung a huge taloned paw through the air. I bit my lip as he sliced Dylan's side to ribbons, sending blood splashing thirty feet below to spatter the trampled, icy grass. Ari had done that to Fang once. Fang had almost died. I watched, holding my breath, as Dylan abruptly turned and hurtled toward a tree. He grabbed a strong branch, snapped it off as if it were a twig, and dove back toward Ari. Dylan swung the branch in a deadly arc... just as something collided with my head so hard that I gasped and stumbled. Immediately, I felt blood trickling down my cheek. Watching the fight above had cost me. I jumped to my feet and almost fell back down as a wave of dizziness hit me. Wiping blood out of my eyes, I made like a windmill, fists swinging in hard punches that jarred my shoulders, feet shooting out in kicks that were backed by every ounce of my weight. I could hardly tell which way was up or down, but I wouldn't give up. I could hear someone yelling in pain in the distance. My flock needed me. "Don't give up, Nudge! Fang—help Gazzy and Iggy!" I karate-chopped the throat of my umpteenth Eraser and screamed encouragement to my flock. _I won't let them die._ Whirling in a circle, I delivered a kick that snapped an Eraser's arm before shooting up onto the porch, where three more of them were trying to get into the house. There were Erasers _everywhere_. I heard a bloodcurdling howl to my right. Dylan swung the tree branch again, and there was a sickening thud. Blood flew in all directions and Ari shrieked with murderous rage. He started to lunge toward Dylan but faltered suddenly, a fatal mistake. My heart pounding, I watched Dylan swing the branch again, a cold, grim expression on his frighteningly beaten face. This time, the branch smashed into Ari's head. Ari's wings folded and he fell down, down, hitting the ground with bone-crunching force. I stared at Ari's contorted, unnatural position—a position no living body could be in. Dylan—alive and upright—floated slowly downward to land a couple of feet away from me on the porch. He looked dazed, and his shirt was shredded and so wet with blood that I couldn't tell what color it had been. His face was so beaten up that I mainly recognized him by his hair. He looked exhausted. Older. "Max," he began, and gave a little cough. Then he collapsed at my feet. "He's dead!" someone shouted. I didn't know who. I was too stunned by the horror of what I'd just witnessed. But then, impossibly, miraculously, something else happened. The Erasers suddenly went limp and crumpled lifelessly to the ground one by one. # DYLAN WATCHED WITH half-open eyes from the porch floor. _Out of batteries_ , he thought. _Game over._ He was so dizzy, and not entirely sure he wasn't hallucinating. The fight with Ari had taken a lot out of him. "What the—?" Iggy said mid-swing, as the fist he'd aimed at an Eraser's face connected with empty air. "How come they're all down?" the Gasman asked exhaustedly. "Are they dead?" "What happened?" Nudge asked, swaying slightly. All of the bird kids were more whipped, more damaged than Dylan had ever seen them. "It's like... they were all linked," Fang said hoarsely. He wiped a hand under his nose, which was running with blood. Both of his eyes were swollen almost shut. "All connected, all 'wired' to their leader somehow. So if Ari died..." "Then they would, too," finished Max. But her voice sounded funny, and she wasn't looking at the fallen Erasers, wasn't preoccupied with them the way everyone else was. She was on her knees, looking at him, at _Dylan_ , her expression afraid and grateful and so, so tender it made his heart thump wildly in his chest. She did care, then. She had to. "Dylan, can you hear me?" she whispered urgently. Seeing his half-open eyes, she gave a sigh of relief. "I thought you were dead." She peeled his fingers away from his side. He looked numbly down at the wound, where dark blood was still flowing freely from deep, agonizing slashes. "Let's get you cleaned up." She tore one leg off her sweatpants and he watched her quick, capable fingers transform it into a bandage. He winced as she pressed it against him. "At least it's over," Nudge said weakly. She smiled through a split and puffy lip, then sat down stiffly on a step. "Well, almost." She warily eyed Jeb's quietly groaning, semiconscious form, still lying awkwardly next to the porch where he'd passed out earlier, but no one said anything—they'd deal with him later. "Cheers to that." The Gasman nodded and plopped down next to her with a sigh of relief, moving as if every muscle hurt. And yet... for Dylan, it still wasn't over. Not even almost. Dylan, after all, still had a mission. Though he and Ari had had the same goal, he hadn't trusted Jeb's motives, hadn't been sure that the rabid, enhanced wolves wouldn't go wild after Fang was dead and take out the entire flock. He'd needed to eliminate all threats to Max before he attempted his despicable mission. And he knew that once he had made up his mind, he had to be the one to do it. _Well_ , he thought, _now it's up to me alone._ He had to be the one to kill Fang. He struggled to his feet, conscious of Max's sweet, concerned eyes watching him carefully. "I'm sorry, Max," he murmured, so softly that only she could hear. And he whipped around, slamming his fist into Fang's already broken nose. # DYLAN THOUGHT THE shocked look on Fang's face was utterly priceless. It gave him the strength to do what he knew he had to do next. Dylan rose into the air with powerful strokes, the air swirling and roiling around him. Fang had shot away from Dylan in shock, anger, and surprise, twisting his face into a grimace as his nose gushed from the blow. But Dylan matched him wing to wing. He was the hunter, his body strong and sure in the pursuit, his face set in grim expectation. Dr. Williams had been right: He was stronger, more powerful, more advanced. He had been _created_ for this. There was only one way this could end. In his mind's eye, Dylan saw the fight from above—a giant bird of prey and a snarling, wounded grizzly clawing and screeching at each other, streaking violently through the sky like a shooting star, both intent on one thing: blood. Dylan watched as the bear twisted his lean body defensively, his dark, matted hair lifted by the wind. He watched the paw swing and find its mark, saw blood gushing from fresh wounds. Then Dylan was aware of a spark of electricity, a wetness vibrating on his arm. He saw those famous fangs, bared and gnashing as a deadly snarl built from somewhere vicious and animal within. Then he watched the eagle, stalking its prey from above with graceful speed and huge breadth, wings spread, talons out, ready to strike. Diving for the kill. Going for the throat. And before he could register what was going on, Max was there, between them, real and physical, her voice echoing in his eardrums. "Dylan!" she wailed, blocking Fang, _cradling_ him, propping his body up even as she kicked and clawed at Dylan's face. "If you ever loved me, if you care about me at all, _please_ "—her voice broke as sobs overtook her, and it was like a knife slicing through him—"don't do this." She was fighting him with all her strength, pulling at his hands, pleading with all her heart. Pleading for him to spare Fang's life. As if waking from a nightmare, he blinked a few times and panted as he looked from the tears running down Max's dirty, bloody face to the hands clenched, viselike, around Fang's throat. They were his hands, he understood with shock. He had wanted to protect Max, he told himself miserably. But Fang's death, he realized, would kill her as surely as any whitecoat could. That was when he realized he couldn't go through with it. Dylan loved Max more than anything. Even more than the survival of the earth. # JUST WHEN I thought Dylan was going to crush the life out of Fang forever, the word "us" changed everything. _You're better than this, Dylan_ , I had screamed at him. _They're the ones making you do this—not you. You don't want to kill Fang. Let him go. Do it for you. And me. Do it for_ us _!_ When I was sure that Fang was on his last breath, when I was sure my heart was one second away from irreversibly shattering, Dylan suddenly released Fang's throat and shot away from us, his powerful wings beating so fast they were a blur. I dropped to the ground with Fang's unconscious body in my arms, still weeping. "Is Fang..." Nudge asked, her voice trembling. I could only look at her solemnly as I heaved us both up and staggered toward the house. I didn't know how to answer her yet, and I couldn't voice the fears snaking through my thoughts. "Let's just get him inside," I said shakily. With the flock close on my heels, I laid Fang on the couch, wondering if I would ever have furniture that wasn't bloodstained. Nudge hurried over with a blanket and carefully covered Fang. I looked at my flock, being so strong, and my throat threatened to close. I sat down next to Fang and held his cold hand in mine, trying to warm it. I stroked his dark, bloodied hair. The blood vessels in his eyelids and cheeks had burst, and there were tiny red lines streaking over his pale face. The face I'd grown up with, the face I loved. His neck was all blotchy, covered in dark purple, hand-shaped bruises—it looked like Dylan was still choking him. "He's supposed to be immortal, anyway, right?" Iggy said from next to me. He was trying to sound tough, but I heard the fear in his voice, and saw how tightly he was pressing his lips together. " _Right_ , Max?" I shook my head. Iggy hadn't quite understood Jeb's shorthand scientific gobbledygook, but I couldn't explain it to him now. I couldn't speak. All I could think about was what Angel had said long ago: _Fang will be the first to die._ I pressed an ear to Fang's chest, holding my breath. His heartbeat was weak and erratic, but it was there. "He's alive," I said with a sigh, sweet relief flooding through me. Behind me, Gazzy cheered, and I heard small, hiccupping sobs coming from Angel. "He's okay, he's okay—he's just knocked out," I continued, my voice hard and determined. "He's going to be _fine_." I concentrated on Fang, trying to will his strength back into him. "Do you think he needs blood or x-rays or—" Iggy started to say, and then he suddenly froze, a strange expression on his face. _Everything changes now_ , I heard my Voice say in my head. _Be ready. You've won this battle, but the real threat has been unleashed. The war has only just begun._ I watched Gazzy's face grow even paler and saw the despair in Nudge's eyes, and I realized that the Voice wasn't just in my own head this time. Every member of my little flock had heard the same thing. _Be ready_ , the Voice repeated. _The 99% Plan is in effect._ # I DIDN'T EVEN have time to launch into a full-fledged freak-out over the Voice's message before my thoughts were drowned out by a distinctive chopping sound that was quickly getting louder and louder. "Is that a helicopter?" Nudge asked, peering out a window. "There's a helicopter now?" The chopper was super close—almost right on our roof, it sounded like. I hated leaving Fang for even a second, but I hurried over to the window. Outside, the treetops were bent almost double and dead leaves were flying everywhere. The house windows were starting to shake when the whirring sound of the blades slowed and stopped. "I seriously can't deal with this right now," I muttered. For the first time, I really didn't know if we were up to any new challenge. My flock was bloody and beaten up, Fang was still out cold, and Dylan was gone. If this was some new threat, I didn't have a Plan B. Or a Plan A, for that matter. I needed a break. But leaders don't get breaks. "Okay," I said, straightening my shoulders even though inside I was screaming. I pushed a strand of blood-soaked hair out of my eyes. "I'm going to go see what's up. If I'm not back in ten, I'm either dead or asleep on my feet. Stay with Fang—keep him safe. Do _not_ come after me." With that, I walked woodenly back outside. It was fully light out. I stepped over the fallen Erasers and past Jeb, who was still lying next to the porch, unconscious. I didn't have enough energy to feel anything toward the man who had created me, the man who had betrayed me in the worst way imaginable—more than once. I'd been awake since about three AM, and most of those hours had been spent locked in fatal combat. I was too exhausted to feel anything but despair. The chopper had landed on a piece of flat ground right next to the house. I squinted but couldn't see through the tinted windows, so I stopped and waited to see what fresh disaster was about to emerge. The chopper's small door opened. I braced myself. My mother, Valencia Martinez, stepped out. That did it. My knees gave out, and I crumpled in an ungraceful pile on the trampled grass. # "MAX!" MY MOM cried, and her voice washed over me like a warm breeze. She sprinted toward me, her arms open, her face twisted with concern. "It is really you?" I asked, blearily looking up at her as she lifted me from the ground. She nodded and smiled her warm, familiar smile. After a quick embrace she pulled back and gently placed both of her hands on my shoulders, her worried eyes appraising my blood-spattered clothes and dirty face. "Let me look at you," she said. "What happened to you?" "Jeb," I said bleakly. "Jeb happened. And Ari. And his Erasers. And Dylan... He attacked Fang—they were _all_ trying to kill Fang, and..." I couldn't stop the sobs that overtook me then. "Oh, honey," she said, hugging me tight. "I'm so sorry. I tried to get here sooner...." "It's not your fault," I said, still crying. I hugged her back with all I had, breathing in her warm, homey scent. "I'm not so sure about that, Max," she said quietly, her voice wracked with pain. I pulled away, wiping my nose on my dirty sleeve, and stared at her blankly. I couldn't process what she might have meant; I was too wrapped up in the joy of having her back. Mom looked at me solemnly, seemingly prepared for the worst. "Where is Fang?" she asked. "Is he alive?" I nodded, pointing toward the house, and she dashed off. The next hour was a blur of my mom checking on Fang and then helping the rest of us get patched up as best we could. Gazzy and Nudge both needed stitches, and I was so glad that my mom was a trained medical professional. For animals, but still. "Fang will be fine, I think," she said, and I breathed another sigh of relief. "He has a concussion, so he needs to take it easy for a while. But he should wake up soon. Everything else looks worse than it actually is." I nodded. With Fang sorted out, I finally asked the other burning question that had been on my mind: "Mom, what happened to you? Where have you been all this time?" Her eyes flicked to Angel and filled with something it took me a moment to recognize. "It's... a long story," she replied hesitantly. It was shame she had in her eyes, I realized. Angel blinked, looking down, and said nothing. My heart froze as I remembered what she'd told me: _Max, your mom was there. I saw her. Dr. Martinez. She's one of them._ The expression on my mom's face now told me Angel hadn't been hallucinating. "No," I said, drawing in a sharp breath. "No, Mom, not you..." I felt like I was trying to swallow a whole ice cube. "Please believe me when I tell you this, Max," my mom said tentatively. "I was brainwashed. Jeb brainwashed me as effectively as the Doomsday Group did Ella and Iggy. You remember how quickly that cult spread, like a pandemic. I... I never thought I'd be a victim of that kind of thing, and it still seems impossible to me that it happened. I'm a doctor, a pragmatist, not some unhinged fanatic! It's a mystery that I'm going to investigate for the rest of my life. But, honestly, Max, I don't have time to deal with that just now. All I know is that I have to get you kids to safety right away—" "Not so fast, Mom," I interrupted, crossing my arms over my chest and shaking my head in disbelief. "If you were brainwashed, how do I know you're not 'under the influence' anymore?" She looked at me intently, her eyes pleading. "I know it's hard to believe, Max. But after Jeb left, this... spell, or whatever it is... disappeared. Wore off. I don't know. Jeb just knows me too well. He's an incredibly smart and powerful man, and apparently he's figured out how to use his power to control me. I somehow fell into believing again in a man I once thought could change the world, stupidly following him into the darkness." For the first time, my mother seemed imperfect. And a hundred percent human. "When Jeb left the lab," she rushed on, "I suddenly saw the true horror in everything and everyone around me at the facility. I knew Jeb was insane at that point. But I also gained valuable information as... one of them. I knew 99% was beginning, so I left the lab and immediately notified Pierpont that we had to get to you and the flock. To implement the final steps we'd been working on together for so long." The rest of the flock was crowded around me, shocked into silence. My face was hard, giving nothing away as I listened. I didn't like the sound of the words "final steps we'd been working on together for so long." It seemed like this new development came with more secrets, more lies. The stuff my life was made of. "I promise you this is the real me, Max." Mom swallowed, looking at me levelly. "And I promise you, all of you, that I'm back now. I know what's right, what's true, and I'm on your side." None of us answered her or so much as breathed, but I could feel the eyes of each member of the flock on my face as they waited for my next move. Whatever I said, they would follow my lead. "Angel, check her mind," I said faintly, still trying to harden my heart against the possible outcome. "See if she's telling the truth." My mom closed her eyes, openly accepting the mind reading. _Please let that be a good sign_ , I said to myself. After what seemed like multiple eternities, Angel said, slowly, "She's being honest. Dr. Martinez isn't with the 99% Plan anymore. She's a good guy." # "NINO HAS A jet waiting for us, back near the city," my mom said. "We can take the chopper there. With the 99% Plan taking effect and God knows how many scientists seeking Fang for his DNA, you won't be safe here. You need a new beginning." Four pairs of eyes turned toward me, pleading. The flock waited for my decision. "Yeah," I said wearily. "Getting out of here sounds good." The flock responded with the biggest smiles I'd seen in weeks. But as we raced through the house gathering our things, Total weaving between my legs, barking orders about packing techniques, two thoughts wouldn't leave my mind: _Where is Dylan?_ And: _What about Jeb?_ I didn't know why Dylan had done what he'd done or where he'd disappeared to, so there was nothing I could do about the first question, regardless of how confused and devastated it made me feel. But Jeb _was_ here, out in the Oregon air, unconscious, with broken ribs that _I'd_ caused. If we left him, he would freeze during the night. I was helping Angel and Nudge carry their bags to the chopper when I finally made my decision. I flagged down my mom, who was turning off the lights and shutting the front door. "Wait—we need to bring Jeb," I blurted before I could change my mind. " _What?_ " Angel hissed, recoiling in surprise. Iggy was indignant. "Max, he wanted to _kill_ Fang, we can't just—" "We _can't_ just leave him out there to die," I cut him off. "He saved our lives once, and we owe him this. No matter what he's done." Sometimes being a leader isn't about winning. Sometimes it's about doing what's right, instead of what's powerful. "We'll keep him under lock and key," my mom agreed, giving me a look that said _I'm proud of you._ "He's a sick man, but not an evil one." She immediately set about tying up Jeb's hands and feet while the rest of us loaded Fang into to the chopper on a makeshift stretcher. Total had to be forcefully scooped and carried into the back, protesting all the while that he couldn't go anywhere that might be too far away from Akila. Mom reassured Total that Akila would be waiting for him at the place we were headed. She refused to divulge anything further. The pilot started the helicopter, and the deep noise of the blades filled our ears as we fastened our seat belts. I sighed as the chopper lifted off the ground and we left everything—all of our emotional baggage, Ari, a hundred dead Erasers, and the empty house in Newton—behind us. I wondered briefly what the neighbors would think of the mess we'd left in our wake, and couldn't help smiling. # WE WERE FIVE hours into a very long flight on Nino Pierpont's fancy private jet when Fang's eyes finally fluttered open. "Fang!" I shrieked. I was so ecstatic I almost kissed him right there, in front of everyone. Instead I settled for hugging him tightly, like my life depended on it—way too roughly for his injuries. "Max?" he croaked. "What... happened?" I took a deep breath and told Fang that he had been hurt really badly in a fight, and that when the fight was over, he was unconscious. I told him that Ari had been taken down in the fight, but I didn't mention Dylan. I told him how my mom had come for us, how it turned out that, in the end, Jeb was just another stupid whitecoat who had lost his mind. I was breathless, talking as fast as I could. I was afraid if I stopped talking, even for a second, I'd start sobbing again. "Whoa, there." Fang smiled and reached up, tracing a hand down the side of my face, winding strands of my hair around his fingers. "Stop talking and let me just tell you how great it is to wake up staring at your face. Okay?" That was maybe the most direct thing Fang had ever said to me. A lump formed in my throat. "Okay," I croaked. "Okay, so... it's really great to wake up looking at your face." He blinked, like his eyes were still trying to focus. "It's... beautiful, actually." The lump in my throat got bigger. Way bigger. "I thought..." I whispered, tears pricking my eyes. "I thought you were never going to wake up." "Come on. You really thought I'd leave you right when things were getting interesting?" Fang gave a gruff little laugh that sounded more like a cough. "Not in a million years." His eyes turned serious then, and he took my hand, bringing it to his cracked, swollen lips. "I'll never leave you, Max. Not ever again." My heart leaped. I squeezed his hand and nodded. "Me neither." For the rest of the flight I didn't budge from Fang's side. Sometimes I just sat there and watched his bruised face as he slept. Sometimes I woke from my own dozing to see his dark eyes watching me, as if I were a stranger and he was meeting me for the first time. And the whole time, awake or asleep, Fang never let go of my hand. Not once. And here's the weird thing: Even with all the awful stuff that had gone on, that was _still_ going on, I felt content. I felt whole. I felt _right_. I wasn't afraid of anything anymore. With Fang and the flock by my side, I could face anything. Come what may. "So, where are we going, again?" Fang asked, yawning. He squinted out the window. "To the one place in the world where you'll be safe," my mom said, turning around in her plush seat a few rows ahead of us. "To paradise." # Book Four # PARADISE # SIX BIRD KIDS and one very jet-lagged flying dog stepped off Pierpont's plane into glorious sunshine and tropical humidity. We left Jeb on the plane; my mom said that this place had a medical team who would deal with him, and that they knew to keep him under guard. "Just a short walk to your new home," my mom said, and soon we were parading after her through the welcome shade of the rain forest. I looked around me, struck dumb with wonder. Vines snaked up towering trees fuzzy with neon moss. Birds twittered and trilled all around us. Through a window of branches, we could see distant cliffs falling sharply to a beach of bleached sand and turquoise water. My mom was right: If you looked up "paradise" in the dictionary, this would be it. "Whoa," I breathed. "To our new life," Fang said, threading his fingers in mine, his smile implying so many things we hadn't been able to put into words: Together. Our new life together. I grinned, dizzy with the possibilities of this place. "Oh, my gosh!" Nudge said breathlessly. "Iggy! Feel the moss on the trees. Everything is lush and gorgeous and _so_ green. And there's parrots!" she squealed. "That's the noise you hear above, that weird cackle. There are tons of 'em—blue and red and yellow. They're huge!" Gazzy flew up to join the parrots and started swinging from vines, Tarzan-style, and Iggy zoomed up after him, deftly maneuvering through the trees. "Quickest way to ruin our first day in paradise? Scraping your feathered butts off the jungle floor!" Total yelled, and Gazzy hung upside down by one foot, giggling maniacally. "Ooh, I bet there are waterfalls, too," Nudge continued, ignoring the boys. "Tropical paradises always have waterfalls! Don't they?" My mom smiled indulgently. "They do, and there are." "Tree house!" Gazzy yelled from above. "Oh, man! You guys, look at all the tree houses!" The tree houses were camouflaged so well that I hadn't noticed them at first, but he was right—now I could see their shapes forming a village high in the jungle's canopy. A village just for us. "They have our names on the doors!" Gazzy yelled. "Nudge, this one's yours." "Really?" Nudge bolted up there as fast as her wings would carry her. Nudge's tree house was the most chic-looking of all the tree houses: ultramodern, with sleek, clean lines. It was minimal—almost delicate—and seemed to be held together by nothing more than sap. "A canopied bed!" I heard Nudge exclaim from inside. This was followed by a "Gazzy! Off!" I snorted with laughter. "I think that's yours over there, Total," my mom said, pointing to an enormous mansion of a tree house. "Mine?" Total asked, gaping upward. "Oh, Dr. M! Look at those glorious arches, the Grecian lines! Plush, with understated elegance and seaside charm," he gushed. "So classy! So regal! It's so... me." Just at that moment we heard a bark—and it wasn't Total's high-pitched yap, but the joyful call of a much bigger canine. A wet nose peeked out from between some of the tree-house branches above. _"Akila!"_ Total was off in a flash to be reunited with his furry lady love. _Wow. They really have thought of everything_ , I thought. Laughing, Angel, Fang, and I followed my mom farther down the path. "This is you, Max." My mom nodded up at a mammoth banyan tree. My new home was almost impossible to see if you didn't know it was there—the perfect hideout. At the top of the towering trunk, a canopy of leaves reached for the sun. "It's beautiful," I said in awe. "It suits you," Fang said from behind me, his breath making the hairs on my neck stand up. I looked at the brittle, gnarled roots snaking all the way up and around the trunk, creating a hard, protective layer for the tree's core. Maybe Fang wasn't so far off. "How do we get in?" I asked. My mom turned and smiled at me. "You fly." # _I COULD FLY in here_ , I thought breathlessly. _Inside my own house._ The tree was completely hollow. The ceiling was made of thick protective glass, but it was all the way up top, near the banyan's broad, glossy leaves. Strips of sunlight filtered through the canopy, reminding me of old, dusty churches with swallows darting among the rafters. Angel stayed with me to explore the place after Mom had taken Fang somewhere—who knows where; maybe a floating tree-house hospital in paradise?—to remove the bandages from his quickly healing wounds. As we explored, all kinds of cool little details caught our eyes. The furniture looked like the tree itself had just grown naturally into rough, chairlike shapes, and tunnels from the main room led to elaborate balconies with comfy hammocks. It all looked kind of haphazard, but at the same time beautifully, thoughtfully designed. _Someone knows me_ very _well_ , I thought. I pressed a button on one wall and a metal ladder spiraled silently down to the jungle floor below. Mechanical. _Fancy._ I soared upward, the wood circling around me in a blur, and found the latch to a door in the glass ceiling that lead to the roof. There was a small balcony high above the jungle's canopy where I could see everything: the towering cliffs on the other side of the island, the sea lapping against the sandy coast... and, of course, it was an ideal spot for spying on my wayward flock. The perfect perch. Angel and I sat there together for a moment. I was dreaming of long days of swimming, cliff-diving, soaring above the most beautiful place I'd ever seen, so I was surprised to suddenly catch sight of Angel's distant, unsettling look. "What, honey?" I said gently. She looked up at me urgently. "I want to stay here forever," she said, gripping my hand tightly. "Max, I never want to leave." "You won't have to, sweetie," I promised her. I peered at the banyan's sturdy silhouette and beamed. "None of us will ever have to leave again." I felt so much relief as I said it, knowing it was true. But Angel was still staring at me, like she didn't want to let me out of her newly recovered sight. Her eyes were huge in her little face, and she seemed pretty spooked. "Angel?" I said uneasily. "Are you sure you're okay?" "Yeah," she said, but it came out as a stressed little squeak. "It's just... nothing." I put my arm around her. "I know you've been through a lot lately, but that's all over now. You can trust my mom. We're thousands of miles from anyone who would hurt you, and totally off the radar. It's safe here. Really." Angel let out her tense breath and smiled. "Thanks, Max." She walked over to the doorway. "I'll be at my tree house if you want to find me." As I gave Angel a quick good-bye hug, I noticed that a thick branch connected my home to another tree house. I shimmied across it, wondering which member of the flock's butt I'd have to kick in the mornings, weighing the pros and cons of waking up to Nudge's sugary pop music versus being downwind of Gazzy's infamous morning emissions. Instead, the bold, black letters staring back at me from the wooden plaque on the door caused a helpless little squeak to come out of my mouth: DYLAN. Does. Not. Compute. That name on the door was like a hard fist to my stomach, and I felt all the stuff I'd been so good at swallowing come back up: Anger that he'd almost killed Fang in front of all of us. Hurt and confusion over his complete freak-out. Shame for all the stupid, fluttery feelings I'd felt when he looked at me with those ocean eyes of his. Clearly he was _not_ my perfect other half. Everything came spewing out like some sort of emotional vomit. Romantic, huh? And because the universe just loves to screw with my emotions, I felt a hand on my shoulder right then, and I nearly jumped out of my skin. Was he...? "Don't worry, Max," my mom said, striding past me. I exhaled. The ladder—I'd left it down. With one hard wrench, she pried the nameplate off the door and tossed it out of the tree like yesterday's garbage. "That sign will be replaced." Mom sighed. "Uhhh," I groaned, totally incapable of any other response. I clenched my jaw and concentrated on pushing every stupid thought of Dylan back down again. "Fang! Up here! Come see your house," Mom called from the balcony. She looked back at me with... what? Pity? "I'm sorry, honey," she said, giving my arm a squeeze. "He wasn't... expected." # "THERE'S SOMETHING ELSE you need to know," my mom said when we all met up again, and Fang's eyes flicked to mine. Was it all too good to be true? "What?" I asked uneasily. "Let me show you," she said, and then she called the rest of the flock to join her. After a short, brisk hike through the jungle, during which my anxiety steadily grew, the flock finally emerged to face the spectacular cliffs we'd seen from our houses. My heart leaped. I couldn't wait to dive over the edge and weave through all those crazy crevices, the wind surging through my feathers. But before I could take off, my mom put two fingers to her mouth and let out a crisp, high-pitched whistle. A signal. The flock looked around, confused. The place seemed abandoned. Then slowly, tentatively, people started emerging from the surrounding trees and from fractures in the rocks. I remembered what Angel had said about my mom earlier, that she was a traitor, and had a moment of panic. _Hostiles?_ I immediately took a defensive stance and the flock followed suit, ready to attack, but then I realized something. "There aren't any adults," I said, relaxing. "It's all kids." Their expressions were serene, welcoming, and as they came closer I saw scales, tails, metal arms. "They're mutants!" Gazzy squeezed Iggy's arm. "Yes," my mother answered. "All _enhanced_ kids. Just like you." As if to punctuate her words, a girl who looked about eight years old unfurled a pair of speckled black and gray wings, laughing to her friends. They all soared upward ten, twenty, thirty feet. "Just like us," Nudge whispered, echoing my mom. Even Fang was grinning. It was impossible not to. After so many years of being experimented on, of doing what everyone else wanted us to do, of running, running, running, we were finally in a place where we belonged. "Max," Mom said, and I followed her gaze to the jungle behind us. There, with a ginormous grin on her face, was my half sister. "Ella!" I squealed as she barreled into me for a bear hug. I hadn't seen her since our mom had her rescued and squirreled away from the 99% cult, who almost had her brainwashed. Back before Angel disappeared. In the middle of our embrace, someone tapped on Ella's shoulder and she turned around to see Iggy, looking shy and totally lovestruck. Her face lit up in a huge grin and she leaned in and kissed him, right there in front of all of us, and then Iggy wrapped her up in a long, tender hug. Watching them, I was drunk with love and hope and happiness all at once, and as the other mutant kids on the cliffs started cheering, I looked at Fang standing beside me, silent and strong. His fingers found their way to mine and his smile said everything I couldn't. We were finally, truly home. # THEN THE PARTY started. We walked into a hidden cove with lush green foliage surrounding a breathtaking waterfall, just like my mom had promised. I was waiting for unicorns to come galloping out and fairies to start singing. Nudge waded into the water, grinning as two girls her age chatted her up, their wings unfurled proudly around them. She looked so happy, so comfortable in her own skin. Iggy did a perfectly executed back dive with a half twist off the cliff, slicing the shallow water next to Ella with minimal splash, and I thought she was going to faint right there. Even Angel was looking more like her former self, laughing and splashing with Total and Akila as the Gasman torpedoed into them underwater. Fang and I were seated with Mom and Nino Pierpont at a wooden table off to the side, watching the festivities. Pierpont looked impossibly cool in his deliberately rugged, undoubtedly expensive trekking outfit as he watched us wolf down a huge meal of braised pork and paella, prepared by his bustling team of private chefs. If there is a way to our hearts, it is definitely though our stomachs—which is why I was getting a little nervous. "So, what's the catch?" Fang asked, obviously thinking the same thing. I housed a giant bite of sausage, wanting desperately for there not to be a catch, for once. "Hmm?" Mom asked, too innocently. "Like, is this how it all ends?" I asked. "No more experiments? No more running? Happily ever after, sleeping under the stars in our beautiful tree houses, living carefree in our island paradise?" My mom smiled, but her eyes said something different. "I wish, Max... I hope. God, I hope." Her glance flicked to Pierpont, who was shifting uncomfortably in his seat. "But..." "But what?" Fang asked accusingly, tensing beside me. "This is your new world. Your new community," my mom said. "But it's a community for..." "The ones who will survive," Pierpont finished her sentence gravely. "Wait," Fang said, dropping his fork. "The ones who _what_?" I looked at my mom in alarm, and she nodded sadly. I'd been hearing about the world ending for so long, had been preparing for this moment for years, but it still hit me like a rock falling out of the sky. "Can someone tell us what's going on?" I asked, my voice rising. "Can someone, for once, please just be _honest_ with us?" "Where do I even start?" My mom sighed. "How about with the part we know—that the 99 Percenters want to save the earth and its environment through the genocide of... well, almost the entire human race. So, what exactly is their plan?" My mom took a deep breath. I knew this was going to be hard to listen to, and I took Fang's hand. "They've been working for years on developing a form of avian flu that has a terrifying ability to quickly mutate and has been manufactured to mimic other, even deadlier, viruses, ebola among them." Mom looked me in the eye, letting her words sink in. "The virus is called H8E, but it's known among the 99 Percenters as 'The Finisher.' " "So we're more susceptible to it because we're bird kids?" I asked. "No, actually," Mom said, smiling. "It seems counterintuitive, but because of your mixed DNA, you kids have a natural immunity to it that we haven't seen in any other species. Of course, Ella and Nino and I, and some of the other enhanced kids—and Jeb, of course—aren't immune." My heart jumped into my throat. "And if, by some fluke and despite our precautions, the virus spread to this island and we became infected, and the virus then mutated after evolving through the simple human system—" "You don't have to worry about that, Maximum," Pierpont cut in, waving at my mom to shut up. I narrowed my eyes at him. "We've been working for years—since before you were born—to create a safe refuge for those who have the most hope of surviving and continuing the human race. We believe that you children will absolutely thrive here." "Wow, and here I would've thought that if you knew a biotoxin was being manufactured for decades, you might've been spending that time trying to create a vaccine or something," I said dryly. Pierpont took off his chic safari hat and ran his hands through his short, silvery hair. "It mutates too fast for that, Max," my mom said, unfazed as usual by my insolent audacity. "On the surface, of course, you have a tropical paradise," Pierpont continued, gesturing widely at the waterfall. "But should the worst occur, you will be safe inside a luxurious city of caves protected by a force field created with the latest technology. A complex system of passages will allow you to live quite comfortably belowground." "You mean until the biotoxin becomes extinct, along with the rest of the human race?" Fang asked. Mom and Pierpont were quiet, which I took as a "yes." "So... what exactly does this ultimate toxin do?" I asked, not sure if I really wanted to know. But I had to find out. I didn't want any more secrets. My mom studied her notebook. Then her eyes flicked to Ella, who was splashing in the waterfall. Then she stared down at her shoes. Mom was one tough cookie. If she couldn't say it outright, it was way worse than I'd thought. "Just give it to us straight," I said, huddling closer to Fang, who wrapped his arm around my shoulders. "We can handle it." "Okay." She sighed and started to read. "The toxin is first inhaled and moves through the lungs, causing a slight cough and, in some cases, a rash. The cells multiply, creating internal fissures in the organs and hemorrhaging into the bloodstream. A short time later, boils appear on the skin's surface. When the boils burst, the wounds weep, shedding billions of the highly contagious cells and infecting, basically, anyone in the vicinity." Mom cleared her throat. "At this point, with so many open sores secreting contagion, the victim will likely develop a staph infection that will quickly progress to necrotizing fasciitis, literally rotting the skin off the body in a matter of days." So, to break it down: You breathe in this little villain, and it basically liquefies your organs, then moves to your bloodstream, and then rots off the surface of your skin until you're a bleeding, writhing mass of agony, all while infecting everyone around you in every way possible. I felt bile rising in my throat. Fang's face had gone white, and I could feel him shivering. "Mark," he said under his breath. "The contagion..." We were remembering the same thing: Mark's last words at the hospital where Angel had been held captive. "Mom," I said, "could the... threat have been released already?" My mother didn't flinch. She obviously knew the answer. And she was going to tell it to me straight. "Yes," my mom said softly. "The toxin itself will kill almost all of the population on its own. But based on the agonizing effects it has on the human body, we estimate that at least half of the deaths will be from suicide." I let out a slow, unsteady breath. It was so much worse than I could've imagined. # LATER THAT NIGHT—after I'd finally been able to put all of what I'd learned out of my mind for a few blessedly peaceful moments—Fang crept across the branch connecting our tree houses. He gave a low whistle. "Penthouse, eh?" "Yeah." I nodded, watching the lithe movements of Fang's body as he surveyed my new digs, his glossy black wings folded behind him. "Honeymoon suite." Fang turned around and cocked an eyebrow, and my stomach leaped. "Well, in that case..." He strode toward me and, in one slick move, picked me up. He carried me out to a giant hammock on one of the balconies. I think we've established that I'm not the type of girl who needs to actually be swept off her feet, but the suggestion in his mischievous eyes was enough to make even the most cynical assassin woozy. We settled in together, and I was incredibly aware of the heat coming from Fang's body, which was pressed against mine as we snuggled. He nuzzled my neck, inhaling deeply. "Mmm. You smell so good." "Oh, yeah," I said, smirking. "I call this new perfume 'Le Jungle grime et tropical BO.' " "Dirt and sweat. _Very_ sexy." I laughed, but Fang's voice was husky, and he was already leaning closer. Then his soft lips were on mine. Everything in my body was buzzing, aching for more, but there was a kernel of guilt buried underneath it that I just couldn't ignore. "Fang," I whispered. "Mmm?" Fang mumbled, his lips brushing my neck and sending shivers through me. I kissed him again. Lately, my life felt like a freaking rags-to-riches fairy tale, complete with the perfect guy whispering sweet nothings in my ear. This felt so easy. So right. So _overdue_. Everything was finally as it should be. Except... The flip side of that was that while we were here, in paradise, chosen to be saved, humanity was about to be wiped out. It was so completely screwed up. I sighed, pulling away from Fang's embrace. "I'm sorry. I just keep thinking about what my mom said. Trying to make sense of it." "I know," Fang said softly, brushing my knotted hair out of my eyes. "I was trying not to think about it, pretend it wasn't happening, but it's always there now, isn't it? I keep thinking of my blog, all those kids reading it, dying in the way that Dr. M. described. It's, like, totally... incomprehensible." I couldn't tell if it was him or me who was trembling. I was so frustrated I wanted to scream. "We've been searching for something like this forever—safety, a place that could finally, really be home. And now that we have it, it's at the expense of everyone else's survival." "Welcome to the real world," Fang said, bitterness creeping into his voice. "Where kids are raised in cages, six-year-olds are tortured for the 'betterment of science' "—we both stiffened, thinking of Angel—"and a group of genocidal wackjobs can wipe out the entire planet with a bug cooked up in someone's kitchen." Fang and I were silent for a long time, the trees casting shadows on our faces and the knowledge of the world's imminent doom sitting like the Grand Canyon between us. The moon shone down on us, a giant eye, a quiet witness. I thought back to those miserable early days in the cages at the School and the short-lived freedom afterward, when Fang just felt like a brother and Jeb actually felt like a father. When I barely knew how to survive, let alone fight. When I first heard my Voice telling me I had to save the world. How long ago those days felt now. "I just feel so, so old now," I said, looking up through the leaves at the sky with its endless stars. "Like... twenty-one or something." Fang snickered. "We could always create a new birthday for ourselves," he said, reminding me that we'd done that once. "Seriously. How ridiculous is it that we can't legally drink alcohol, but the fate of the whole freaking world is on our shoulders?" Fang shifted in the hammock so he could peer down at my face in the moonlight, a wry half smile on his lips. "Since when do you care about what's legal?" I jabbed him in the ribs. Then his gravelly voice turned serious again, and I felt like he was looking right into me. "Also, saving the world isn't on us anymore, Max," Fang said. "Or you. We're past that." I blinked up at him and felt the last three years of my life fall away in shreds. He was right, of course. But if I wasn't supposed to save the world... Then who is Maximum Ride? # FANG WRAPPED HIS strong, sinewy arms around me. He stroked the spot between my wings as we swayed in the hammock in the cool night air. My whole body screamed to just drown in this moment with Fang, in his love—one hundred percent mine now, _finally_ —but my conscience just wouldn't shut up. "I know I should be grateful," I said after a few moments, my mind whirring. "But to be honest, I kind of resent Nino Pierpont—and even my mom—for protecting us, for saving only us. Like just because others don't have wings or aren't enhanced they're not superior enough to live?" "It's so frustrating," Fang said, sighing. "We've spent our whole lives either being totally exploited or trying to protect other people. And this time, there's no way to save them, no one to kill." "We're powerless." I sighed. We're all aware of my control issues. "It kills me," he agreed. "But I _do_ know that we were brought here, that we were saved, so that you could help this island full of kids who need you. You're one of the most stubborn people I've ever met, Maximum Ride. You're also incredibly intelligent, and beautiful, and charming when you want to be, which is probably why you can manipulate people into doing what you want most of the time." "I'm not manip—" I protested. "But those qualities also make you a brilliant leader," Fang interrupted. "And an awesome fighter. That's why you were chosen for this—to lead the new generation." "And meanwhile the rest of the world's just screwed?" I said. "Maybe." His soft feathers brushed against my skin, enveloping us. "But if the world's doomed either way, maybe we can have this _one_ night of our lives to just be together and forget that anyone else exists. To just be happy." I was quiet for a moment. _Just be happy._ How I ached for that freedom. "Max?" "Hmm?" Fang lifted my chin and looked down at me intently. He took a deep breath. "I've waited my whole life to be with you. Do you get that?" My heart fluttered as I nodded. I did. I felt exactly the same way. "So can't we just enjoy this? Just for a little while?" Fang's eyes were liquid black in the darkness, that familiar lopsided little smile playing across his lips. His lips... My heart raced as he leaned in again, never taking his eyes from my face. Then those perfect lips met mine in the softest, most tender kiss, and I closed my eyes and breathed in the sweetness of him. When I finally opened my eyes again, dazed with happiness, Fang looked shocked, almost pained, like he'd just realized something. "What?" I asked, nervous. "Nothing. I just..." His voice was hoarse. "This is _everything_. You're all I need." Then Fang's lips crashed into mine again, even more passionately, almost desperately. I kissed him back fiercely. I felt his fingers tangle in my hair, then his hands moving over my stomach, my hips, pulling me closer. I pressed against him, our legs twisted in the hammock. My entire body was shaking as I kissed him deeper, with a desire—a _need_ —I didn't even know I had. I wasn't actually positive I was even breathing. Fang held me tightly, like he'd never, ever let go again, and we kissed for what felt like an eternity, for all of those tense moments that had been building between us for years, and for every second we'd been apart. We kissed like we were inhaling each other, like we would live and die in this moment. We kissed like the world was ending. # AND THEN, SUDDENLY, it was like the world really _was_ ending. Without warning, an explosion tore through my tree house, dangerously rocking the structure like an earthquake. Adrenaline overloaded my system and Fang and I scrambled to untwist from the hammock and ran inside. Our senses were hammered from all sides: Glass shattering. Wood splintering. Someone crashing toward us with the force of a tornado. _What on earth—_ "GET OUT!" someone yelled at full volume. "GET OUT _NOW_!" A tall figure emerged from the shadows, looking totally strung out and insane and desperate. I nearly shrieked in fury. After ruining everything else, now he was ruining my perfect night with Fang. _"Dylan!"_ I exploded at him. "What are you even _doing_ here? On _our_ island?" "Max! Just give me a chance to explain—" "A chance?" My mouth hung open. I could not believe what I was hearing. "How _dare_ you. You went ballistic!" I yelled. "You abandoned the flock. And, _oh, yeah_ , you TRIED TO KILL FANG! You don't get anything, do you? There are _no more chances_!" "But this is it!" Dylan persisted. "I _saw_ something, in the sky." His eyes were wild. "We have to get out right now!" "No. _You_ need to get out," Fang said in a low voice. He stepped closer so that his face was inches from Dylan's. "Now." Dylan didn't flinch, but grabbed my wrist and tried to pull me toward the door. Fang shot forward, batting his hand away. Fang's face was warped with anger, his body rigid and his wings spread wide. He looked deadly. Things were spiraling out of control. "Look, I know things haven't been the best between us lately," Dylan said, backtracking. "But you guys just have to trust me—" _"Trust you?"_ Fang almost spit. "Why should we trust you?" "Because I have always, always had Max's best interests at heart," Dylan answered. Fang scoffed, but Dylan continued, his voice rising. "Because every second you stay here you're putting her at risk—putting everyone at risk. Do you really want that on your shoulders? Don't you care about her at all?" "Enough!" I yelled, stepping between them. "Okay," I snapped, pointing to Dylan. "You have sixty seconds. Start talking. Now." Dylan swallowed. "I saw something. In the sky," he said, breathing heavily, trying to speak coherently. "I don't know how to explain. We have to get to the caves, get all the kids out. Now." I shook my head. "It's okay. We know about the plague and the 99% Plan. This place was built to protect us. We're safe." "Even if no one else is," Fang muttered from behind me. "None of that matters!" Dylan shrieked. His eyes were wild, crazed. He looked like he was about to jump out of his skin. "This isn't a plague. Not even close." I put a hand on his arm to try to calm him. After everything we'd been through, it still hurt to see him like this. "You... saw something in the sky," I said gently, trying to make sense of what he was saying. "Did it have wings? Was it a jet? A flyboy?" "No, nothing like that." Dylan shook his head. "It's something... big. And it's moving too fast for me to clearly see what it is. But it's headed this way." Fang walked to the window and peered out. I looked at him questioningly, but he shook his head. "Sky's totally clear. The leaves are still—there's not even any wind. Are you sure you didn't just see a shooting star, buddy?" Fang asked dryly. Dylan's eyes hardened, his jaw tightening. "It was no everyday shooting star." I crossed my arms over my chest, thinking. I glanced back at Fang and saw his eyes flashing threateningly through his curtain of dark hair. He was rational to a fault. My _real_ "other half." And then there was Dylan, in front of me, looking all broken and insane and like he really needed me. "Do you not hear what I'm telling you?" Dylan asked in frustration. "Max, I was created to protect you." "Protect _me_?" I bristled. "I have spent years leading this flock, making split-second decisions based on well-honed instincts," I growled. "You have been alive for, what, a minute? And you've spent the past few days having a well-documented meltdown. Now, after almost murdering Fang, you have the nerve to show up here, to insist that we follow you because something weird is about to just... fall from the sky?" I was hitting a fever pitch. "Who do you think needs protection more, Dylan, me or you?" His eyes were pleading, but I wasn't moving. "It's coming _now_ ," he said. "Please." I sighed. "Dylan, just... go." "Fine, stay here. I'm getting the rest of the kids to the caves. I'm not having their deaths on my head." Dylan sighed sadly. "I know you don't trust me anymore, Max. But I've never lied to you, not once, and though it might seem like I've done some questionable things, I'm not crazy. You have to know that everything I've ever done, I did for you." I cringed as he turned his back on us, his shoes crunching over the broken glass. "And Max," Dylan called from the doorway, "after I get everyone to safety, I'll be back for you. Even if it means dying with you out here. That's the only way I want my life to end. With you." # "WHO DOES THAT guy think he is?" Fang exploded after Dylan was out of sight. "Seriously!" I was as cranky as a wet cat and pacing furiously. "What the heck does he think he's doing barging into my house"—I gestured dramatically—"in the middle of—" I locked eyes with Fang. He raised an eyebrow, and his smirk sent a buzz through my whole body. "In the middle of the night. Trying to freak everyone out?" I yanked an upturned table back over and slammed the door Dylan had left open. "Max," Fang said cautiously. When I turned around, there was uncertainty on his face. "Do you think he might've really seen something? His vision is crazy sharp, isn't it?" "Oh, please," I huffed. "It's not that great. And I don't know if he's short-circuiting or what, but he's clearly not the brightest bulb right now." Fang nodded and bent to right an overturned chair. One of the reasons Fang and I work so well together? He keeps his mouth shut when I'm in fire-breathing dragon mode. Unlike Blondie down there. At that point, I'd almost gotten used to Dylan strapping us in for his own personal roller-coaster ride of highs and lows, complete with lingering nausea at the whole rotten experience. This, however, was on a whole new level. _I was made to protect you_ , he'd said, his sea-blue eyes begging me to trust him, still full of that same fierce drive he'd shown when I'd taught him to fly, not so very long ago. But that dopey innocence, which had seemed almost endearing then, was nowhere in sight now. I shook my head. I couldn't afford to be sentimental. Not anymore. Sentimentality is for suckers. And a sucker, I ain't. _Harden your heart._ Done. My heart is a freaking diamond. Only less glittery. I bent to help Fang pick up the pieces of glass from the shattered window, and I couldn't help staring down at the havoc Dylan was already wreaking on our little paradise. The place had gone from zero to sixty in minutes, and I watched as he herded dozens of hysterical kids into the ultra-secure underground cave system. Abuse of privileges. Mom was gonna freak. "Gazzy!" I shouted when I spotted him moving along in his bobbing gait. "Nudge!" Iggy was with them, consoling Ella as they hurried toward the caves. Even Total was barking anxious orders at Akila in their dog language. "You guys, he's delusional. Cuckoo. There's nothing to worry about!" In the chaos, they didn't seem to hear me. "Oh, no," I fumed. "This. Will. Not. Stand." Making a mess was one thing. Hijacking my flock was another. "Wait, where's—" "Angel." Fang pointed at the ragged-looking ball of feathery fluff zooming toward us through the trees. She was sobbing as she crashed into my arms. "Whoa," I said, cuddling her close. "It's okay, Ange. You're okay." Angel shook her head, her soft curls framing her tear-streaked face. "You guys have to get to the caves," she said, hiccupping. "It's coming. Dylan saw—" "Yeah, I'm going to put a stop to that," I reassured her. "No!" she wailed, her blue eyes wide with fear. "Dylan knows what he's doing. I saw things when I was in that lab, Max. Horrible things." Her little face contorted, and my mother-bear instincts raged. _As soon as we get off this island_ , I swore, _I am going to hunt down those sickos who hurt my baby._ "But we're never going to leave here, Max. We can't leave. You promised!" Angel cried, reading my mind. I wiped the tears from her face and cupped her tiny chin in my hands. "It's okay, sweetie. Deep breaths. What did you see in the lab?" "I saw trees falling over like dominoes. This place, coated in ash. The light comes first, then the sound. And you and Fang, blown out of the sky." Fang's dark eyes flicked to my face, but he didn't move. "When we landed, it seemed familiar, but I wasn't sure. It all makes sense now, though. Dylan is right—the sky is falling." _It's time_ , the Voice inside my head said. _Listen to her, Max._ # THE WORLD WAS ending, and we were in paradise. I knew I should join the others, kiss away the rest of humanity, and spend the next fifty years snuggled up to my winged prince charming, finally free. Fang and Angel were both studying my face closely. I shook my head slowly. I knew this was the decision that would define my life. I just didn't have it in me to die like a coward. "I'm flying back to the States," I said. "Now." I stepped past them, out onto the limb between the tree houses. Below, the jungle was quiet, the leaves rustling softly. Except for a few small figures I could see at the cliffs in the distance, everyone was already safe in the caves. If I was going to do this, if I was going to walk away from my flock, maybe forever, I had to go before I lost my nerve. "What?" Angel looked horrified. "Are you sure?" Fang asked, his face trusting and true. I nodded, trying not to look into his eyes, trying not to think about what I was leaving behind. "If the toxin has been engineered like my mom said, there has to be an antidote. Or maybe Mark was lying. Maybe the contagion hasn't been released. Maybe we can stop the psychopaths before they release the bug. But if it _is_ released... Well, at least we can warn people." Angel shook her head. "Max, you don't understand what you're up against." "Look, it's not like the odds haven't been stacked against me before," I said, trying to sound reassuring. "I always come out all right in the end, don't I?" I didn't say what everyone else was thinking: that it might actually _be_ the end this time. "Please don't do this now," Angel pleaded, reaching for my arm. "We have to get to the caves. Fang, tell her! We'll be safe, I promise. Just come with us." _Listen to her_ , the Voice repeated. _Go._ I'd been obeying my Voice for so long, trusting whatever it said, even when it seemed to be mocking my existence. But I couldn't do it this time. Not when the consequences were so major. "I can't, sweetie," I said to Angel. "I'm tired of running from the unknown. If this threat is real, I'm going to face it, whatever it is, with the rest of the world." I looked at Fang, standing next to her. _I'm sorry_ , I mouthed, my heart breaking. But Fang walked out to the limb and took my hand. He brought it to his lips and, without taking his smoldering, coal-black eyes from my face, said, "I'm with Max." "Fang, no, you can't," I said. If this really was it, the end of the world, I couldn't ask this of him. "Yes, I can. We'll fly back to face 99%," he said, nodding at me. I stared at Fang for a long moment. It felt like we were one person. "I'm with you," he repeated solemnly. "But it's not them!" Angel shrieked from the ledge. "Aren't you listening? All the preparation Dr. Martinez and Pierpont and Jeb and all the other whitecoats did, poking and prodding and testing us, shooting us up with God knows what to make us immune—it was all totally pointless! It's not coming from 99%. It's coming from the sky." Fang shrugged. "Then we'll face the thing in the sky. Whatever it is, we'll face it together." He gave my hand a squeeze, and tears streamed down my face. "You'll die here!" Angel cried. "You'll both die, falling, just like what I saw." I looked down at her, not sure how to explain myself. "Angel, I was supposed to save the world," I said quietly. I paused for a moment, realizing the gravity of that statement, and then stood up straighter, suddenly more sure of myself than I'd ever been. "I was supposed to save the whole world—not just the 'special' ones, not just the ones who have the protection of some multibillionaire. So if the rest of the world has to die, I have to go down with them." I looked out across the row of abandoned tree houses with the pristine beaches in the background. _So long, paradise. It was nice knowing you._ Fang and I snapped out our wings and prepared for takeoff. "Max!" Angel shouted. "Listen to me. You have to. I'm your Voice!" # I COULDN'T HELP but gasp. Then I quickly regrouped. I retracted my wings and shot her a supremely annoyed look. "You're not serious," I managed to say. "You always listen to your Voice, right?" Angel said, hovering in front of us, her white wings outspread. "So please, please, listen this time." "Are you really going to do this right now?" I growled. "Come on. I think we've all grown out of playing games at this point, Angel. You especially." "I'm not playing games. It's me. It always has been." "Let's just go, Max," Fang said, his fingers brushing mine. "You know what she's doing." "I've always been your Voice," Angel insisted. I'm sure my face positively dripped with skepticism—I'm not exactly good at hiding such things—but she started counting on her fingers. "Before you found your mom, way back when we were looking for the Institute, your Voice guided you into the sewers with a riddle, right? Something about rainbows?" She cocked an eyebrow. _There's a pot of gold under every rainbow, Max._ Angel laughed, and it sounded creepy, almost disembodied. "I definitely had more fun with it, in the beginning, being inside your head." Her eyes darkened, and I looked at Fang uneasily. "Then it got more serious. When you first killed Ari, the Voice told you that you had to do it, didn't it?" I winced, thinking of the day I'd murdered my half brother. The first time, when he had really felt like family. I was speechless. We didn't talk about that day. Why was she doing this? "That was me, too. I could feel your anguish, Max. And I knew he'd come back anyway, again and again, worse every time." "Angel." Fang's voice was hard, protective. "That's enough." But she went on. "I was the one who told you that you had a greater mission in the first place. This is that mission: leading the new society after the apocalypse." The Voice had said all of those things, true. And, true, no one knew about them but me. But Angel could read minds. Of course she could know everything the Voice had ever said to me. She was manipulating me. Again. "No, Angel. The only thing _you_ told me was that Fang was going to die." I looked at her accusingly. "I told you that Fang would be the first to die because I saw it, in a vision. I saw him falling." "And you were wrong about that, weren't you?" I asked. "He's still here." "It's still true, though." Angel frowned. "It's not over yet. Soon, but not yet." No. NO. I shook my head against her idiotic claims, her attempts at mind control. We had been through all of this too many times before. "I know it hurts," Angel said sadly. "Didn't I tell you to harden your heart?" "You're wrong," I said through tears, clutching Fang's hand. "You're lying." "I told you knowledge was a terrible burden, Max," Angel whispered, and I could hear the Voice saying those exact words in my head, years before. "That's why I couldn't tell you. Do you know how hard it is, seeing everything that's going to happen all the time?" There were tears shimmering in her eyes, a bitterness in her voice. She sounded jaded, old. So much older than a seven-year-old should ever sound. "Imagine feeling what people feel, thinking what they think. It's so hard to stop listening, even when it hurts. Your Voice said she considered you a friend and loved you more than anyone. I meant it, Max. I always will. Don't you trust me?" I thought about that question long and hard. How I'd missed her, how I'd felt like my heart had been ripped out of my chest when we thought she was dead. But it was Angel who tried to hijack my leadership, who put the flock in danger over and over again. Angel who could kill us all. She was my baby, and I loved her so, so much. But did I trust her? Angel's face crumpled; she looked hurt and betrayed. She turned from us then and soared off toward the cliffs. _Don't deny the truth_ , the Voice said inside my head, and this time it was Angel's voice, sweet and coaxing. _Now is your time! Save yourself and the others! Do it now!_ I spun around, flabbergasted. I was choking on tears. "What are we supposed to do?" I asked Fang. I'd been doing this for so long, taking on the responsibility, making all the decisions, that I'd forgotten what it felt like to have absolutely no clue where to turn. "After all that, what the heck are we supposed to do now?" Fang shook his head and stroked the sides of my face with his slender fingers. "I've spent my life trying to deny what I felt, when all I ever really wanted was to be with you, Max," he said. "I don't care what Angel says. I'm with you. Always. Whatever you decide." But as I looked into Fang's angular face, his pupils suddenly dilated to pinheads as the world lit up around us. I wasn't going to get to decide, after all. # THE SKY WAS on fire. I mean really, actually, burning through the clouds on fire. A moment before it had been blue and calm, but suddenly the entire sky was exploding, as far as I could see, reaching from the jungle all the way across the ocean. The light was nearly blinding as the yellow and orange flames licked overhead, burning through the atmosphere. I heard Fang inhale sharply next to me, and we both stared in awe and wonder. Seconds felt like hours as we watched the whole horizon transform into a raging inferno. I could not move. It was... dazzling. More than that. It was awesomely, terrifyingly beautiful. Like, it hurt to look at. The most spectacular sunset the world would ever see—this was the world's final good night. Moments later, a gash ripped across the sky, splitting it into two flaming halves, with an aching hole of nothingness between them. Then the split opened wider, like a horrible, garish sneer, and I felt all the dread I'd been bottling up sigh right out of it. I held my breath as I waited for the hand of God, or aliens, or even vindictive Ari, back from the dead one last time, to reach out and pluck me from where I stood. Instead, from that gaping mouth came a wave of excruciating heat that swept through the jungle and right over us. I snapped out of my trance and collapsed to the floor in agony, tearing at my feathers, my clothes; I was sure my skin was boiling off. I couldn't even scream—my lungs were like shriveled little steaks baking inside my chest. I was hyperventilating, trying desperately to breathe. Everything was getting fuzzy, except the pain. I was passing out. But after what felt like a century of torture, the gap zipped closed as quickly as it had opened. I gagged, sucking in the cooling air. I was alive. With intact skin and feathers. How was that even possible? I squinted upward, disbelieving. Except for some dying red streaks, the fire was no longer scorching the sky. My adrenaline finally caught up to the insanity and the world rushed back into place. I scrambled to my feet, looking around wildly. I didn't know what I was looking for—just an answer, a direction I could follow. "Everybody's at the caves!" Fang wheezed over the now furious wind. Smoke and ash billowed around us. I shook my head stubbornly. "Not Angel," I croaked, my throat raw. Fang looked me in the eye and saw what else I couldn't say: _Or Dylan._ They'd be at the cliffs, rounding up the rest of the community. Like I should've been from the start. Together, in silent agreement, Fang and I shot into the sky. A few hundred meters away, all the trees were scorched—a few more seconds of that heat and we would've been human fireworks. As we raced over the smoking jungle toward the coastline, we saw trees crashed down on one another like dominoes. Their trunks were stripped of bark and branches from where the fire had come. Suddenly then there was a bang like nothing I'd ever heard—like a bomb connected to an amp had been detonated right inside my skull. It sounded like what the fiery explosion should've sounded like, but it came more than a full minute later. It was like I'd been shot. I felt it in my teeth, and vibrating through my brain. I felt it in my wings as I flapped and spun uncontrollably. It sang through my eardrums and made my eyes blur. And then we were falling. Down. Down. Like Angel knew we would. I watched, helpless, as the ash whirled around and the jutting precipice of rock raced up to meet me. Then the eyes of the world winked shut. # _GET UP_ , A fuzzy voice shrieked. _Get up get up get up._ It sounded water-soaked, low and slow. Was it my Voice, or Angel's, or someone else's entirely? I didn't even know if it was real. The ringing in my head grew, turning into a sound like the hiss of rushing water, an echo bouncing around like a rubber ball inside my head. Wind whipped around me and the hiss grew to a wail. My brain throbbed. I covered my ears and felt wetness. The metallic smell of blood burned in my nostrils. I pried open my eyes, and that's when the hurricane-strength needles of rain started to hit my face. I turned to look for help and felt my stomach lurch as a strong arm yanked me back, keeping me from plummeting over the edge of the cliff. "Get up!" Fang yelled in my face, finally piercing through my confusion and dragging me to my feet. I looked across the cliffs for the other kids, but saw only a wall of water out in the sea. Not just a wall—a massive wall, miles long and taller than a skyscraper. Surrounding us. The monstrous wave grew more massive by the second, almost blotting out the smoking sky as it surged toward the precarious crag we clung to. A mega-tsunami. I instinctively tried to flap, but a searing pain shot through my mangled, bleeding wing. Panic froze my heart. This was it. There would be no more. I felt a sob of self-pity building in my chest, but Fang held my face in his hands and looked at me urgently, his eyes locked on mine. "I love you, Max," Fang said, and those words, the ones I'd been waiting to hear forever, towered above all the chaos, making everything else fall away. Whole universes were built and destroyed by those words. There were tears in his eyes. "God, Max, I love you so much." _I know_ , I thought. _I've always known._ Then Fang's stormy eyes grew blacker than I'd ever seen them as they looked past me, at our fate. I turned to see the wave swelling toward us, seconds away, the white foam of its mouth howling higher and higher. But I wasn't surprised, or scared, or even angry. I accepted it like a friendly wind, come to fly me home. _It's okay_ , I thought. And it was. Fang kissed my eyelids, my cheeks, and then my lips one more time, whisper soft. Then he clutched my head to his chest and we took one last deep breath, wrapping ourselves in each other's arms for eternity as the warm water crashed over the cliff and swallowed us whole. _I love you, too, Fang._ # Epilogue ## [MAX'S LAST WORDS](toc.html#toc-epilogue) # NOW, DON'T GET all weepy on me, dear reader. No chin-quivering or nose-sniveling, either. These pages do not need to be all soggy with your mucus. There's nothing to moan and groan about, anyway. The truth is, I am the luckiest girl in the world. Don't give me that I-can-see-right-through-you-Max- and-not-just-because-you're-freaking-dead look. I'm serious. Think about it. When the end comes, will you be buried in the arms of the one you love? Of the one who knew you your whole life, who loved you your whole life? The one person who could really and truly love you like you needed to be loved? I hope so. Because I was, and I wouldn't change any of it—not for anything. Not even the world. Okay, I can see that you're upset. I know you must be wondering, just like I'm wondering right now: Was I really supposed to save the world, or was it all just a big lie? In other words, did I fail? (Gosh, it sounds so ugly when you put it like that.) Or was my life just a metaphor for what we're _all_ supposed to do with our lives—that each of us is supposed to believe that we _can_ , that we _must_ save the world? That the world will be saved only if we _each_ take that kind of responsibility? Because if this life has taught me anything, it's that we can't leave anything up to fate or chance, or for someone else to clean up. Because in the end, "special" people are still just people. Because, PS, those so-called special people _can't_ actually save us. We all have to save ourselves. Or maybe this was a lesson in carpe ever-loving diem— _seize the day_ , kiddos, and hold tight to your loved ones, the only part of life that really matters, and live each moment to the fullest, because you never know when an explosive ball of gas is going to light up the sky and blow you into oblivion. But no, really. Was it all just a big shrug of meaninglessness that will now plunge you into a pit of existential emptiness and melancholy? I hope not. At least, don't blame me for it. What, carrying the weight of the whole world wasn't enough? I have to look out for your happiness, too? Jokes aside, I really do hope that my life meant something in the end—that it meant _all_ of those things. I don't know what's next—what any of us can expect—but I do know that I'm ready to see what's out there for me. In fact, I think I hear Fang calling my name now. He sounds so far away.... You guys? I don't want to, like, freak you out at this point in our journey, but I think I'm starting to see that famous light at the end of the tunnel that you always hear about. This is where we part ways, I'm afraid. Before I go, even if you've rolled your eyes at every bit of cheesy advice I pulled out of my butt when the flock needed some pep in their patooties these last few years, know that I mean this last little nugget from the bottom of my not-really-so-cynical little freak heart: Save your world. Love it, protect it, and respect it, and don't let haters represent it. Don't leave the saving to anyone else, ever, because, exhibit A—why, hello there!— _it's way too much for one person_. And if you want to skip out on the responsibility train, my whole life—and death—will have been in vain. It's yours. It's all yours for the taking! You're not going to waste it now, are you? # Epilogue the Last # [THE BEGINNING](toc.html#toc-epilogueb) # One WHEN I OPEN my eyes, everything is dim blue wonder. Playful shapes of light dance across my vision, diving, and dipping, then merging into shadow. I thought heaven would be brighter. I'm spinning, and I watch in bug-eyed wonder as my hand moves in front of my face in slow motion, my fingers leaving streaks like sparkler trails in the dark as my eyes try to adjust to their movement. I can feel the air as I push and poke, think I can taste the sound of what blue feels like—a whale's warbling echo. Or is that singing? Of course _my_ angels sound like strangled whales. It's wonderful feeling weightless, free. Almost like flying, but without even having to move—floating toward an easy, carefree eternity of being rocked like a baby, free of all burdens and responsibility. I actually sigh with relief. Wait a minute. I just _sighed_. I'm... breathing? Underwater? I'm alive? "Max," I hear a voice call from above. What a magical sound that is. _Hmm?_ I think. _Voice, is that you pestering me again? Do not disturb. Busy floating. Call if you want to talk rainbows._ A disembodied hand grasps mine and pulls me upward. _Are you there, God? It's me, Max._ "Max!" The voice is clearer, immediate. The water cradles me closer. _Am I moving at all? Is this real?_ My eyes trace slowly, lazily up the hand that's entwined with mine, the squared fingers tan and vaguely familiar. And strong. Like the arm and shoulder the hand is connected to. The face finally registers just as we break the surface. As does shock. Thrashing, I stupidly suck in a huge breath through my nose, instead of using the gills I developed long ago. The harsh air rips through my lungs, and I double over, coughing and choking out water. "I told you I would come back for you," Dylan whispers, rubbing my back. # Two FANG, DYLAN, ANGEL, and I sit perched on a large, exposed ridge of rock that rises high out of the water. We're alive. A little soggy and a lot banged up, maybe, but still living, breathing. Survivors. Hawks soar above us, diving through the narrow crevices, their long brown feathers mirroring my own. As the sun warms my face, I long to join them. I peer out over the vast strangeness of the landscape, a charred wasteland: the island, now broken up into hundreds of smaller islands, with narrow inlets snaking in and out of them; the spindly remaining trees, branchless, barkless, standing straight up like frightened soldiers with an army of dead brothers at their feet; the hardening ash, swirling into surreal silver spirals, hot air belching out of cracks in the crust to form thermal pools; and an unfathomable high-tech city of luxury, sealed in caves that are now buried below the turquoise water. It's been only a few hours since the Split—when the gash in the sky severed this new world from the old one—but we swam and limped and swerved into our new existence feeling changed. But we haven't changed, really; the rest of the world has. And somehow, this new world makes sense in a way that the old one never did. Fang's tying a singed but sturdy branch to my wing with a scrap of his T-shirt, creating a splint. My wing, though still painful, is already healing before my eyes. Because it was _made_ to. We are not fragile creatures, after all. And that is why we're still here. Dylan is watching Fang's movements—deft, efficient—but there's no threat there. Something has shifted. In all of us. "I read about something like this happening in Russia," Dylan says, answering the question we're all asking in our heads: What, exactly, was that _thing_ that split our world in two? "The Tunguska event, I think it was, in the early twentieth century. A meteor exploded near the earth's surface and wiped out miles and miles of forest." I can't help but notice how confident he sounds, how he doesn't look down when he talks, how he's no longer embarrassed about his interest in science, his love of books. He's just eager to share the knowledge that will help the group survive. He knows, as we all do, that we can use any help we can get. "This seems a lot bigger than that one, though," he says. "I wonder if anything like this is happening elsewhere—like a ripple effect or something. Just look at the sky. I've definitely never read about anything like that." The sky has taken on this bizarre, Technicolor hue that warps and shimmers like some psychedelic black-light poster—totally surreal. Yet... it feels familiar, somehow. Like I've been dreaming about it every night of my life, but I've just forgotten my dreams each day on waking to the life in which I have been trapped. I keep thinking how amazing this place is going to be to explore by air. Dylan stands up. "We should probably start combing the perimeter for possible other entrances to the caves. The main line I took everybody through is now underwater." "I'll check out the tree-house village," Fang says. "See if there's anything left, start the rebuilding." He gives my hand a tight squeeze, but that desperation, that urgency between us is gone. No insecurities. Max and Fang. Fang and Max. No longer a question. We just _are_. Angel and I sit together on the edge, watching the guys soar through the air. We don't need to talk, because everything is understood. The weirdness that had come between us is gone, and since resurfacing I haven't heard a word from my Voice, trying to tell me what to do. There's no leader now, no power. We're all working—quickly, efficiently—together. It's well documented that I've never been very good at school or any of the other junk normal kids are supposed to slog through. That's because I'm _not_ normal, and never have been. None of us are. But in this postapocalyptic world, on this tiny, wrecked island, I have a feeling we're going to excel. "Dylan's right that this thing's big," Angel says after a few minutes. "I'm tapping into Dr. Martinez's thoughts, and they're monitoring satellite connections all over the world from inside the caves. This wasn't the only event. It's triggered a ripple effect. There's been major volcanic and tectonic activity. Whole countries may be covered in water, ash, or flame. It's unclear at this point." The two of us are silent for a long moment, letting that sink in—that the whole world and probably most of the people we know in it are done for. "I'm so glad that it wasn't me, that it wasn't us," Angel says, her eyes brimming with tears. "Isn't that selfish?" I shake my head. "It's not selfish. _We're_ here. _We're_ alive. I'm not going to apologize for surviving." That might sound harsh, but through the grief and the devastation, I can't help feeling hope, too. If you could choose between life and death, wouldn't you leap toward living with everything you had? No one wanted life as we knew it to end. But we were _made_ for this. Surviving, I mean. And the truth is, we weren't that great at fitting in to life as we knew it, anyway. In fact, life as we knew it kind of sucked. Stuck in cages, trackers implanted beneath our skin, all that power they shoveled between us, turning us into sideshow freaks. That's all over now. The whitecoats only know how to live in a world where they can have cushy homes and order factory-farmed, premade food. This is definitely not their world. It's ours. "I know what you mean," Angel says, reading my thoughts. Her blue eyes have a faraway look, and even without the ash in her feathers, she looks older, more mature. Like she grew a century in an hour. Like she grew into that Voice of hers. "It's almost like we were meant for this world, and not that other one. Like it's finally our time." It's a dark thought, but one I can't turn away from. This is an environment that requires a little something extra from its inhabitants. Half of it is underwater. And we have _gills_. The other half is made of unreachable cliffs and towering trees. And we have _wings_. This place is primal, and it's raw. I was made for this. And if I'm going to start this new life being who I am truly meant to be, there is something I know I have to do. I look beyond Angel's windblown curls and see that Fang has returned and is looking at me. I walk over to him, our gazes fully locked. And when I reach him, I don't hesitate to say what I know is the most important truth of my life. The only truth. "I love you, Fang," I whisper. He smiles and takes my hand. We stand together on the precipice, opening our wings to their full span and watching the long feathery shadows reach out over the land below. In a way, maybe I did die in that wet grave, because it's like I was completely reborn when I came up from that water. The air feels different to me now. I'm breathing it differently now. Like my body is a whole new machine. It _is_ my time. The time of Maximum Ride. # I have some really bad secrets to share with someone, and it might as well be you—a stranger, a reader of books, but most of all, a person who can't hurt me. So here goes nothing, or maybe everything. I'm not sure if I can even tell the difference anymore. The night my parents died—after they'd been carried out in slick black body bags through the service elevator—my brother Matthew shouted at the top of his powerful lungs, "My parents were vile, but they didn't deserve to be taken out with the _trash_!" He was right about the last part—and, as things turned out, the first part as well. But I'm getting ahead of myself, aren't I? Please forgive me.... I do that a lot. I'd been asleep downstairs, directly under my parents' bedroom, when it happened. So I never heard a thing—no frantic thumping, no terrified shouting, no fracas at all. I woke up to the scream of sirens speeding up Central Park West, maybe one of the most common sounds in New York City. But that night it was different. The sirens stopped _right downstairs_. That was what caused me to wake up with a hundred-miles-an-hour heartbeat. Was the building on fire? Did some old neighbor have a stroke? I threw off my double layer of blankets, went to my window, and looked down to the street, nine dizzying floors below. I saw three police cruisers and what could have been an unmarked police car parked on Seventy-second Street, right at the front gates of our apartment building, the exclusive and infamous Dakota. A moment later our intercom buzzed, a jarring _blat-blat_ that punched right through my flesh and bones. Why was the doorman paging _us_? This was _crazy_. My bedroom was the one closest to the front door, so I bolted through the living room, hooked a right at the sharks in the aquarium coffee table, and passed between Robert and his nonstop TV. When I reached the foyer, I stabbed at the intercom button to stop the irritating blare before it woke up the whole house. I spoke in a loud whisper to the doorman through the speaker: "Sal? What's happening?" "Miss Tandy? Two policemen are on the way up to your apartment right now. I couldn't stop them. They got a nine-one-one call. It's an emergency. That's what they said." "There's been a mistake, Sal. Everyone is asleep here. It's after midnight. How could you let them up?" Before Sal could answer, the doorbell rang, and then fists pounded the door. A harsh masculine voice called out, "This is the police." I made sure the chain was in place and then opened the door—but just a crack. I peered out through the opening and saw two men in the hallway. The older one was as big as a bear but kind of soft-looking and spongy. The younger one was wiry and had a sharp, expressionless face, something like a hatchet blade, or... no, a hatchet blade is exactly right. The younger one flashed his badge and said, "Sergeant Capricorn Caputo and Detective Ryan Hayes, NYPD. Please open the door." _Capricorn Caputo?_ I thought. _Seriously_? "You've got the wrong apartment," I said. "No one here called the police." "Open the door, miss. And I mean _right now_." "I'll get my parents," I said through the crack. I had no idea that my parents were dead and that we would be the only serious suspects in a double homicide. I was in my last moment of innocence. But who am I kidding? No one in the Angel family was ever innocent. # "Open up, or my partner will kick down the door!" Hatchet Face called out. It is no exaggeration to say that my whole family was about to get a wake-up call from _hell_. But all I was thinking at that particular moment was that the police could _not_ kick down the door. This was the _Dakota_. We could get _evicted_ for allowing someone to disturb the peace. I unlatched the chain and swung the door open. I was wearing pajamas, of course; chick-yellow ones with dinosaurs chasing butterflies. Not exactly what I would have chosen for a meeting with the police. Detective Hayes, the bearish one, said, "What's your name?" "Tandy Angel." "Are you the daughter of Malcolm and Maud Angel?" "I am. Can you please tell me why you're here?" "Tandy is your real name?" he said, ignoring my question. "I'm called Tandy. Please wait here. I'll get my parents to talk to you." "We'll go with you," said Sergeant Caputo. Caputo's grim expression told me that this was not a request. I turned on lights as we headed toward my parents' bedroom suite. I was climbing the circular stairwell, thinking that my parents were going to kill me for bringing these men upstairs, when suddenly both cops pushed rudely past me. By the time I had reached my parents' room, the overhead light was on and the cops were bending over my parents' bed. Even with Caputo and Hayes in the way, I could see that my mother and father looked all wrong. Their sheets and blankets were on the floor, and their nightclothes were bunched under their arms, as if they'd tried to take them off. My father's arm looked like it had been twisted out of its socket. My mother was lying facedown across my father's body, and her tongue was sticking out of her mouth. It had turned _black_. I didn't need a coroner to tell me that they were dead. I knew it just moments after I saw them. Diagnosis certain. I shrieked and ran toward them, but Hayes stopped me cold. He kept me out of the room, putting his big paws on my shoulders and forcibly walking me backward out to the hallway. "I'm sorry to do this," he said, then shut the bedroom door in my face. I didn't try to open it. I just stood there. Motionless. Almost not breathing. So, you might be wondering why I wasn't bawling, screeching, or passing out from shock and horror. Or why I wasn't running to the bathroom to vomit or curling up in the fetal position, hugging my knees and sobbing. Or doing any of the things that a teenage girl who's just seen her murdered parents' bodies ought to do. The answer is complicated, but here's the simplest way to say it: I'm not a whole lot like most girls. At least, not from what I can tell. For me, having a meltdown was seriously out of the question. From the time I was two, when I first started speaking in paragraphs that began with topic sentences, Malcolm and Maud had told me that I was exceptionally smart. Later, they told me that I was analytical and focused, and that my detachment from watery emotion was a superb trait. They said that if I nurtured these qualities, I would achieve or even exceed my extraordinary potential, and this wasn't just a good thing, but a great thing. It was the only thing that mattered, in fact. It was a challenge, and I had accepted it. That's why I was more prepared for this catastrophe than most kids my age would be, or maybe _any_ kids my age. Yes, it was true that panic was shooting up and down my spine and zinging out to my fingertips. I was shocked, maybe even terrified. But I quickly tamped down the screaming voice inside my head and collected my wits, along with the few available facts. One: My parents had died in some unspeakable way. Two: Someone had known about their deaths and called the police. Three: Our doors were locked, and there had been no obvious break-in. Aside from me, my brothers Harry and Hugo and my mother's personal assistant, Samantha, were the only ones home. I went downstairs and got my phone. I called both my uncle Peter and our lawyer, Philippe Montaigne. Then I went to each of my siblings' bedrooms, and to Samantha's, too. And somehow, I told them each the inexpressibly horrible news that our mother and father were dead, and that it was possible they'd been murdered. # Can you imagine the words you'd use, dear reader, to tell your family that your parents had been murdered? I hope so, because I'm not going to be able to share those wretched moments with you right now. We're just getting to know each other, and I take a little bit of time to warm up to people. Can you be patient with me?I promise it'll be worth the wait. After I'd completed that horrible task—perhaps the worst task of my life—I tried to focus my fractured attention back on Sergeant Capricorn Caputo. He was a rough-looking character, like a bad cop in a black- and-white film from the forties who smoked unfiltered cigarettes, had stained fingers, and was coughing up his lungs on his way to the cemetery. Caputo looked to be about thirty-five years old. He had one continuous eyebrow, a furry ledge over his stony black eyes. His thin lips were set in a short, hard line. He had rolled up the sleeves of his shiny blue jacket, and I noted a zodiac sign tattooed on his wrist. He looked like _exactly_ the kind of detective I wanted to have working on the case of my murdered parents. Gnarly and mean. Detective Hayes was an entirely different cat. He had a basically pleasant, faintly lined face and wore a wedding ring, an NYPD Windbreaker, and steel-tipped boots. He looked sympathetic to us kids, sitting in a stunned semicircle around him. But Detective Hayes wasn't in charge, and he wasn't doing the talking. Caputo stood with his back to our massive fireplace and coughed into his fist. Then he looked around the living room with his mouth wide open. He couldn't believe how we lived. And I can't say I blame him. He took in the eight-hundred-gallon aquarium coffee table with the four glowing pygmy sharks swimming circles around their bubbler. His jaw dropped even farther when he saw the life-size merman hanging by its tail from a bloody hook and chain in the ceiling near the staircase. He sent a glance across the white-lacquered grand piano, which we called "Pegasus" because it looked like it had wings. And he stared at Robert, who was slumped in a La-Z-Boy with a can of Bud in one hand and a remote control in the other, just watching the static on his TV screen. Robert is a remarkable creation. He really is. It's next to impossible to tell that he, his La-Z-Boy, and his very own TV are all part of an incredibly lifelike, technologically advanced sculpture. He was cast from a real person, then rendered in polyvinyl and an auto-body filler composite called Bondo. Robert looks so real, you half expect him to crunch his beer can against his forehead and ask for another cold one. "What's the point of this thing?" Detective Caputo asked. "It's an artistic style called hyperrealism," I responded. "Hyper-real, huh?" Detective Caputo said. "Does that mean 'over-the-top'? Because that's kind of a theme in this family, isn't it?" No one answered him. To us, this was home. When Detective Caputo was through taking in the décor, he fixed his eyes on each of us in turn. We just blinked at him. There were no hysterics. In fact, there was no apparent emotion at all. "Your parents were _murdered_ ," he said. "Do you get that? What's the matter? No one here loved them?" We did love them, but it wasn't a simple love. To start with, my parents were complicated: strict, generous, punishing, expansive, withholding. And as a result, we were complicated, too. I knew all of us felt what I was feeling—an internal tsunami of horror and loss and confusion. But we couldn't show it. Not even to save our lives. Of course, Sergeant Caputo didn't see us as bereaved children going through the worst day of our tender young lives. He saw us as _suspects_ , every one of us a "person of interest" in a locked-door double homicide. He didn't try to hide his judgment, and I couldn't fault his reasoning. I thought he was right. My parents' killer was in that room. # My gaze turned to the angry face of my ten-year-old "little" brother, Hugo. From the look of outrage he directed toward the cops, I got the feeling that he felt they were villains, and that he wanted to take Sergeant Caputo apart like a rotisserie chicken. The thing is, Hugo is probably as strong as a full-grown man. I thought he could actually do it. What else could Hugo do? He sat in the "Pork Chair," a pink upholstered armchair with carved wooden pig hooves for feet. He looked adorable, as he almost always did. He was wearing an enormous Giants sweatshirt over his pajamas. Because Goliath was his biblical hero, he allowed a haircut only once a year, so it had been eleven months since Hugo's last trim and his brown hair eddied down his back like a mountain stream. My twin brother, Harrison—aka Harry—sat on the red leather sofa across from Hugo. You would like Harry; everyone does. We're fraternal twins, of course, but we look very much alike, with dark eyes and hair that we got from our mother. I wear my hair below my shoulders, sometimes with a headband. Harry's hair has curls that I would die for. He wears Harry Potter–style dark-rimmed glasses. We both twirl our hair with our fingers when deep in thought. I do it clockwise, and he does it in the other direction. Harry also has a great smile. I guess I do, too, but I almost never use it. Harry uses his a lot. Maybe he's the only Angel who does, actually. That night, Harry wore painter's pants and a sweatshirt with the hood pulled half over his face, which told me that he wanted to disappear. His breathing sounded wheezy, like he had a harmonica in his throat, which meant an asthma attack was coming on. Samantha Peck, my mother's kind and beautiful live-in personal assistant, had spent the night in the apartment, behind our locked doors. She worked for Maud, and that made her a suspect, too. She stood behind Hugo with her hand on his shoulder, her sandy-colored braid cascading over her pink satin robe. Her face was drawn and pale, as if her heart had stopped pumping. I thought she might be in shock. Caputo pointed at Robert's TV, which broadcast static 24/7. He said, "Can someone turn that off?" Hugo said, "We never turn it off. Never." Caputo walked to the wall and pulled the plug. For an instant, the room was completely quiet, as Caputo watched us to see how we would react. I found myself wishing more than anything that my older brother, Matthew, would suddenly appear. I had tried to reach him several times, but he wasn't answering his phone. He may not have been on the best terms with our parents, but I wouldn't be able to entirely focus until he had been informed of their deaths. And Matthew, I was sure, would know how to deal with these police officers. Sergeant Caputo shoved his sleeves up farther on his forearms and said, "The penthouse is a crime scene. It's off-limits until I say otherwise. Are we all clear?" I thought about how my parents would have wanted us to behave in this situation. My mother was like a perpetual-motion machine, never stopping, hardly sleeping at all. She seemed to barely notice people—even her children. Her strength was in analyzing financial markets and managing the billions in her exclusive hedge fund. My father co-owned Angel Pharmaceuticals with his younger brother, Peter. He was a chemist with a gigantic brain and enormous gifts. Unlike my mother, Malcolm engaged with us so intensely that after a few minutes of contact with my father, I felt invaded to the core. Even with all their faults, Malcolm and Maud had had their children's interests at heart. They tirelessly taught us to harness what they called our "superhuman powers": our physical strengths, our emotions, and our remarkable IQs. Our parents wanted us to be perfect. Even in this situation, they would've wanted us to behave perfectly. You can probably imagine that the constant press toward perfection might affect your relationships with others and the expectations you have of yourself. It's like being a camera and the subject of its photographs at the same time. That's screwed up, right? Still, somehow the Angel kids survived this—perhaps by a means that I might describe as... _not entirely natural_. But we'll get to that later. For the moment, I decided to use the skills my parents had driven into all of us, and to refuse to react the way Caputo wanted me to. "Of course, Officer Caputo," I finally responded to his demand. "We wouldn't want to interfere in your very thorough investigation." I would just have to wait until the officers were out of my way. # Confession If only Caputo could interrogate Robert. You see, Robert sees stuff. He _knows_ stuff. About the Angels. About me. Such as: He knows about the time I put my foot right through his TV screen. _On purpose._ Or so I'm told. I don't even remember it. But I know it happened because one day I was the best lacrosse player at All Saints, and the next day I woke up in the hospital with fifty stitches in my foot and leg. In the hospital, Malcolm and Maud's stern faces had looked at me without sympathy. Maud said she never thought lacrosse was good for me, anyway. (I would never play again.) Malcolm announced that my Big Chop was going to be repairing Robert so that he was as good as new. (My efforts were, sadly, flawed; that's why Robert only watches static these days.) And that's pretty much all they'd told me. You don't demand answers from Malcolm and Maud. Hugo was the only one who saw what happened. He said I flew into the apartment in such a rage that he hid behind the Claes Oldenburg sculpture and watched me kick the hell out of Robert, screaming, _"They killed her. They killed her!"_ My foot crashed through Robert's screen with the force of a wrecking ball, he claims. How could I do that? I'd need almost superhuman strength. When I asked Matthew, he shrugged and said only: "It's a piece of art, Tandy. It's not industrial strength." More important, though, was _why_ I would do that. Could I really have been talking about my dead sister, Katherine? Was I accusing Malcolm and Maud of killing their eldest daughter? _And why don't I remember it at all?_ # Caputo was still pacing and coughing, giving us the evil eye and warning us that if we crossed into the no-go zone of the penthouse suite, he would have us removed from the apartment. "I'm doing you a favor, letting you stay downstairs. Don't make me sorry." I stared back at the menacing detective and remembered what it had been like growing up here in the Dakota—a gated island on an island. It was one of the few places in the world where I felt secure. Yet Malcolm and Maud Angel weren't the first people to be killed at the Dakota. Everyone knows that Mark David Chapman gunned John Lennon down right at the front gates, where the police cars were now parked. And just two floors below us, the actor Gig Young killed his wife and then shot himself. Now my parents had been murdered in their own bed by an unknown killer for a reason I couldn't imagine. Or maybe I could... but I digress. Those are very private thoughts, for later. As I sat beside Harry, under the withering gaze of Sergeant Caputo, crime-scene investigators trooped through the private entranceway that very few New Yorkers had ever seen, even in photographs. They crossed the cobbled courtyard and used the residents' elevators to come upstairs, which was strictly forbidden by the cooperative's bylaws. Sergeant Caputo had banned us from our parents' suite—but I _lived_ there. I had rights. And I had already taught myself basic criminology. I learned all about JonBenét Ramsey when I was six, the same age she'd been when she was murdered. She had been an adorable little girl, seemingly happy and unafraid and loving. I was so moved by her death that I wrote to the police in Colorado, asking them why they hadn't found her killer. No one wrote back. To this day, her killer has not been found. The unsolved Ramsey case had inspired me to read up on the famous forensic pathologists Michael Baden and Henry Lee. I had consumed practical guides to homicide investigations, so I knew that the longer it took to solve a crime, the more likely it was that it would never be solved. I wasn't one to trust authority. Who knows, though—maybe Caputo and Hayes _were_ decent cops. But my parents were just a case to them. That was all they could ever be. Malcolm and Maud were my _parents_. I owed them. I owed it to myself, and to my siblings, to try to solve their murders. The fact is, I was the ideal detective for this case. This was a job that I could—and _should_ —do. Please don't think I'm completely full of myself when I say that. I just knew that my doggedness and personal motivation would trump any training these guys had. I am an Angel, after all. As Malcolm always said, we get things done. So as I sat in the living room that night, I took on the full responsibility of finding my parents' killer—even if it turned out that the killer shared my DNA. Even if it turned out to be me. You shouldn't count that out, friend. # Are you familiar with the phrase _unreliable narrator_? Maybe from English-lit class? It's when the storyteller might not be worthy of your trust. In fact, the storyteller might be a complete liar. So given what I just said, you're probably wondering: Is that me? Would I do that to you? Of course I wouldn't. At least, I don't think I would. But you can never tell about people, can you? How much do you really know about my past? That's a subject we'll have to investigate together, later. For now, back to my story. I was about to begin the investigation of my parents' murders. While the two detectives conferred in the study, out of sight, I climbed the stairs to the long hallway in my parents' penthouse suite. I flattened myself against the dark red wall and averted my eyes as the techs from the medical examiner's office took my parents away in body bags. Then I edged down the hall to the threshold of Malcolm and Maud's bedroom and peered inside. An efficient-looking crime-scene investigator was busily dusting for fingerprints. The name tag on her shirt read CSI JOYCE YEAGER. I said hello to the freckle-faced CSI and told her my name. She said that she was sorry for my loss. I nodded, then said, "Do you mind if I ask you some questions?" CSI Yeager looked around before saying, "Okay." I didn't have time for tact. I'd been warned away from this room and everything in it, so I began to shoot questions at the CSI as if I were firing them from a nail gun. "What was the time of death?" "That hasn't been determined," she said. "And the means?" "We don't know yet how your parents were killed." "And what about the manner of death?" I asked. "The medical examiner will determine if these were homicides, accidents, natural deaths—" "Natural?" I interrupted, getting fed up. "Come on." "It's the medical examiner's job to determine these things," she said. "Have you found a weapon? Was there any blood?" "Listen, Tandy. I'm sorry, but you have to go now, before you get me in trouble." CSI Yeager was ignoring me now, but she didn't close the door. I looked around the room, taking in the enormous four-poster bed and the silk bedspread on the floor. And I did a visual inventory of my parents' valuables. The painting over their fireplace, by Daniel Aronstein, was a modern depiction of an American flag: strips of frayed muslin layered with oil paints in greens and mauve. It was worth almost $200,000—and it hadn't been touched. My mother's expensive jewelry was also untouched; her strand of impossibly creamy Mikimoto pearls lay in an open velvet-lined box on the dresser, and her twelve-carat emerald ring still hung from a branch of the crystal ring tree beside her bed. It could not be clearer that there had been no robbery here. It shouldn't surprise me that the evidence pointed to the fact that my parents had been killed out of anger, fear, hatred... Or revenge. # As I stood outside my parents' bedroom a shadow fell across me and I jumped, as if I were already living in fear of the ghosts of Malcolm and Maud. Many ghosts in my family already haunt us, friend, so it helps me to know that you're here. Fortunately, this shadow just belonged to Sergeant Caputo. He pinched my shoulder. Hard. "Let's go, Tansy. I told you, this floor is off-limits. Entering a crime scene before it's cleared is evidence tampering. It's against the law." "Tandy," I said. "Not Tansy. Tandy." I didn't argue his point; he was right. Instead, I went ahead of him down the stairs and back to the living room, arriving just as my big brother, Matthew, stormed in from the kitchen. When Matthew entered a room, he seemed to draw all the light and air to him. He had light brown dreadlocks tied in a bunch with a hank of yarn, and intense blue eyes that shone like high beams. I've never seen eyes like his. No one has. Matty was dressed in jeans and a black T-shirt under a leather jacket, but anyone would've sworn he was wearing a bodysuit with an emblem on the chest and a cape fluttering behind. Hugo broke the spell by leaping out of his chair. "Hup!" he yelled at Matty, jumping toward his brother with outstretched arms. Matthew caught Hugo easily and put a hand to the back of his baby brother's head while fastening his eyes on the two homicide detectives. Matthew is six-two and has biceps the size of thighs. And, well, he can be a little scary when he's mad. _Mad_ wasn't even the word to describe him that night. " _My parents_ were just carried out of the building in the _service_ elevator," he shouted at the cops. "They were _vile_ , but they didn't deserve to be taken out with the _trash_." Detective Hayes said, "And you are...?" "Matthew Angel. Malcolm and Maud's son." "And how did you get into the apartment?" Hayes said. "Cops let me in. One of them wanted my autograph." Caputo said to Matthew, "You won the Heisman, right?" Matthew nodded. In addition to having won the Heisman and being a three-time all-American, Matthew was a poster boy for the NFL and had a fat Nike contract. The sportscaster Aran Delaney had once said of Matthew's blazing speed and agility, "He can run around the block between the time I strike a match and light my cigarette. Matthew Angel is not just a cut above, but an order of _magnitude_ above other outstanding athletes." So it didn't surprise me that Caputo recognized my brother. Matty was sneering, as if the mention of his celebrity was offensive under the circumstances. I kind of had to agree. _Who cares about his stupid Heisman right now?_ Fortunately, Hayes was all business. "Look, Matthew. I'm sorry we had to take your folks out the back way. You wouldn't have wanted them carried around the front so the rubberneckers could gawk and take pictures, would you? Please sit down. We have a few questions." "I'll stand," Matthew said. By that point, Hugo had climbed around Matthew's body and was on his back, looking at the cops over his brother's shoulder. Caputo went right into hostility mode. "Where have you been for the last six hours?" "I stayed with my girlfriend on West Ninth Street. We were together all night, and she'll be happy to tell you that." Matthew's girlfriend was the actress Tamara Gee. She'd received an Academy Award nomination the previous year, when she was twenty-three, and was almost as famous as Matty. I should have realized he would be at her apartment, but I really had no way of contacting him there. I met Tamara the one time Matty brought her home to meet our parents, and while she was certainly pretty in real life, and maybe an order of _magnitude_ above other actors in smarts, I understood easily from her posture and way of speaking that she wanted nothing to do with us. She certainly wasn't passing out her phone number in case I ever needed to call my brother at her apartment. Especially in the dead of night, to inform him that our parents had been murdered. My father, on the other hand, seemed to admire Tamara's obvious distrust of us, and later remarked to me that she was the last piece of the puzzle to make Matthew's future all but certain. You see, he wanted Matty to run for president one day. He was certain Matty would win. Incidentally, Malcolm also thought that Matthew was a sociopath. But, except for Harry, all of us, including my father, had been called sociopaths at some time in our lives. "My siblings will tell you that I haven't set foot in this place, or even seen my parents, for months," Matthew was saying to Detective Hayes. "You have a problem with your parents?" Hayes asked. "I'm twenty-four. I've flown the coop." Matthew didn't even try to disguise the fact that he had no use for Malcolm and Maud. "We'll check out your alibi soon enough," Caputo snapped. "But listen: We all know you could have left your girlfriend in the Village, killed your parents, and gone back to bed before your twinkie even knew you were gone." It was just short of an accusation, obviously meant to provoke a reaction from Matthew. But my big brother didn't bite. Instead, he turned to Hugo and said, "I'm going to tuck you into bed, Buddy." Caputo hadn't gotten anything from Matty, but he'd forced me to face my own suspicions. My brother hated our parents. He was a 215-pound professional football player, a cunning brute. Was he also a killer? # Confession I have pretty bad associations with the Heisman. My therapist, Dr. Keyes, has done a lot to help me forget that night, but every now and then, a memory will pierce my mind's eye. It was after the celebration, after we'd returned to the apartment from dinner at Le Cirque. Malcolm and Matty had both had more than a few drinks at that point, and Malcolm said, "So, let me hold the Angel family Heisman now, son." He latched on to the trophy, like Matty should hand it over. "Remember, you owe everything to us," he went on. "Your speed, your strength, your endurance. Your career. Your money." That did not go over well with Matty. To say the least. "I didn't _ask_ for what you gave me," he said through clenched teeth. He slammed his fist on the glass dining table and I jumped as a crack appeared, sure his hand was going to get sliced to ribbons. Matty was so angry I don't think he would have even noticed. "You created each and every one of us to live out one of your _freakish childhood fantasies_! We're Malcolm's puppets. Maud's baby dolls. Malcolm and Maud's _precious little trophies_." And that's when he hurled the Heisman trophy through the living room window, less than two inches above my head. He could have killed someone walking down below. He could have killed _me_. Would he have regretted it? They didn't call us sociopaths for nothing. # Contents WELCOME DEDICATION TO THE READER PROLOGUE BOOK ONE: BEFORE CHAPTER 1 CHAPTER 2 CHAPTER 3 CHAPTER 4 CHAPTER 5 CHAPTER 6 CHAPTER 7 CHAPTER 8 CHAPTER 9 CHAPTER 10 CHAPTER 11 CHAPTER 12 CHAPTER 13 CHAPTER 14 CHAPTER 15 CHAPTER 16 CHAPTER 17 CHAPTER 18 CHAPTER 19 CHAPTER 20 CHAPTER 21 CHAPTER 22 CHAPTER 23 CHAPTER 24 CHAPTER 25 CHAPTER 26 BOOK TWO: AND SO IT BEGINS CHAPTER 27 CHAPTER 28 CHAPTER 29 CHAPTER 30 CHAPTER 31 CHAPTER 32 CHAPTER 33 CHAPTER 34 CHAPTER 35 CHAPTER 36 CHAPTER 37 CHAPTER 38 CHAPTER 39 CHAPTER 40 CHAPTER 41 CHAPTER 42 CHAPTER 43 CHAPTER 44 CHAPTER 45 CHAPTER 46 CHAPTER 47 CHAPTER 48 CHAPTER 49 CHAPTER 50 CHAPTER 51 BOOK THREE: THE END CHAPTER 52 CHAPTER 53 CHAPTER 54 CHAPTER 55 CHAPTER 56 CHAPTER 57 CHAPTER 58 CHAPTER 59 CHAPTER 60 CHAPTER 61 CHAPTER 62 CHAPTER 63 CHAPTER 64 CHAPTER 65 CHAPTER 66 CHAPTER 67 CHAPTER 68 CHAPTER 69 CHAPTER 70 CHAPTER 71 CHAPTER 72 CHAPTER 73 BOOK FOUR: PARADISE CHAPTER 74 CHAPTER 75 CHAPTER 76 CHAPTER 77 CHAPTER 78 CHAPTER 79 CHAPTER 80 CHAPTER 81 CHAPTER 82 CHAPTER 83 CHAPTER 84 CHAPTER 85 EPILOGUE: MAX'S LAST WORDS EPILOGUE THE LAST: THE BEGINNING A PREVIEW OF _CONFESSIONS OF A MURDER SUSPECT_ COPYRIGHT # Copyright This book is a work of fiction. Names, characters, places, and incidents are the product of the author's imagination or are used fictitiously. Any resemblance to actual events, locales, or persons, living or dead, is coincidental. Copyright © 2012 by James Patterson Excerpt from _Confessions of a Murder Suspect_ © 2012 by James Patterson All rights reserved. In accordance with the U.S. Copyright Act of 1976, the scanning, uploading, and electronic sharing of any part of this book without the permission of the publisher constitute unlawful piracy and theft of the author's intellectual property. If you would like to use material from the book (other than for review purposes), prior written permission must be obtained by contacting the publisher at [email protected]. Thank you for your support of the author's rights. Little, Brown and Company Hachette Book Group 237 Park Avenue, New York, NY 10017 www.hachettebookgroup.com www.twitter.com/littlebrown First e-book edition: August 2012 Little, Brown and Company is a division of Hachette Book Group, Inc. The Little, Brown name and logo are trademarks of Hachette Book Group, Inc. The publisher is not responsible for websites (or their content) that are not owned by the publisher. The Hachette Speakers Bureau provides a wide range of authors for speaking events. To find out more, go to www.hachettespeakersbureau.com or call (866) 376-6591. ISBN 978-0-316-19186-9
<filename>todos/audioFilesWork/concatAudios.py ''' author: @sunil-dhaka todo: use tqdm to show fancy progress bar for file reading and concatening added: automatically convert non-wav files into wav for wave method << done todo: add low quality options for wav conversion in toWAV() ''' from moviepy.editor import concatenate_audioclips, AudioFileClip import wave from pydub import AudioSegment import os,subprocess def toWAV(file): ''' description: convert audio files into '.wav' files using ffmpeg unix utility input: file: input audio file ''' if os.path.splitext(file)[1]!='.wav': base_path='/'.join(os.path.abspath(file).split('/')[:-1]) wav_file=os.path.splitext(file)[0]+'.wav' new_file=os.path.join(base_path,wav_file) # to check whether wav version of mp3 exists or not if not only then convert to wave if not os.path.exists(new_file): subprocess.call(['ffmpeg','-i',file,'-vn', '-acodec','pcm_s16le', '-ac', '1', '-ar','44100', '-f', 'wav',new_file],stdout=subprocess.DEVNULL,stderr=subprocess.STDOUT) print('Converted to wav -- ',wav_file) # rename file to wav version using mv unix command # subprocess.call(['mv',file,new_file],stderr=subprocess.STDOUT,stdout=subprocess.DEVNULL) # print(f'Renamed: {file}\nto ----: {new_file}') def moviepyConcatAudios(inputClips,outClipPath): ''' using moviepy issue: some weird errors with MoviePy when reading some audio files. input: inputClips: input audio files outClipPath: output concated file path ''' print('Using moviepy method.') audioFiles=[] for clip in inputClips: audioFiles.append(AudioFileClip(clip)) concatFile=concatenate_audioclips(audioFiles) concatFile.write_audiofile(outClipPath) print('Concated and saved @', outClipPath) def waveConcatAudios(inputClips,outClipPath): ''' using wav issue: only works with .wav files This method is reliable and much faster. However, the downside is that only the wav extension is supported sol: either convert input files into wav or use pydub method input: inputClips: input audio files outClipPath: output concated file path ''' print('Using wave method.') for clip in inputClips: toWAV(clip) renamedInputClips=[] for clip in inputClips: base_path='/'.join(os.path.abspath(clip).split('/')[:-1]) wav_clip=os.path.splitext(clip)[0]+'.wav' renamed_file=os.path.join(base_path,wav_clip) renamedInputClips.append(renamed_file) audioData=[] for clip in renamedInputClips: tmp_file=wave.open(clip,'rb') audioData.append([tmp_file.getparams(),tmp_file.readframes(tmp_file.getnframes())]) # set params of outfile same as first clip file with wave.open(outClipPath,'wb') as outFile: outFile.setparams(audioData[0][0]) for c in range(len(audioData)): outFile.writeframes(audioData[c][1]) print('Concated and saved @', outClipPath) def pydubConcatAudios(inputClips,outClipPath): ''' using pydub preferred: use this method to combine several audio files into one, as it supports a lot of audio file extensions and does not produce any weird error when loading audio files input: inputClips: input audio files outClipPath: output concated file path ''' print('Using pydub method.') audioData=[] def getFileExt(file): return os.path.splitext(file)[1].lstrip('.') for clip in inputClips: clip_ext=getFileExt(clip) clip_data=AudioSegment.from_file(clip,clip_ext) audioData.append(clip_data) outClip=audioData[0] for c in range(1,len(inputClips)): outClip+=audioData[c] outClipExt=getFileExt(outClipPath) outClip.export(outClipPath,format=outClipExt) print('Concated and saved @', outClipPath) def parser(): myParser=argparse.ArgumentParser(description='script to concat multiple audio files into single file',prog='concatAudios',epilog='Useful script. author: @sunil-dhaka') myParser.add_argument( '-o', '--output', required=True, help='name of the output concat file name/path; include ext of file' ) myParser.add_argument( '-i', '--input', nargs='+', required=True, help='input audio file names/paths' ) myParser.add_argument( '-m', '--method', help='which method to use? moviepy | wave | pydub', default='pydub', type=str ) return myParser.parse_args() if __name__=="__main__": import argparse myParser=parser() methodUsed=myParser.method.lower() if methodUsed.startswith('w'): waveConcatAudios(myParser.input,myParser.output) elif methodUsed.startswith('m'): moviepyConcatAudios(myParser.input,myParser.output) else: pydubConcatAudios(myParser.input,myParser.output)
A 16-year-old science genius believes he may have made a breakthrough in treating an aggressive form of breast cancer. Krtin Nithiyanandam from Epsom has claimed to have found a way to make triple negative breast cancer, a subset of the disease that affects about 7,500 women every year, respond to traditional cancer drugs. From November 2015: International recognition at Google Science Fair for Sutton Grammar schoolboy who developed test for Alzheimer's From February: Sutton Grammar School student Krtin Nithiyanandam's dementia test shortlisted for national science award The subset is diagnosed based on the presence, or lack of oestrogen receptors, progesterone receptors and human epidermal growth factor receptor 2 (HER2), according to the Triple Negative Breast Cancer Foundation. The most successful breast cancer treatments target these receptors, but since none of these receptors are found in women with triple negative breast cancer, the disease is difficult to treat. Krtin believes he may have found a way to change the cancer, so that it responds to drugs. Speaking to the Epsom Guardian after completing his first day of sixth form at Sutton Grammar School (pictured above) on Monday, September 5, he said: “With most types of breast cancer, they have receptors on them, and a lot of drugs intend to treat cancer by blocking those receptors. “Because triple negative breast cancer doesn’t have those receptors, the drugs don’t work. “To attack it, more traditional methods, like chemotherapy, are used.” Krtin believes he has found a way to turn triple negative breast cancer’s characteristic undifferentiated cells – which get stuck in a deadly embryonic form – into their more complete, more treatable form, by blocking a protein called ID4. “I’m not changing the drug. I’m changing the cancer,” he added. Krtin had been working on the therapies at his school’s laboratory in Manor Lane, Sutton. He hopes announcing his breakthrough will garner interest in the wider scientific community and lead to further medical breakthroughs. He said: “I’ve sent it around to a few professors and they seem to have a lot of contacts so it looks promising.” Krtin attracted international recognition last year for devising a test for Alzheimer’s, and gave a TEDx Talk – a series of global conferences on “ideas worth spreading” in technology, entertainment and design – on why students should break into science. At just 16 years of age, he says he is yet to decide which fields he wants to focus on, but is interested in bioplastics and medicine. He said: “At the moment I’m leaning towards the medicine side of things. “I do like the idea of academic medicine. You get to do the research in the labs, but also get clinical practice.” Got a story? Get in touch at [email protected]
// // THIS FILE HAS BEEN GENERATED AUTOMATICALLY // DO NOT CHANGE IT MANUALLY UNLESS YOU KNOW WHAT YOU'RE DOING // // GENERATED USING @colyseus/schema 1.0.28 // import { Schema, type, ArraySchema, MapSchema, SetSchema, DataChange } from '@colyseus/schema'; import { Card } from './Card' import { CardCollection } from './CardCollection' export class ConstellationCardsState extends Schema { @type({ map: Card }) public cards: MapSchema<Card> = new MapSchema<Card>(); @type({ map: CardCollection }) public collections: MapSchema<CardCollection> = new MapSchema<CardCollection>(); }
<gh_stars>0 #!/usr/bin/env python """ A simple tool to select certain parts of the Chinese Treebank. cat `tools/filerange.py 271-300:528-554:594-596:1040-1042 ctb/chtb_*.conll` >ctb/test.conll """ import sys import re RE_NUMBER = re.compile(r'(\d+)') ranges = [xrange(int(s.split("-")[0]), int(s.split("-")[1])+1) for s in sys.argv[1].split(":")] for filename in sys.argv[2:]: m = RE_NUMBER.search(filename) assert m != None x = int(m.group(1)) if any([x in r for r in ranges]): print filename
/// Returns the selection of language(s) (standard and choosen) that a /// specific race is supposed to comprehend. pub fn from_race(race: Race) -> Selections<Language> { let mut s = Selections::new( vec![Language::Common], 0, Language::all()); match race { Race::Aasimar => s.add_forced(Language::Celestial), Race::Bugbear => s.add_forced(Language::Goblin), Race::Dragonborn => s.add_forced(Language::Draconic), Race::Dwarf | Race::HillDwarf | Race::MountainDwarf => s.add_forced(Language::Dwarvish), Race::DuergarDwarf => { s.add_forced(Language::Dwarvish); s.add_forced(Language::Undercommon); }, Race::Elf | Race:: HighElf | Race::WoodElf => s.add_forced(Language::Elvish), Race::DarkElf => { s.add_forced(Language::Elvish); s.add_forced(Language::Undercommon); }, Race::Firbolg => { s.add_forced(Language::Elvish); s.add_forced(Language::Giant); }, Race::Genasi => {}, Race::AirGenasi => s.add_forced(Language::Auran), Race::EarthGenasi => s.add_forced(Language::Terran), Race::FireGenasi => s.add_forced(Language::Ignan), Race::WaterGenasi => s.add_forced(Language::Aquan), Race::Gnome | Race::ForestGnome | Race::RockGnome => s.add_forced(Language::Gnomish), Race::DeepGnome => { s.add_forced(Language::Gnomish); s.add_forced(Language::Undercommon); }, Race::Goblin => s.add_forced(Language::Goblin), Race::Goliath => s.add_forced(Language::Giant), Race::HalfElf => s.add_forced(Language::Elvish), Race::HalfOrc => s.add_forced(Language::Orc), Race::Halfling | Race::GhostwiseHalfling | Race::LightfootHalfling | Race::StoutHalfling => s.add_forced(Language::Halfling), Race::Hobgoblin => s.add_forced(Language::Goblin), Race::Human => {}, Race::Kenku => s.add_forced(Language::Auran), Race::Kobold => s.add_forced(Language::Draconic), Race::Lizardfolk => s.add_forced(Language::Draconic), Race::Orc => s.add_forced(Language::Orc), Race::Tabaxi => {}, Race::Tiefling => s.add_forced(Language::Infernal), Race::Tortle => s.add_forced(Language::Aquan), Race::Triton => s.add_forced(Language::Primordial), Race::YuanTiPureblood => { s.add_forced(Language::Abyssal); s.add_forced(Language::Draconic); } } // Some races have 1 random language choice if race == Race::HalfElf || race == Race::Human || race == Race::Tabaxi { s.nb_choices += 1; } s }
import { prints, printui, print, printString, printArray, printHex, printi, printI128, printU128, printsf, printdf, printqf, printn, Float128, Contract, } from "as-chain"; @contract class MyContract extends Contract{ @action("test") testPrint( a1: Float128 ): void { printqf(a1); } }
// We have "USE local => use" in this module. If attr was added locally // (i.e. on local but not on use), also write it out in the mod file. void ModFileWriter::PutUseExtraAttr( Attr attr, const Symbol &local, const Symbol &use) { if (local.attrs().test(attr) && !use.attrs().test(attr)) { PutLower(useExtraAttrs_, AttrToString(attr)) << "::"; PutLower(useExtraAttrs_, local) << '\n'; } }
<reponame>eashman/kittentest<filename>src/components/menu/index.ts export { LayoutsList, LayoutsListProps, LayoutsListItemData, } from './layoutsList'; export { ComponentsList, ComponentsListProps, ComponentsListItemData, } from './componentsList';
<reponame>danbirle/ionic-cli describe('@ionic/utils-process', () => { describe('createProcessEnv', () => { describe('non-windows', () => { const mock_terminal = { TERMINAL_INFO: { windows: false } }; jest.resetModules(); jest.mock('@ionic/utils-terminal', () => mock_terminal); const proc = require('../'); it('should be case sensitive', () => { const o = proc.createProcessEnv(); o['asdf'] = 'val1'; o['ASDF'] = 'val2'; expect(o).toEqual({ 'asdf': 'val1', 'ASDF': 'val2' }); }); it('should use sources and be case sensitive', () => { const o = proc.createProcessEnv({ 'hello': 'you' }, { 'hello': 'world' }); o['asdf'] = 'val1'; o['ASDF'] = 'val2'; expect(o['hello']).toEqual('world'); expect(o).toEqual({ 'asdf': 'val1', 'ASDF': 'val2', 'hello': 'world' }); }); }); describe('windows', () => { const mock_terminal = { TERMINAL_INFO: { windows: true } }; jest.resetModules(); jest.mock('@ionic/utils-terminal', () => mock_terminal); const proc = require('../'); it('should be case insensitive', () => { const o = proc.createProcessEnv(); o['asdf'] = 'val1'; o['ASDF'] = 'val2'; expect(o).toEqual({ 'asdf': 'val2' }); }); it('should use sources and be case insensitive', () => { const o = proc.createProcessEnv({ 'HELLO': 'YOU' }, { 'hello': 'world' }); o['asdf'] = 'val1'; o['ASDF'] = 'val2'; expect(o['hello']).toEqual('world'); expect(o).toEqual({ 'asdf': 'val2', 'hello': 'world' }); }); }); }); });
<reponame>ozanh/yaegi package interp import ( "fmt" "go/ast" "go/parser" "go/scanner" "go/token" "reflect" "strconv" "sync/atomic" ) // nkind defines the kind of AST, i.e. the grammar category type nkind uint // Node kinds for the go language const ( undefNode nkind = iota addressExpr arrayType assignStmt assignXStmt basicLit binaryExpr blockStmt branchStmt breakStmt callExpr caseBody caseClause chanType commClause compositeLitExpr constDecl continueStmt declStmt deferStmt defineStmt defineXStmt ellipsisExpr exprStmt fallthroughtStmt fieldExpr fieldList fileStmt forStmt0 // for {} forStmt1 // for cond {} forStmt2 // for init; cond; {} forStmt3 // for ; cond; post {} forStmt3a // for init; ; post {} forStmt4 // for init; cond; post {} forRangeStmt // for range funcDecl funcLit funcType goStmt gotoStmt identExpr ifStmt0 // if cond {} ifStmt1 // if cond {} else {} ifStmt2 // if init; cond {} ifStmt3 // if init; cond {} else {} importDecl importSpec incDecStmt indexExpr interfaceType keyValueExpr labeledStmt landExpr lorExpr mapType parenExpr rangeStmt returnStmt selectStmt selectorExpr selectorImport sendStmt sliceExpr starExpr structType switchStmt switchIfStmt typeAssertExpr typeDecl typeSpec typeSwitch unaryExpr valueSpec varDecl ) var kinds = [...]string{ undefNode: "undefNode", addressExpr: "addressExpr", arrayType: "arrayType", assignStmt: "assignStmt", assignXStmt: "assignXStmt", basicLit: "basicLit", binaryExpr: "binaryExpr", blockStmt: "blockStmt", branchStmt: "branchStmt", breakStmt: "breakStmt", callExpr: "callExpr", caseBody: "caseBody", caseClause: "caseClause", chanType: "chanType", commClause: "commClause", compositeLitExpr: "compositeLitExpr", constDecl: "constDecl", continueStmt: "continueStmt", declStmt: "declStmt", deferStmt: "deferStmt", defineStmt: "defineStmt", defineXStmt: "defineXStmt", ellipsisExpr: "ellipsisExpr", exprStmt: "exprStmt", fallthroughtStmt: "fallthroughStmt", fieldExpr: "fieldExpr", fieldList: "fieldList", fileStmt: "fileStmt", forStmt0: "forStmt0", forStmt1: "forStmt1", forStmt2: "forStmt2", forStmt3: "forStmt3", forStmt3a: "forStmt3a", forStmt4: "forStmt4", forRangeStmt: "forRangeStmt", funcDecl: "funcDecl", funcType: "funcType", funcLit: "funcLit", goStmt: "goStmt", gotoStmt: "gotoStmt", identExpr: "identExpr", ifStmt0: "ifStmt0", ifStmt1: "ifStmt1", ifStmt2: "ifStmt2", ifStmt3: "ifStmt3", importDecl: "importDecl", importSpec: "importSpec", incDecStmt: "incDecStmt", indexExpr: "indexExpr", interfaceType: "interfaceType", keyValueExpr: "keyValueExpr", labeledStmt: "labeledStmt", landExpr: "landExpr", lorExpr: "lorExpr", mapType: "mapType", parenExpr: "parenExpr", rangeStmt: "rangeStmt", returnStmt: "returnStmt", selectStmt: "selectStmt", selectorExpr: "selectorExpr", selectorImport: "selectorImport", sendStmt: "sendStmt", sliceExpr: "sliceExpr", starExpr: "starExpr", structType: "structType", switchStmt: "switchStmt", switchIfStmt: "switchIfStmt", typeAssertExpr: "typeAssertExpr", typeDecl: "typeDecl", typeSpec: "typeSpec", typeSwitch: "typeSwitch", unaryExpr: "unaryExpr", valueSpec: "valueSpec", varDecl: "varDecl", } func (k nkind) String() string { if k < nkind(len(kinds)) { return kinds[k] } return "nKind(" + strconv.Itoa(int(k)) + ")" } // astError represents an error during AST build stage type astError error // action defines the node action to perform at execution type action uint // Node actions for the go language const ( aNop action = iota aAddr aAssign aAssignX aAdd aAddAssign aAnd aAndAssign aAndNot aAndNotAssign aBitNot aBranch aCall aCase aCompositeLit aConvert aDec aEqual aGreater aGreaterEqual aGetFunc aGetIndex aGetSym aInc aLand aLor aLower aLowerEqual aMethod aMul aMulAssign aNeg aNot aNotEqual aOr aOrAssign aPos aQuo aQuoAssign aRange aRecv aRem aRemAssign aReturn aSend aShl aShlAssign aShr aShrAssign aSlice aSlice0 aStar aSub aSubAssign aTypeAssert aXor aXorAssign ) var actions = [...]string{ aNop: "nop", aAddr: "&", aAssign: "=", aAssignX: "X=", aAdd: "+", aAddAssign: "+=", aAnd: "&", aAndAssign: "&=", aAndNot: "&^", aAndNotAssign: "&^=", aBitNot: "^", aBranch: "branch", aCall: "call", aCase: "case", aCompositeLit: "compositeLit", aConvert: "convert", aDec: "--", aEqual: "==", aGreater: ">", aGetFunc: "getFunc", aGetIndex: "getIndex", aGetSym: ".", aInc: "++", aLand: "&&", aLor: "||", aLower: "<", aMethod: "Method", aMul: "*", aMulAssign: "*=", aNeg: "-", aNot: "!", aNotEqual: "!=", aOr: "|", aOrAssign: "|=", aPos: "+", aQuo: "/", aQuoAssign: "/=", aRange: "range", aRecv: "<-", aRem: "%", aRemAssign: "%=", aReturn: "return", aSend: "<~", aShl: "<<", aShlAssign: "<<=", aShr: ">>", aShrAssign: ">>=", aSlice: "slice", aSlice0: "slice0", aStar: "*", aSub: "-", aSubAssign: "-=", aTypeAssert: "TypeAssert", aXor: "^", aXorAssign: "^=", } func (a action) String() string { if a < action(len(actions)) { return actions[a] } return "Action(" + strconv.Itoa(int(a)) + ")" } func (interp *Interpreter) firstToken(src string) token.Token { var s scanner.Scanner file := interp.fset.AddFile("", interp.fset.Base(), len(src)) s.Init(file, []byte(src), nil, 0) _, tok, _ := s.Scan() return tok } // Note: no type analysis is performed at this stage, it is done in pre-order // processing of CFG, in order to accommodate forward type declarations // ast parses src string containing Go code and generates the corresponding AST. // The package name and the AST root node are returned. func (interp *Interpreter) ast(src, name string) (string, *node, error) { inRepl := name == "" var inFunc bool var mode parser.Mode // Allow incremental parsing of declarations or statements, by inserting // them in a pseudo file package or function. Those statements or // declarations will be always evaluated in the global scope if inRepl { switch interp.firstToken(src) { case token.PACKAGE: // nothing to do case token.CONST, token.FUNC, token.IMPORT, token.TYPE, token.VAR: src = "package main;" + src default: inFunc = true src = "package main; func main() {" + src + "}" } // Parse comments in REPL mode, to allow tag setting mode |= parser.ParseComments } if ok, err := interp.buildOk(&interp.context, name, src); !ok || err != nil { return "", nil, err // skip source not matching build constraints } f, err := parser.ParseFile(interp.fset, name, src, mode) if err != nil { return "", nil, err } setYaegiTags(&interp.context, f.Comments) var root *node var anc astNode var st nodestack var pkgName string addChild := func(root **node, anc astNode, pos token.Pos, kind nkind, act action) *node { var i interface{} nindex := atomic.AddInt64(&interp.nindex, 1) n := &node{anc: anc.node, interp: interp, index: nindex, pos: pos, kind: kind, action: act, val: &i, gen: builtin[act]} n.start = n if anc.node == nil { *root = n } else { anc.node.child = append(anc.node.child, n) if anc.node.action == aCase { ancAst := anc.ast.(*ast.CaseClause) if len(ancAst.List)+len(ancAst.Body) == len(anc.node.child) { // All case clause children are collected. // Split children in condition and body nodes to desambiguify the AST. nindex = atomic.AddInt64(&interp.nindex, 1) body := &node{anc: anc.node, interp: interp, index: nindex, pos: pos, kind: caseBody, action: aNop, val: &i, gen: nop} if ts := anc.node.anc.anc; ts.kind == typeSwitch && ts.child[1].action == aAssign { // In type switch clause, if a switch guard is assigned, duplicate the switch guard symbol // in each clause body, so a different guard type can be set in each clause name := ts.child[1].child[0].ident nindex = atomic.AddInt64(&interp.nindex, 1) gn := &node{anc: body, interp: interp, ident: name, index: nindex, pos: pos, kind: identExpr, action: aNop, val: &i, gen: nop} body.child = append(body.child, gn) } // Add regular body children body.child = append(body.child, anc.node.child[len(ancAst.List):]...) for i := range body.child { body.child[i].anc = body } anc.node.child = append(anc.node.child[:len(ancAst.List)], body) } } } return n } // Populate our own private AST from Go parser AST. // A stack of ancestor nodes is used to keep track of current ancestor for each depth level ast.Inspect(f, func(nod ast.Node) bool { anc = st.top() var pos token.Pos if nod != nil { pos = nod.Pos() } switch a := nod.(type) { case nil: anc = st.pop() case *ast.ArrayType: st.push(addChild(&root, anc, pos, arrayType, aNop), nod) case *ast.AssignStmt: var act action var kind nkind if len(a.Lhs) > 1 && len(a.Rhs) == 1 { if a.Tok == token.DEFINE { kind = defineXStmt } else { kind = assignXStmt } act = aAssignX } else { kind = assignStmt switch a.Tok { case token.ASSIGN: act = aAssign case token.ADD_ASSIGN: act = aAddAssign case token.AND_ASSIGN: act = aAndAssign case token.AND_NOT_ASSIGN: act = aAndNotAssign case token.DEFINE: kind = defineStmt act = aAssign case token.SHL_ASSIGN: act = aShlAssign case token.SHR_ASSIGN: act = aShrAssign case token.MUL_ASSIGN: act = aMulAssign case token.OR_ASSIGN: act = aOrAssign case token.QUO_ASSIGN: act = aQuoAssign case token.REM_ASSIGN: act = aRemAssign case token.SUB_ASSIGN: act = aSubAssign case token.XOR_ASSIGN: act = aXorAssign } } n := addChild(&root, anc, pos, kind, act) n.nleft = len(a.Lhs) n.nright = len(a.Rhs) st.push(n, nod) case *ast.BasicLit: n := addChild(&root, anc, pos, basicLit, aNop) n.ident = a.Value switch a.Kind { case token.CHAR: v, _, _, _ := strconv.UnquoteChar(a.Value[1:len(a.Value)-1], '\'') n.rval = reflect.ValueOf(v) case token.FLOAT: v, _ := strconv.ParseFloat(a.Value, 64) n.rval = reflect.ValueOf(v) case token.IMAG: v, _ := strconv.ParseFloat(a.Value[:len(a.Value)-1], 64) n.rval = reflect.ValueOf(complex(0, v)) case token.INT: v, _ := strconv.ParseInt(a.Value, 0, 0) n.rval = reflect.ValueOf(int(v)) case token.STRING: v, _ := strconv.Unquote(a.Value) n.rval = reflect.ValueOf(v) } st.push(n, nod) case *ast.BinaryExpr: kind := binaryExpr act := aNop switch a.Op { case token.ADD: act = aAdd case token.AND: act = aAnd case token.AND_NOT: act = aAndNot case token.EQL: act = aEqual case token.GEQ: act = aGreaterEqual case token.GTR: act = aGreater case token.LAND: kind = landExpr act = aLand case token.LOR: kind = lorExpr act = aLor case token.LEQ: act = aLowerEqual case token.LSS: act = aLower case token.MUL: act = aMul case token.NEQ: act = aNotEqual case token.OR: act = aOr case token.REM: act = aRem case token.SUB: act = aSub case token.SHL: act = aShl case token.SHR: act = aShr case token.QUO: act = aQuo case token.XOR: act = aXor } st.push(addChild(&root, anc, pos, kind, act), nod) case *ast.BlockStmt: st.push(addChild(&root, anc, pos, blockStmt, aNop), nod) case *ast.BranchStmt: var kind nkind switch a.Tok { case token.BREAK: kind = breakStmt case token.CONTINUE: kind = continueStmt case token.FALLTHROUGH: kind = fallthroughtStmt case token.GOTO: kind = gotoStmt } st.push(addChild(&root, anc, pos, kind, aNop), nod) case *ast.CallExpr: st.push(addChild(&root, anc, pos, callExpr, aCall), nod) case *ast.CaseClause: st.push(addChild(&root, anc, pos, caseClause, aCase), nod) case *ast.ChanType: st.push(addChild(&root, anc, pos, chanType, aNop), nod) case *ast.CommClause: st.push(addChild(&root, anc, pos, commClause, aNop), nod) case *ast.CommentGroup: return false case *ast.CompositeLit: st.push(addChild(&root, anc, pos, compositeLitExpr, aCompositeLit), nod) case *ast.DeclStmt: st.push(addChild(&root, anc, pos, declStmt, aNop), nod) case *ast.DeferStmt: st.push(addChild(&root, anc, pos, deferStmt, aNop), nod) case *ast.Ellipsis: st.push(addChild(&root, anc, pos, ellipsisExpr, aNop), nod) case *ast.ExprStmt: st.push(addChild(&root, anc, pos, exprStmt, aNop), nod) case *ast.Field: st.push(addChild(&root, anc, pos, fieldExpr, aNop), nod) case *ast.FieldList: st.push(addChild(&root, anc, pos, fieldList, aNop), nod) case *ast.File: pkgName = a.Name.Name st.push(addChild(&root, anc, pos, fileStmt, aNop), nod) case *ast.ForStmt: // Disambiguate variants of FOR statements with a node kind per variant var kind nkind if a.Cond == nil { if a.Init != nil && a.Post != nil { kind = forStmt3a } else { kind = forStmt0 } } else { switch { case a.Init == nil && a.Post == nil: kind = forStmt1 case a.Init != nil && a.Post == nil: kind = forStmt2 case a.Init == nil && a.Post != nil: kind = forStmt3 default: kind = forStmt4 } } st.push(addChild(&root, anc, pos, kind, aNop), nod) case *ast.FuncDecl: n := addChild(&root, anc, pos, funcDecl, aNop) if a.Recv == nil { // function is not a method, create an empty receiver list addChild(&root, astNode{n, nod}, pos, fieldList, aNop) } st.push(n, nod) case *ast.FuncLit: n := addChild(&root, anc, pos, funcLit, aGetFunc) addChild(&root, astNode{n, nod}, pos, fieldList, aNop) addChild(&root, astNode{n, nod}, pos, undefNode, aNop) st.push(n, nod) case *ast.FuncType: st.push(addChild(&root, anc, pos, funcType, aNop), nod) case *ast.GenDecl: var kind nkind switch a.Tok { case token.CONST: kind = constDecl case token.IMPORT: kind = importDecl case token.TYPE: kind = typeDecl case token.VAR: kind = varDecl } st.push(addChild(&root, anc, pos, kind, aNop), nod) case *ast.GoStmt: st.push(addChild(&root, anc, pos, goStmt, aNop), nod) case *ast.Ident: n := addChild(&root, anc, pos, identExpr, aNop) n.ident = a.Name st.push(n, nod) if n.anc.kind == defineStmt && n.anc.nright == 0 { // Implicit assign expression (in a ConstDecl block). // Clone assign source and type from previous a := n.anc pa := a.anc.child[childPos(a)-1] if len(pa.child) > pa.nleft+pa.nright { // duplicate previous type spec a.child = append(a.child, interp.dup(pa.child[a.nleft], a)) } // duplicate previous assign right hand side a.child = append(a.child, interp.dup(pa.lastChild(), a)) a.nright++ } case *ast.IfStmt: // Disambiguate variants of IF statements with a node kind per variant var kind nkind switch { case a.Init == nil && a.Else == nil: kind = ifStmt0 case a.Init == nil && a.Else != nil: kind = ifStmt1 case a.Else == nil: kind = ifStmt2 default: kind = ifStmt3 } st.push(addChild(&root, anc, pos, kind, aNop), nod) case *ast.ImportSpec: st.push(addChild(&root, anc, pos, importSpec, aNop), nod) case *ast.IncDecStmt: var act action switch a.Tok { case token.INC: act = aInc case token.DEC: act = aDec } st.push(addChild(&root, anc, pos, incDecStmt, act), nod) case *ast.IndexExpr: st.push(addChild(&root, anc, pos, indexExpr, aGetIndex), nod) case *ast.InterfaceType: st.push(addChild(&root, anc, pos, interfaceType, aNop), nod) case *ast.KeyValueExpr: st.push(addChild(&root, anc, pos, keyValueExpr, aNop), nod) case *ast.LabeledStmt: st.push(addChild(&root, anc, pos, labeledStmt, aNop), nod) case *ast.MapType: st.push(addChild(&root, anc, pos, mapType, aNop), nod) case *ast.ParenExpr: st.push(addChild(&root, anc, pos, parenExpr, aNop), nod) case *ast.RangeStmt: // Insert a missing ForRangeStmt for AST correctness n := addChild(&root, anc, pos, forRangeStmt, aNop) r := addChild(&root, astNode{n, nod}, pos, rangeStmt, aRange) st.push(r, nod) if a.Key == nil { // range not in an assign expression: insert a "_" key variable to store iteration index k := addChild(&root, astNode{r, nod}, pos, identExpr, aNop) k.ident = "_" } case *ast.ReturnStmt: st.push(addChild(&root, anc, pos, returnStmt, aReturn), nod) case *ast.SelectStmt: st.push(addChild(&root, anc, pos, selectStmt, aNop), nod) case *ast.SelectorExpr: st.push(addChild(&root, anc, pos, selectorExpr, aGetIndex), nod) case *ast.SendStmt: st.push(addChild(&root, anc, pos, sendStmt, aSend), nod) case *ast.SliceExpr: if a.Low == nil { st.push(addChild(&root, anc, pos, sliceExpr, aSlice0), nod) } else { st.push(addChild(&root, anc, pos, sliceExpr, aSlice), nod) } case *ast.StarExpr: st.push(addChild(&root, anc, pos, starExpr, aStar), nod) case *ast.StructType: st.push(addChild(&root, anc, pos, structType, aNop), nod) case *ast.SwitchStmt: if a.Tag == nil { st.push(addChild(&root, anc, pos, switchIfStmt, aNop), nod) } else { st.push(addChild(&root, anc, pos, switchStmt, aNop), nod) } case *ast.TypeAssertExpr: st.push(addChild(&root, anc, pos, typeAssertExpr, aTypeAssert), nod) case *ast.TypeSpec: st.push(addChild(&root, anc, pos, typeSpec, aNop), nod) case *ast.TypeSwitchStmt: n := addChild(&root, anc, pos, typeSwitch, aNop) st.push(n, nod) if a.Init == nil { // add an empty init node to disambiguate AST addChild(&root, astNode{n, nil}, pos, fieldList, aNop) } case *ast.UnaryExpr: var kind = unaryExpr var act action switch a.Op { case token.ADD: act = aPos case token.AND: kind = addressExpr act = aAddr case token.ARROW: act = aRecv case token.NOT: act = aNot case token.SUB: act = aNeg case token.XOR: act = aBitNot } st.push(addChild(&root, anc, pos, kind, act), nod) case *ast.ValueSpec: kind := valueSpec act := aNop if a.Values != nil { if len(a.Names) > 1 && len(a.Values) == 1 { if anc.node.kind == constDecl || anc.node.kind == varDecl { kind = defineXStmt } else { kind = assignXStmt } act = aAssignX } else { if anc.node.kind == constDecl || anc.node.kind == varDecl { kind = defineStmt } else { kind = assignStmt } act = aAssign } } else if anc.node.kind == constDecl { kind, act = defineStmt, aAssign } n := addChild(&root, anc, pos, kind, act) n.nleft = len(a.Names) n.nright = len(a.Values) st.push(n, nod) default: err = astError(fmt.Errorf("ast: %T not implemented, line %s", a, interp.fset.Position(pos))) return false } return true }) if inFunc { // Incremental parsing: statements were inserted in a pseudo function. // Set root to function body so its statements are evaluated in global scope root = root.child[1].child[3] root.anc = nil } return pkgName, root, err } type astNode struct { node *node ast ast.Node } type nodestack []astNode func (s *nodestack) push(n *node, a ast.Node) { *s = append(*s, astNode{n, a}) } func (s *nodestack) pop() astNode { l := len(*s) - 1 res := (*s)[l] *s = (*s)[:l] return res } func (s *nodestack) top() astNode { l := len(*s) if l > 0 { return (*s)[l-1] } return astNode{} } // dup returns a duplicated node subtree func (interp *Interpreter) dup(nod, anc *node) *node { nindex := atomic.AddInt64(&interp.nindex, 1) n := *nod n.index = nindex n.anc = anc n.start = &n n.pos = anc.pos n.child = nil for _, c := range nod.child { n.child = append(n.child, interp.dup(c, &n)) } return &n }
[Haskell-cafe] Haskell opportunity at investment bank Hello, I'm looking for a developer with expertise in Haskell for an investment bank in London. The role will involve working on a multi-asset, multi-region, pricing, risk and trade lifecycle solution for the wholesale banking division. Solutions are developed using Java, C#/WPF, C++ and make heavy use of Haskell. The requirement is for an experienced developer with in-depth knowledge of functional programming in Haskell - ideally in a commercial environment. If interested, please feel free to send your CV through or call me to discuss. Thanks, Chris Pearse 0207 469 5050 http://www.linkedin.com/pub/3/9a1/142 ------------------------------------------------------------------------------- Huxley Associates - Professional Recruitment Solutions Established in 1995, Huxley Associates is an international recruitment consultancy. We provide bespoke recruitment services to the Accountancy & Finance, Banking Technology, Energy, Engineering, Global Markets, Human Resources, IT, Oil & Gas, Sales & Marketing, and Supply Chain sectors. With over 400 specialist recruitment professionals, we are consistently able to meet the high recruitment needs of a diverse range of companies across the UK, Europe, Asia and the United States. This email message may contain confidential and/or privileged information, and is intended solely for the addressee(s). If you have received this email in error, please notify Huxley Associates immediately. Unauthorised copying, disclosure or distribution of the material in this email is forbidden. If you do not want to receive emails from us about our services in future, or if you want to query or qualify how your personal data is held by us (for details on this see our privacy statement http://www.huxley.co.uk/privacy_policy.html ) please e-mail audit.data at huxley.com. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20100604/5622ae70/attachment.html
<filename>src/testing/servermanager.py import subprocess import time import requests import requests.exceptions class ServerManager: #################################################################################################################### # Constructor. #################################################################################################################### def __init__(self, executable_path, config_path): ### Attributes from outside. self._executable_path = executable_path self._config_path = config_path ### Private attributes. self._current_process = None #################################################################################################################### # Public methods. #################################################################################################################### def start(self): self._current_process = subprocess.Popen( ['pipenv', 'run', 'python', self._executable_path, '-c', self._config_path], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) def stop(self): if self._current_process is not None: self._current_process.terminate() self._current_process.wait() self._current_process = None def wait_for_initialization(self, base_url): for _ in range(0, 10): time.sleep(1) try: response = requests.get(base_url) if response.status_code == 200: return True except requests.exceptions.ConnectionError: pass return False
/** * Stop Service * Clears and removes auth listener * Should be called in Activities onStop() method */ @Override public void stop() { if (mAuthListener != null) { mAuth.removeAuthStateListener(mAuthListener); } }
<filename>src/actions/list/delete-list.action.ts import "source-map-support/register"; import ResponseModel from "../../models/response.model"; import DatabaseService, { DeleteItem, QueryItem, } from "../../services/database.service"; import { createChunks, databaseTables, validateRequest, } from "../../utils/util"; import requestConstraints from "../../constraints/list/get.constraint.json"; import { QueryParams, wrapAsRequest } from "../../utils/lambda-handler"; import { StatusCode } from "../../enums/status-code.enum"; import { ResponseMessage } from "../../enums/response-message.enum"; const deleteListHandler = async ( _body: never, queryParams: QueryParams ): Promise<ResponseModel> => { const { listTable, tasksTable } = databaseTables(); const databaseService = new DatabaseService(); try { await validateRequest(queryParams, requestConstraints); const { listId } = queryParams; // check item exists const existsItem = await databaseService.existsItem({ key: listId!, tableName: listTable, }); if (!existsItem) { return new ResponseModel( {}, StatusCode.NO_CONTENT, ResponseMessage.DELETE_LIST_NOTFOUND ); } const params: DeleteItem = { TableName: listTable, Key: { id: listId }, }; await databaseService.delete(params); // Delete to-do list const taskParams: QueryItem = { TableName: tasksTable, IndexName: "list_index", KeyConditionExpression: "listId = :listIdVal", ExpressionAttributeValues: { ":listIdVal": listId, }, }; const results = await databaseService.query(taskParams); if (results?.Items && results?.Items.length) { const taskEntities = results?.Items?.map((item) => { return { DeleteRequest: { Key: { id: item.id } } }; }); if (taskEntities.length > 25) { const taskChunks = createChunks(taskEntities, 25); await Promise.all( taskChunks.map((tasks) => { return databaseService.batchCreate({ RequestItems: { [tasksTable]: tasks, }, }); }) ); } else { await databaseService.batchCreate({ RequestItems: { [tasksTable]: taskEntities, }, }); } } return new ResponseModel( {}, StatusCode.NO_CONTENT, ResponseMessage.DELETE_LIST_SUCCESS ); } catch (error) { return error instanceof ResponseModel ? error : new ResponseModel( {}, StatusCode.ERROR, ResponseMessage.DELETE_LIST_FAIL ); } }; export const deleteList = wrapAsRequest(deleteListHandler);
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.apache.hadoop.mapred; import java.io.*; import java.util.*; import junit.framework.TestCase; import org.apache.commons.logging.*; import org.apache.hadoop.fs.*; import org.apache.hadoop.io.*; import org.apache.hadoop.conf.*; public class TestSequenceFileInputFilter extends TestCase { private static final Log LOG = FileInputFormat.LOG; private static final int MAX_LENGTH = 15000; private static final Configuration conf = new Configuration(); private static final JobConf job = new JobConf(conf); private static final FileSystem fs; private static final Path inDir = new Path(System.getProperty("test.build.data",".") + "/mapred"); private static final Path inFile = new Path(inDir, "test.seq"); private static final Random random = new Random(1); private static final Reporter reporter = Reporter.NULL; static { FileInputFormat.setInputPaths(job, inDir); try { fs = FileSystem.getLocal(conf); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); } } private static void createSequenceFile(int numRecords) throws Exception { // create a file with length entries SequenceFile.Writer writer = SequenceFile.createWriter(fs, conf, inFile, Text.class, BytesWritable.class); try { for (int i = 1; i <= numRecords; i++) { Text key = new Text(Integer.toString(i)); byte[] data = new byte[random.nextInt(10)]; random.nextBytes(data); BytesWritable value = new BytesWritable(data); writer.append(key, value); } } finally { writer.close(); } } private int countRecords(int numSplits) throws IOException { InputFormat<Text, BytesWritable> format = new SequenceFileInputFilter<Text, BytesWritable>(); Text key = new Text(); BytesWritable value = new BytesWritable(); if (numSplits==0) { numSplits = random.nextInt(MAX_LENGTH/(SequenceFile.SYNC_INTERVAL/20))+1; } InputSplit[] splits = format.getSplits(job, numSplits); // check each split int count = 0; LOG.info("Generated " + splits.length + " splits."); for (int j = 0; j < splits.length; j++) { RecordReader<Text, BytesWritable> reader = format.getRecordReader(splits[j], job, reporter); try { while (reader.next(key, value)) { LOG.info("Accept record "+key.toString()); count++; } } finally { reader.close(); } } return count; } public void testRegexFilter() throws Exception { // set the filter class LOG.info("Testing Regex Filter with patter: \\A10*"); SequenceFileInputFilter.setFilterClass(job, SequenceFileInputFilter.RegexFilter.class); SequenceFileInputFilter.RegexFilter.setPattern(job, "\\A10*"); // clean input dir fs.delete(inDir, true); // for a variety of lengths for (int length = 1; length < MAX_LENGTH; length+= random.nextInt(MAX_LENGTH/10)+1) { LOG.info("******Number of records: "+length); createSequenceFile(length); int count = countRecords(0); assertEquals(count, length==0?0:(int)Math.log10(length)+1); } // clean up fs.delete(inDir, true); } public void testPercentFilter() throws Exception { LOG.info("Testing Percent Filter with frequency: 1000"); // set the filter class SequenceFileInputFilter.setFilterClass(job, SequenceFileInputFilter.PercentFilter.class); SequenceFileInputFilter.PercentFilter.setFrequency(job, 1000); // clean input dir fs.delete(inDir, true); // for a variety of lengths for (int length = 0; length < MAX_LENGTH; length+= random.nextInt(MAX_LENGTH/10)+1) { LOG.info("******Number of records: "+length); createSequenceFile(length); int count = countRecords(1); LOG.info("Accepted "+count+" records"); int expectedCount = length/1000; if (expectedCount*1000!=length) expectedCount++; assertEquals(count, expectedCount); } // clean up fs.delete(inDir, true); } public void testMD5Filter() throws Exception { // set the filter class LOG.info("Testing MD5 Filter with frequency: 1000"); SequenceFileInputFilter.setFilterClass(job, SequenceFileInputFilter.MD5Filter.class); SequenceFileInputFilter.MD5Filter.setFrequency(job, 1000); // clean input dir fs.delete(inDir, true); // for a variety of lengths for (int length = 0; length < MAX_LENGTH; length+= random.nextInt(MAX_LENGTH/10)+1) { LOG.info("******Number of records: "+length); createSequenceFile(length); LOG.info("Accepted "+countRecords(0)+" records"); } // clean up fs.delete(inDir, true); } public static void main(String[] args) throws Exception { TestSequenceFileInputFilter filter = new TestSequenceFileInputFilter(); filter.testRegexFilter(); } }
/// Returns a reference to the slot at the given SlotIndex /// if such a slot exists. Otherwise, an error is returned. pub fn slot(&self, index: &SlotIndex) -> Result<&Option<u32>, Error> { self.items .get(index) .map(|i| Ok(i)) .unwrap_or_else(|| Err(Error::InvalidSlotIndex)) }
/** * A listener that will subscribe to test execution and dump * informational info about the progress to the console or a text * file. */ @SuppressWarnings("resource") public class TextReport implements AggregatedEventListener { /* * Indents for outputs. */ private static final String indent = " > "; private static final String stdoutIndent = " 1> "; private static final String stderrIndent = " 2> "; /** * Failure marker string. */ private static final String FAILURE_MARKER = " <<<"; private static final String FAILURE_STRING = FAILURE_MARKER + " FAILURES!"; /** * Default 16kb for maximum line width buffer. Otherwise we may get OOMs buffering * each line. */ private static final int DEFAULT_MAX_LINE_WIDTH = 1024 * 16; /** * Code pages which are capable of displaying all unicode glyphs. */ private static Set<String> UNICODE_ENCODINGS = new HashSet<String>(Arrays.asList( "UTF-8", "UTF-16LE", "UTF-16", "UTF-16BE", "UTF-32")); /** * Display mode for output streams. */ public static enum OutputMode { /** Always display the output emitted from tests. */ ALWAYS, /** * Display the output only if a test/ suite failed. This requires internal buffering * so the output will be shown only after a test completes. */ ONERROR, /** * Don't display the output, even on test failures. */ NEVER; } /** * Status names column. */ private static EnumMap<TestStatus, String> statusNames; static { statusNames = new EnumMap<>(TestStatus.class); for (TestStatus s : TestStatus.values()) { statusNames.put(s, s == TestStatus.IGNORED_ASSUMPTION ? "IGNOR/A" : s.toString()); } } /** @see #setShowThrowable(boolean) */ private boolean showThrowable = true; /** @see #setShowStackTraces(boolean) */ private boolean showStackTraces = true; /** @see #setShowOutput(String) */ private OutputMode outputMode = OutputMode.ALWAYS; /** @see #setShowSuiteSummary(boolean) */ private boolean showSuiteSummary = true; /** @see #showEmptySuites(boolean) */ private boolean showEmptySuites = false; /** * Status display info. */ private final EnumMap<TestStatus,Boolean> displayStatus; /** * Initialize {@link #displayStatus}. */ { displayStatus = new EnumMap<>(TestStatus.class); for (TestStatus s : TestStatus.values()) { displayStatus.put(s, true); } } /** * A {@link Writer} for writing output messages. */ private Writer output; /** * Maximum number of columns for class name. */ private int maxClassNameColumns = Integer.MAX_VALUE; /** * Use simple names for suite names. */ private boolean useSimpleNames = false; /** * Display timestamps and durations for tests/ suites. */ private boolean timestamps = false; /** * {@link #output} file name. */ private File outputFile; /** * Append to {@link #outputFile} if specified. */ private boolean append; /** * Forked concurrent JVM count. */ private int forkedJvmCount; /** * Format line for JVM ID string. */ private String jvmIdFormat; /** Standard output, prefixed and decoded. */ private PrefixedWriter outWriter; /** Standard error, prefixed and decoded. */ private PrefixedWriter errWriter; /** sysout recode stream. */ private WriterOutputStream outStream; /** syserr recode stream. */ private WriterOutputStream errStream; /** Summarize the first N failures at the end. */ private int showNumFailuresAtEnd = 3; /** A list of failed tests, if to be displayed at the end. */ private List<Description> failedTests = new ArrayList<>(); /** Stack trace filters. */ private List<StackTraceFilter> stackFilters = new ArrayList<>(); private int totalSuites; private AtomicInteger totalErrors = new AtomicInteger(); private AtomicInteger suitesCompleted = new AtomicInteger(); private String seed; public void setShowStatusError(boolean showStatus) { displayStatus.put(TestStatus.ERROR, showStatus); } public void setShowStatusFailure(boolean showStatus) { displayStatus.put(TestStatus.FAILURE, showStatus); } public void setShowStatusOk(boolean showStatus) { displayStatus.put(TestStatus.OK, showStatus); } public void setShowStatusIgnored(boolean showStatus) { displayStatus.put(TestStatus.IGNORED, showStatus); displayStatus.put(TestStatus.IGNORED_ASSUMPTION, showStatus); } /** * Set maximum number of class name columns before truncated with ellipsis. */ public void setMaxClassNameColumns(int maxClassNameColumns) { this.maxClassNameColumns = maxClassNameColumns; } /** * Use simple class names for suite naming. */ public void setUseSimpleNames(boolean useSimpleNames) { this.useSimpleNames = useSimpleNames; } /** * Show duration timestamps for tests and suites. */ public void setTimestamps(boolean timestamps) { this.timestamps = timestamps; } /** * Filter stack traces from certain frames. */ public void addConfigured(StackTraceFilter sfilter) { this.stackFilters.add(sfilter); } /** * If enabled, displays extended error information for tests that failed * (exception class, message, stack trace, standard streams). * * @see #setShowStackTraces(boolean) */ public void setShowThrowable(boolean showThrowable) { this.showThrowable = showThrowable; } /** * Show stack trace information. */ public void setShowStackTraces(boolean showStackTraces) { this.showStackTraces = showStackTraces; } /** * Display mode for output streams. */ public void setShowOutput(String mode) { try { this.outputMode = OutputMode.valueOf(mode.toUpperCase(Locale.ROOT)); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("showOutput accepts any of: " + Arrays.toString(OutputMode.values()) + ", value is not valid: " + mode); } } /** * Summarize N failures at the end of the report. */ public void setShowNumFailures(int num) { this.showNumFailuresAtEnd = num; } /** * Display suites without any errors and with no tests (resulting from filtering * expressions, for example). */ public void setShowEmptySuites(boolean showEmptySuites) { this.showEmptySuites = showEmptySuites; } /** * If enabled, shows suite summaries in "maven-like" format of: * <pre> * Running SuiteName * [...suite tests if enabled...] * Tests: xx, Failures: xx, Errors: xx, Skipped: xx, Time: xx sec [&lt;&lt;&lt; FAILURES!] * </pre> */ public void setShowSuiteSummary(boolean showSuiteSummary) { this.showSuiteSummary = showSuiteSummary; } /** * Set an external file to write to. That file will always be in UTF-8. */ public void setFile(File outputFile) throws IOException { if (!outputFile.getName().isEmpty()) { this.outputFile = outputFile; } } /** * Append if {@link #setFile(File)} is also specified. */ public void setAppend(boolean append) { this.append = append; } /** * Initialization by container task {@link JUnit4}. */ @Override @SuppressForbidden("legitimate sysstreams.") public void setOuter(JUnit4 task) { this.seed = task.getSeed(); if (outputFile != null) { try { Files.createParentDirs(outputFile); final CharSink charSink; if (append) { charSink = Files.asCharSink(outputFile, Charsets.UTF_8, FileWriteMode.APPEND); } else { charSink = Files.asCharSink(outputFile, Charsets.UTF_8); } this.output = charSink.openBufferedStream(); } catch (IOException e) { throw new BuildException(e); } } else { if (!UNICODE_ENCODINGS.contains(Charset.defaultCharset().name())) { task.log("Your default console's encoding may not display certain" + " unicode glyphs: " + Charset.defaultCharset().name(), Project.MSG_INFO); } output = new LineFlushingWriter(new OutputStreamWriter(System.out, Charset.defaultCharset())) { @Override // Don't close the underlying stream, just flush. public void close() throws IOException { flush(); } }; } } /* * Test events subscriptions. */ @Subscribe public void onStart(AggregatedStartEvent e) throws IOException { this.totalSuites = e.getSuiteCount(); logShort("Executing " + totalSuites + Pluralize.pluralize(totalSuites, " suite") + " with " + e.getSlaveCount() + Pluralize.pluralize(e.getSlaveCount(), " JVM") + ".\n", false); forkedJvmCount = e.getSlaveCount(); jvmIdFormat = " J%-" + (1 + (int) Math.floor(Math.log10(forkedJvmCount))) + "d"; outWriter = new PrefixedWriter(stdoutIndent, output, DEFAULT_MAX_LINE_WIDTH); errWriter = new PrefixedWriter(stderrIndent, output, DEFAULT_MAX_LINE_WIDTH); } @Subscribe public void onChildBootstrap(ChildBootstrap e) throws IOException { logShort("Started J" + e.getSlave().id + " PID(" + e.getSlave().getPidString() + ")."); } @Subscribe public void onHeartbeat(HeartBeatEvent e) throws IOException { logShort("HEARTBEAT J" + e.getSlave().id + " PID(" + e.getSlave().getPidString() + "): " + formatTime(e.getCurrentTime()) + ", stalled for " + formatDurationInSeconds(e.getNoEventDuration()) + " at: " + (e.getDescription() == null ? "<unknown>" : formatDescription(e.getDescription()))); } @Subscribe public void onQuit(AggregatedQuitEvent e) throws IOException { if (showNumFailuresAtEnd > 0 && !failedTests.isEmpty()) { List<Description> sublist = this.failedTests; StringBuilder b = new StringBuilder(); b.append("\nTests with failures [seed: ").append(seed).append("]"); if (sublist.size() > showNumFailuresAtEnd) { sublist = sublist.subList(0, showNumFailuresAtEnd); b.append(" (first " + showNumFailuresAtEnd + " out of " + failedTests.size() + ")"); } b.append(":\n"); for (Description description : sublist) { b.append(" - ").append(formatDescription(description, true)).append("\n"); } b.append("\n"); logShort(b, false); } if (output != null) { Closeables.close(output, true); } } @Subscribe public void onSuiteStart(AggregatedSuiteStartedEvent e) throws IOException { final Charset charset = e.getSlave().getCharset(); outStream = new WriterOutputStream(outWriter, charset, DEFAULT_MAX_LINE_WIDTH, true); errStream = new WriterOutputStream(errWriter, charset, DEFAULT_MAX_LINE_WIDTH, true); if (showSuiteSummary && isPassthrough()) { SuiteStartedEvent evt = e.getSuiteStartedEvent(); emitSuiteStart(evt.getDescription(), evt.getStartTimestamp()); } } @Subscribe public void onOutput(PartialOutputEvent e) throws IOException { if (isPassthrough()) { // We only allow passthrough output if there is one JVM. switch (e.getEvent().getType()) { case APPEND_STDERR: ((IStreamEvent) e.getEvent()).copyTo(errStream); break; case APPEND_STDOUT: ((IStreamEvent) e.getEvent()).copyTo(outStream); break; default: break; } } } @Subscribe public void onJvmOutput(JvmOutputEvent e) throws IOException { final String id = Integer.toString(e.getSlave().id); output.append(">>> JVM J").append(id) .append(" emitted unexpected output (verbatim) ----\n"); try (Reader r = Files.newReader(e.getJvmOutputFile(), e.getSlave().getCharset())) { CharStreams.copy(r, output); } output.append("<<< JVM J" + id + ": EOF ----\n"); } @Subscribe public void onTestResult(AggregatedTestResultEvent e) throws IOException { if (isPassthrough() && displayStatus.get(e.getStatus())) { flushOutput(); emitStatusLine(e, e.getStatus(), e.getExecutionTime()); } if (!e.isSuccessful() && showNumFailuresAtEnd > 0) { failedTests.add(e.getDescription()); } } @Subscribe public void onSuiteResult(AggregatedSuiteResultEvent e) throws IOException { final int completed = suitesCompleted.incrementAndGet(); if (e.isSuccessful() && e.getTests().isEmpty() && !showEmptySuites) { return; } // We must emit buffered test and stream events (in case of failures). if (!isPassthrough()) { if (showSuiteSummary) { emitSuiteStart(e.getDescription(), e.getStartTimestamp()); } emitBufferedEvents(e); } // Emit a synthetic failure for suite-level errors, if any. if (!e.getFailures().isEmpty() && displayStatus.get(TestStatus.ERROR)) { emitStatusLine(e, TestStatus.ERROR, 0); } if (!e.getFailures().isEmpty() && showNumFailuresAtEnd > 0) { failedTests.add(e.getDescription()); } // Emit suite summary line if requested. if (showSuiteSummary) { emitSuiteEnd(e, completed); } } private void emitBufferedEvents(AggregatedSuiteResultEvent e) throws IOException { final IdentityHashMap<TestFinishedEvent,AggregatedTestResultEvent> eventMap = new IdentityHashMap<>(); for (AggregatedTestResultEvent tre : e.getTests()) { eventMap.put(tre.getTestFinishedEvent(), tre); } final boolean emitOutput = (outputMode != OutputMode.NEVER) && ((outputMode == OutputMode.ALWAYS && !isPassthrough()) || (outputMode == OutputMode.ONERROR && !e.isSuccessful())); for (IEvent event : e.getEventStream()) { switch (event.getType()) { case APPEND_STDOUT: if (emitOutput) ((IStreamEvent) event).copyTo(outStream); break; case APPEND_STDERR: if (emitOutput) ((IStreamEvent) event).copyTo(errStream); break; case TEST_FINISHED: assert eventMap.containsKey(event); final AggregatedTestResultEvent aggregated = eventMap.get(event); if (displayStatus.get(aggregated.getStatus())) { flushOutput(); emitStatusLine(aggregated, aggregated.getStatus(), aggregated.getExecutionTime()); } default: break; } } if (emitOutput) { flushOutput(); } } /** * Flush output streams. */ private void flushOutput() throws IOException { outStream.flush(); outWriter.completeLine(); errStream.flush(); errWriter.completeLine(); } /** * Suite prologue. */ private void emitSuiteStart(Description description, long startTimestamp) throws IOException { String suiteName = description.getDisplayName(); if (useSimpleNames) { if (suiteName.lastIndexOf('.') >= 0) { suiteName = suiteName.substring(suiteName.lastIndexOf('.') + 1); } } logShort(shortTimestamp(startTimestamp) + "Suite: " + FormattingUtils.padTo(maxClassNameColumns, suiteName, "[...]")); } /** * Suite end. */ private void emitSuiteEnd(AggregatedSuiteResultEvent e, int suitesCompleted) throws IOException { assert showSuiteSummary; final StringBuilder b = new StringBuilder(); final int totalErrors = this.totalErrors.addAndGet(e.isSuccessful() ? 0 : 1); b.append(String.format(Locale.ROOT, "%sCompleted [%d/%d%s]%s in %.2fs, ", shortTimestamp(e.getStartTimestamp() + e.getExecutionTime()), suitesCompleted, totalSuites, totalErrors == 0 ? "" : " (" + totalErrors + "!)", e.getSlave().slaves > 1 ? " on J" + e.getSlave().id : "", e.getExecutionTime() / 1000.0d)); b.append(e.getTests().size()).append(Pluralize.pluralize(e.getTests().size(), " test")); int failures = e.getFailureCount(); if (failures > 0) { b.append(", ").append(failures).append(Pluralize.pluralize(failures, " failure")); } int errors = e.getErrorCount(); if (errors > 0) { b.append(", ").append(errors).append(Pluralize.pluralize(errors, " error")); } int ignored = e.getIgnoredCount(); if (ignored > 0) { b.append(", ").append(ignored).append(" skipped"); } if (!e.isSuccessful()) { b.append(FAILURE_STRING); } b.append("\n"); logShort(b, false); } /** * Emit status line for an aggregated event. */ private void emitStatusLine(AggregatedResultEvent result, TestStatus status, long timeMillis) throws IOException { final StringBuilder line = new StringBuilder(); line.append(shortTimestamp(result.getStartTimestamp())); line.append(Strings.padEnd(statusNames.get(status), 8, ' ')); line.append(formatDurationInSeconds(timeMillis)); if (forkedJvmCount > 1) { line.append(String.format(Locale.ROOT, jvmIdFormat, result.getSlave().id)); } line.append(" | "); line.append(formatDescription(result.getDescription())); if (!result.isSuccessful()) { line.append(FAILURE_MARKER); } line.append("\n"); if (showThrowable) { // GH-82 (cause for ignored tests). if (status == TestStatus.IGNORED && result instanceof AggregatedTestResultEvent) { final StringWriter sw = new StringWriter(); PrefixedWriter pos = new PrefixedWriter(indent, sw, DEFAULT_MAX_LINE_WIDTH); pos.write("Cause: "); pos.write(((AggregatedTestResultEvent) result).getCauseForIgnored()); pos.completeLine(); line.append(sw.toString()); } final List<FailureMirror> failures = result.getFailures(); if (!failures.isEmpty()) { final StringWriter sw = new StringWriter(); PrefixedWriter pos = new PrefixedWriter(indent, sw, DEFAULT_MAX_LINE_WIDTH); int count = 0; for (FailureMirror fm : failures) { count++; if (fm.isAssumptionViolation()) { pos.write(String.format(Locale.ROOT, "Assumption #%d: %s", count, MoreObjects.firstNonNull(fm.getMessage(), "(no message)"))); } else { pos.write(String.format(Locale.ROOT, "Throwable #%d: %s", count, showStackTraces ? filterStackTrace(fm.getTrace()) : fm.getThrowableString())); } } pos.completeLine(); if (sw.getBuffer().length() > 0) { line.append(sw.toString()); } } } logShort(line); } /** * Filter stack trace if {@link #addConfigured(StackTraceFilter)}. */ private String filterStackTrace(String trace) { for (StackTraceFilter filter : stackFilters) { trace = filter.apply(trace); } return trace; } /** * Log a message line to the output. */ private void logShort(CharSequence message, boolean trim) throws IOException { int length = message.length(); if (trim) { while (length > 0 && Character.isWhitespace(message.charAt(length - 1))) { length--; } } char [] chars = new char [length + 1]; for (int i = 0; i < length; i++) { chars[i] = message.charAt(i); } chars[length] = '\n'; output.write(chars); } /** * logShort, trim whitespace. */ private void logShort(CharSequence message) throws IOException { logShort(message, true); } /** * @return <code>true</code> if we can emit output directly and immediately. */ private boolean isPassthrough() { return forkedJvmCount == 1 && outputMode == OutputMode.ALWAYS; } /** * Format a short timestamp. */ private String shortTimestamp(long ts) { if (timestamps) { return "[" + formatTimestamp(ts) + "] "; } else { return ""; } } }
Contrast transesophageal echocardiography using the Acunav ultrasound catheter through the mouth way as a guide to percutaneous closure of patent foramen ovale. AIM Contrast-enhanced transesophageal echo-cardiography (c-TEE) represents the gold standard in the diagnosis of patent foramen ovale (PFO) but it is not always well tolerated by the patient, and it is influenced by his cooperation. Purpose of the present study was to assess feasibility and safety of c-TEE through the oral way using a miniaturized 10-Fr, monoplane probe (Acunav-TEE) and establish its utility in the diagnosis or PFO when compared with c-TEE using the traditional multiplane probe (standard-TEE). METHODS From January 2008 to September 2008, 54 consecutive patients with presumed paradoxical cerebrovascular events and a suspected PFO were prospectively enrolled in this study. After signing a consensus form, these patients underwent both standard-TEE and Acunav-TEE in the same day by two independent operators. RESULTS Feasibility of standard-TEE in our study was 96.3% (52/54) while feasibility of Acunav-TEE was 100% (54/54). When compared to standard-TEE, Acunav-TEE required shorter average time to insert the probe (1.0+/-0.2 vs. 4.1+/-1.1 minutes, P<0.001) but longer average time to look for the best projection and start the examination (13.8+/-2.4 vs. 9.1+/-2.7 minutes, P<0.001). Using standard-TEE as gold standard we defined a sensitivity of 100% (20/20) and a specificity of 97% (31/32) for Acunav-TEE. The positive predictive value, the negative predictive value and the global diagnostic accuracy were 95% (20/21), 100% (31/31) and 98% (51/52), respectively. CONCLUSION Consistent with our experience, Acunav-TEE seems to be a feasible and safe technique when used for the diagnosis of PFO, with excellent sensitivity and specificity as compared with standard-TEE.
Being With the Patient: The Use of “Clinical Evidence,” Reconsidered Abstract Our objective was to review the use in psychiatry of data arising from interaction with the patient, here called “clinical evidence.” We conducted a clinical and historical review. Data from interactions with patients are increasingly marginalized in psychiatry, even as interactional data have an increasing role elsewhere in healthcare. Recommendations for training, clinical care, and administration are made.
/// Creates a new CryptoConfig in a temporary directory for testing. /// The directory has the permissions required for storing crypto state (see /// [`Self::check_dir_has_required_permissions`]) and will be automatically /// deleted when the returned `TempDir` goes out of scope. /// Panics if creating the directory or setting the permissions fails. pub fn new_in_temp_dir() -> (Self, TempDir) { let temp_dir = tempfile::Builder::new() .prefix("ic_crypto_") .tempdir() .expect("failed to create temporary crypto directory"); fs::set_permissions(temp_dir.path(), Permissions::from_mode(0o750)).unwrap_or_else(|_| { panic!( "failed to set permissions of crypto directory {}", temp_dir.path().display() ) }); let temp_dir_path = temp_dir.path().to_path_buf(); CryptoConfig::check_dir_has_required_permissions(&temp_dir_path) .expect("Wrong dir permissions"); let config = CryptoConfig::new(temp_dir_path); (config, temp_dir) }
Highly malignant disease in childhood-onset arrhythmogenic right ventricular cardiomyopathy Abstract Aims This study aimed to explore the incidence of severe cardiac events in paediatric arrhythmogenic right ventricular cardiomyopathy (ARVC) patients and ARVC penetrance in paediatric relatives. Furthermore, the phenotype in childhood-onset ARVC was described. Methods Consecutive ARVC paediatric patients and genotype positive relatives ≤18 years of age were followed with electrocardiographic, structural, and arrhythmic characteristics according to the 2010 revised Task Force Criteria. Penetrance of ARVC disease was defined as fulfilling definite ARVC criteria and severe cardiac events were defined as cardiac death, heart transplantation (HTx) or severe ventricular arrhythmias. Childhood-onset disease was defined as meeting definite ARVC criteria ≤12 years of age. Results Among 62 individuals , 20 (32%) fulfilled definite ARVC diagnosis, of which 8 (40%) had childhood-onset disease. The incidence of severe cardiac events was 23% (n = 14) by last follow-up and half of them occurred in patients ≤12 years of age. Among the eight patients with childhood-onset disease, five had biventricular involvement needing HTx and three had severe arrhythmic events. Among the 51 relatives, 6% (n = 3) met definite ARVC criteria at time of genetic diagnosis, increasing to 18% (n = 9) at end of follow-up. Conclusions In a paediatric ARVC cohort, there was a high incidence of severe cardiac events and half of them occurred in children ≤12 years of age. The ARVC penetrance in genotype positive paediatric relatives was 18%. These findings of a high-malignant phenotype in childhood-onset ARVC indicate a need for ARVC family screening at younger age than currently recommended. Aims This study aimed to explore the incidence of severe cardiac events in paediatric arrhythmogenic right ventricular cardiomyopathy (ARVC) patients and ARVC penetrance in paediatric relatives. Furthermore, the phenotype in childhood-onset ARVC was described. Methods Consecutive ARVC paediatric patients and genotype positive relatives ≤18 years of age were followed with electrocardiographic, structural, and arrhythmic characteristics according to the 2010 revised Task Force Criteria. Penetrance of ARVC disease was defined as fulfilling definite ARVC criteria and severe cardiac events were defined as cardiac death, heart transplantation (HTx) or severe ventricular arrhythmias. Childhood-onset disease was defined as meeting definite ARVC criteria ≤12 years of age. Results Among 62 individuals , 20 (32%) fulfilled definite ARVC diagnosis, of which 8 (40%) had childhood-onset disease. The incidence of severe cardiac events was 23% (n = 14) by last follow-up and half of them occurred in patients ≤12 years of age. Among the eight patients with childhood-onset disease, five had biventricular involvement needing HTx and three had severe arrhythmic events. Among the 51 relatives, 6% (n = 3) met definite ARVC criteria at time of genetic diagnosis, increasing to 18% (n = 9) at end of follow-up. Conclusions In a paediatric ARVC cohort, there was a high incidence of severe cardiac events and half of them occurred in children ≤12 years of age. The ARVC penetrance in genotype positive paediatric relatives was 18%. These findings of a high-malignant phenotype in childhood-onset ARVC indicate a need for ARVC family screening at younger age than currently recommended. 7 To T T tal population 23% cumulative incidence of se evere c ca ar rdi diac e ev ven ents s ( (n = 14) 13% % childhood-onset disea ase se 18% penet tr ra ance of AR RV V R R R R C disea ase se 6% sev ve er re car rdiac even ents 6% childhood-onset disease Relati ives es 40% had childhood-onset disease 14 p patients had sev ver re car rdi diac ac e ev ven ents ts 50% had childhood-onset disease e Introduction Arrhythmogenic right ventricular cardiomyopathy (ARVC) is an inheritable and progressive heart muscle disease characterized by high risk of ventricular tachyarrhythmias and sudden cardiac death, in addition to morphological abnormalities and eventually heart failure. 1 The disease has autosomal dominant inheritance with variants in genes encoding cardiac desmosomal proteins, 2 and it exhibits variable penetrance and expressivity. 3 ARVC diagnosis is made by combining multiple sources of information as described by the consensus-based revised 2010 Task Force Criteria (TFC). 4 ARVC is considered a disease most relevant to the young adult population, with onset typically observed in the third and fourth decade of life. 5 Penetrance of ARVC disease has been described in adolescents, 6 but is currently considered to be extremely rare under the age of 10. 5 Ten perecent to 25% of sudden deaths in children have been shown to be associated with ARVC. 7,8 However, children with ARVC are underrepresented in research publications. The clinical characteristics of paediatric ARVC are largely unknown and data is lacking on both the incidence of events in children with ARVC and the penetrance of disease in ARVC genotype positive paediatric relatives. The current expert consensus document in arrhythmogenic cardiomyopathy (AC) 5 recommends that first-degree relatives undergo clinical evaluation every 1-3 years starting at 10-12 years of age. However, the clinical value of this approach has not been systematically evaluated. We aimed to explore the incidence of severe cardiac events related to ARVC in paediatric patients (≤18 years) and to describe the phenotype of childhood-onset ARVC. Furthermore, we aimed to assess the penetrance of ARVC disease in genotype positive paediatric relatives. We hypothesized that the frequency of childhood-onset ARVC in children is underestimated and that the current screening recommendations leads to under-diagnosis of childhood-onset disease, which can impact timely interventions aimed at preventing severe outcomes. Study population In a single-centre cohort study, we included all consecutive ARVC probands and genotype-positive relatives ≤18 years old followed at the Department of Paediatric Cardiology, Oslo University Hospital, Rikshospitalet, Norway, between 2007 and 2021. Inclusion was defined as the time of first echocardiographic examination. Last clinical follow-up was the last clinical visit before death, cardiac transplantation, turning 19 years of age or August 2021. We defined phenotype positive patients as those fulfilling definite 2010 TFC. These diagnostic criteria were applied retrospectively for patients identified before 2010. We defined a proband as the first person in a family to exhibit clinical symptoms or signs that triggered an evaluation of ARVC. Genotype positive relatives were included regardless of fulfilling definite, borderline, or possible diagnosis at time of inclusion. Genotype negative probands and their relatives were only included if fulfilling a definite ARVC diagnosis by the revised 2010 TFC. 4 Patients with other cardiopulmonary comorbidities were excluded. Penetrance of ARVC disease in family members was defined as fulfilling definite ARVC criteria. Written informed consent was given by the study participants or by the legal guardians of the participants if they were under the age of 16. The study complied with the Declaration of Helsinki and was approved by the Regional Committees for Medical Research Ethics (REK: 185666). Electrocardiogram Twelve-lead electrocardiograms (ECGs) were evaluated for repolarization (precordial T-wave inversion in leads V1 and V2 or beyond) and/or depolarization (epsilon waves or terminal activation duration ≥55 ms). In agreement with the revised 2010 TFC, 4 precordial T-wave inversions were not considered for patients <14 years of age. Holter recordings were evaluated for premature ventricular complex (PVC) count and regarded abnormal if >500 PVCs per 24 h were recorded. 4 Signal-averaged electrocardiographic recordings, obtained using timedomain analysis with a bandpass filter of 40 Hz, were evaluated for evidence of late potentials using age appropriate criteria. 9 Genetic analyses From 2007 to 2018, we used Sanger-based gene panels consisting of DSC2, DSG2, DSP, TMEM43 and PKP2 genes. From 2018, we used larger nextgeneration sequencing (NGS)-based gene panels for genetic testing. If no findings on Sanger sequencing or NGS, multiplex ligation-dependent probe amplification (MLPA, SALSA MLPA Probemix P168 ARVC-PKP2, MRC Holland) was performed. All identified variants were manually curated according to the 2015 American College of Medical Genetics and Genomics (ACMG) guidelines 10 and only variants classified as pathogenic/ likely pathogenic (P/LP) were included. In case of a genotype positive proband, first-degree relatives were offered genetic cascade screening at the time ARVC was diagnosed in the family. Genotype positive relatives were called in to first clinical evaluation at time of genetic diagnosis, regardless of patient age. We measured right ventricular (RV) outflow tract (RVOT) diameter in parasternal short-axis view, RV basal diameter (RVD1) and RV fractional area change (RVFAC). All echocardiographic views, including the subcostal view, were used to detect RV akinesia, dyskinesia, or aneurysms. 11 Left ventricular (LV) function by LV ejection fraction (LVEF) was measured by Simpson`s biplane method. 12 Cardiac magnetic resonance imaging Cardiac magnetic resonance (CMR) imaging was performed in a subset of 22 patients. CMR was performed on clinical indication including severe ventricular arrhythmias and reduced ventricular function and not routinely for diagnostic work-up. The late gadolinium enhancement (LGE) technique was performed in 21 patients. We used 1.5 Tesla units (Magnetom Vision Plus or Magnetom Sonata, Siemens, Erlangen, Germany) and a phased array body coil. Axial and sagittal T1 turbo spin echo images, multiple axial images, and one sagittal cineloop covering the RV and LV were recorded. RV and LV chamber dimensions, wall thickness, and myocardial function were assessed. A negative CMR study was defined as normal RV and LV dimensions, normal global or regional wall motion, no fatty infiltration, and no aneurysm formation. Both echocardiography and CMR imaging were assessed to determine the severity and extent of structural abnormalities according to the revised 2010 TFC. 4 LV involvement was defined by identification of at least one of the following: LVEF <55%; epicardial LGE; end-diastolic volume ≥120/ml/ m²; and wall motion abnormalities. Patients included before 2010 were retrospectively re-evaluated for fulfilment of revised 2010 TFC. 4 Outcomes This study collected three outcomes: (1) Definitive ARVC diagnosis by the revised 2010 TFC 4 established ≤18 years of age. (2) Severe cardiac events, defined as cardiac death, heart transplantation (HTx) or severe ventricular arrhythmias. A severe ventricular arrhythmic event was defined as aborted cardiac arrest (ACA), sustained ventricular tachycardia (VT) documented on 12-lead ECG or Holter, or VT or ventricular fibrillation (VF) terminated by appropriate implantable cardioverter defibrillator (ICD)-therapy. (3) Childhood-onset ARVC, defined as meeting definite ARVC criteria at 12 years of age or younger. Statistical analysis Continuous data were presented as mean ± standard deviation or median , and categorical variables as number (percentage). Continuous variables were compared using the independent Student t test and categorical data using chi-square tests, Fisher exact test or Kruskal-Wallis rank test, as appropriate. We performed exact logistic regression analysis and provided odds ratio (95% confidence interval) for risk markers for severe cardiac events. Survival analyses were performed for age at outcomes with groups compared by log-rank test and displayed in Kaplan-Meyer plots (SPSS statistics version 26). Two-sided P-values <0.05 were considered significant. Severe cardiac events Among the 62 included patients, 6 had a severe cardiac event at inclusion as the first sign of ARVC disease. These six were all arrhythmic events (3 ACA, 3 sustained VT). Additional eight patients experienced a severe cardiac event during follow-up, giving a cumulative incidence of 23% (n = 14/62) at age ≤ 18. Median age at severe cardiac event was 12.9 years ( Figure 3) and 7 (50%) events occurred in patients ≤12 years of age (Table 2, Figure 2, Structured Graphical Abstract). Of the 14 events, 9 (64%) were arrhythmic events (3 ACA, 5 sustained VT, one VF terminated by appropriate ICD therapy) and 5 (36%) were HTx ( Table 2). All 14 patients with severe cardiac events met diagnostic criteria for definite ARVC according to the revised 2010 TFC 4 ( Table 3). Eleven patients (18%) received an ICD; eight as secondary prevention and three as primary prevention therapy. No patients died during the study period ( Table 2). Cardiac phenotype in childhood-onset disease The phenotypes identified in the 20 patients with a definite ARVC diagnosis at end of follow-up were right predominant in 11 (55%) and biventricular in 9 (45%) patients. In the nine patients with biventricular involvement, the ARVC diagnosis was confirmed by CMR in eight and histologically in one patient. The eight patients with childhood-onset disease had more frequently biventricular disease (63% vs. 33%, P < 0.01) with reduced LVEF of 37 ± 14% and RVFAC 23 ± 7% at end of follow-up. All five children who underwent HTx had childhood-onset disease and the youngest patient was transplanted at age 3. Penetrance of AC disease in paediatric relatives The 51 genotype positive paediatric relatives identified by screening were 9.0 (4.3-12.9) years of age at genetic diagnosis. At inclusion, three fulfilled definite ARVC criteria. Another six relatives progressed to definite diagnosis during 5.8 (3.5-9.2) years of follow-up (Figures 1 and 2), giving a cardiac penetrance of 18% (9/51). Three of the nine (33%) relatives with a definitive ARVC diagnosis had childhood-onset ARVC. Three (6%) of the relatives experienced severe cardiac events ( Figure 1) at a mean age of 12.6 (range 7.9-18.8) years ( Figure 3) and at median 1.1 (range 1.0-5.2) years after genetic diagnosis. Two of these patients underwent cardiac transplantation at 7 and 12 years of age, and one experienced exercise induced sustained VT at 18 years of age ( Table 2). Sex differences No sex differences were found, neither regarding penetrance of ARVC disease nor regarding the incidence of cardiac events. Discussion This study reports a 23% cumulative incidence of severe cardiac events in paediatric ARVC patients ≤ age 18. Of those with a definite ARVC diagnosis, 40% had childhood-onset disease, all with a highly malignant phenotype including ventricular arrhythmias and biventricular cardiac involvement and end-stage heart failure, reflecting the severity of ARVC disease at young age. Severe cardiac events also occurred in 6% of paediatric relatives and disease penetrance among relatives was 18%, indicating that genetic testing and clinical evaluation of relatives might be warranted at a younger age than currently recommended. Outcome Our study showed that 40% of patients with definite ARVC diagnosis had childhood-onset disease. Previous studies, however, have suggested that paediatric ARVC is a disease of adolescents. In the study of Roudijk et al. 13 the youngest relative fulfilling ARVC diagnosis was 11 years old, while one proband was 9 years old. Te Riele et al. 6 reported the youngest patient with a definite ARVC diagnose being 11 years old. According to the 2019 HRS expert consensus document ARVC is considered to be extremely rare under the age of 10 and exclusively seen in probands. 5 A recent review of ARVC in children declared that identifying ARVC prior to age 10 is exceedingly unlikely. 14 Our findings question these statements as we found a high frequency of childhood-onset disease defined as meeting definite ARVC criteria at ≤12 years of age. This study is to the best of our knowledge, the first to report the incidence of severe cardiac events in ARVC patients ≤18 years of age. Our study demonstrated that ARVC is a highly malignant paediatric disease with a high incidence of ventricular arrhythmias, heart failure and need of HTx. Importantly, 50% of the severe cardiac events occurred in patients ≤12 years of age. Risk assessment of VT and SCD in ARVC is challenging. There are published risk calculators for VT and SCD derived from the adult ARVC population. 15,16 As always when working with decision support tools, these should be regarded as guidance in decision making and should not be followed blindly. 17 As discussed in a recent commentary, 17 risk calculators do generally not incorporate the effect of treatment. They evaluate the baseline arrhythmic risk to predict future malignant events, without accounting for changes in the risk resulting from treatment and which may overestimate risk. 17 We did not use arrhythmic risk calculators in this study, nor do we use them in clinical paediatric practise due to the lack of validation in children. Implanting cardiac devices in children requires extreme care, involving unique patients' characteristics, technical issues due to growth, and parents' and patients' preferences. Severe cardiac phenotype in childhood-onset ARVC Patients with childhood-onset ARVC showed more frequently biventricular involvement and heart failure necessitating heart transplantation. Five out of 8 children with childhood-onset ARVC showed a grave progression and needed HTx, illustrating the severity of ARVC structural disease in childhood. One of the 2 patients diagnosed with definite ARVC at 3 years of age (PKP2 positive), presented with neonatal cardiac failure, a period of recovery, and then later disease progression leading to HTx at age 3.6 years. During the recent years, the AC clinical spectrum has grown to include both RV-, LV-and biventricular-predominant patterns of disease. 5 AC include a broader spectrum of diseases with other features. 18 Our patient population represented a classical ARVC cohort, with RV disease in all phenotype positive patients. Despite the 'classical' phenotype in our study, nine patients had biventricular disease emphasizing that paediatric-onset ARVC can involve both RV and/or LV at the time of presentation, as also recently shown by deWitt et al. 19 We used the revised 2010 TFC 4 to ascertain ARVC diagnosis in study subjects. It is important to recognize that the revised 2010 TFC were derived using a predominantly adult population (mean 38 ± 13 years of age). More specifically, only 8% of probands in the original TFC document 20 were diagnosed between 12 and 18 years of age. 4 As such, extrapolation of the TFC for use in paediatric cases might be speculative. Of note, all 14 children with severe cardiac events in our study met diagnostic criteria for definite ARVC according to the revised 2010 TFC, 4 indicating that severity of disease is covered by the TFC also in paediatric patients. Clinical yield of screening during childhood In genotype positive paediatric relatives, ARVC penetrance at end of follow-up was as high as 18%, confirming ARVC disease also in paediatric relatives. Cascade family screening to identify asymptomatic individuals is widely accepted as an important part of ARVC management. However, the 2019 HRS expert consensus 5 recommends that firstdegree relatives undergo clinical evaluation every 1-3 years starting as late as at 10-12 years of age. This recommendation is based on previous studies with underrepresentation of children that reported that most ARVC does not manifest until adulthood. However, the high penetrance of ARVC disease in our paediatric patients indicates a need of an earlier screening approach and is emphasized by the findings of childhood-onset disease and severe cardiac events among young paediatric relatives. This highlights the importance of starting clinical and genetic family screening earlier than current recommendations. Study limitations We performed a longitudinal cohort study with inherent limitations. The study may have entailed survival bias and we did not cover out of hospital ARVC deaths. Undiagnosed ARVC patients dying suddenly were not included. We can therefore not report the true incidence of ARVC related SCD in children which would require a nationwide autopsy-based study. Childhood-onset ARVC could be underestimated, as screening did not consequently start at birth. We did not perform CMR in all genotype positive paediatric relatives due to the need of anaesthesia, which may have underestimated the number of relatives fulfilling definite 2010 TFC. In addition, recent reports have shown that the TFC are relatively insensitive for paediatric diagnosis, 21 which further may have underestimated the number of patients with definite ARVC diagnosis. Age-specific norms for T-wave amplitude are anticipated to be useful, 22 T-wave inversions were not counted in patients under the age of 14 years. Results from exact logistic regression analysis were reported as odd ratios (95% confidence interval) and P-values. genetic testing in 2007 in Norway and changes in awareness of ARVC disease 23 may have influenced the dynamics of presentation of disease. Although this study represents one of the largest studies on paediatric ARVC to date, the sample size was limited. The design of our study was a longitudinal cohort study with a descriptive aim and it was not powered for risk analyses nor sex differences. Future multicenter studies with larger number of participants should explore age-, sex-, gene, and variant -specific features to improve management of ARVC in childhood. The issue of dependency within data should be considered when including data from families. Random effect analysis of family could not be included in our model due to absence of convergence. However, the families were relatively small with maximum six members in the biggest family (see Supplementary material online, Table S1). Furthermore, the analysis on clustering of genetic variant did not show association with severe cardiac events, suggesting that the relevance of dependency was not likely to be too significant in our model. Conclusions We found a 23% cumulative incidence of severe cardiac events, including VA and HTx, in a paediatric ARVC cohort of probands and genotype positive relatives ≤ 18 years of age. Childhood-onset ARVC was found in 40% of all patients with a definite diagnosis and appeared with a highly malignant phenotype, including biventricular involvement and end-stage heart failure necessitating HTx. Genotype positive paediatric relatives had a 18% disease penetrance and 6% experienced severe cardiac events. Increased awareness of childhood-onset, aggressive ARVC disease has important implications for patient management, suggesting that clinical screening should begin at a younger age than currently recommended. Supplementary material Supplementary material is available at European Heart Journal online. Funding Funding for this project was provided by the Research Council of Norway #309762 ProCardio Center for Innovation.
/* * Copyright: Copyright 2015 (c) Parametric Technology GmbH * Product: PTC Integrity Lifecycle Manager * Author: <NAME>, Senior Consultant ALM * Purpose: Custom Developed Code * ************** File Version Details ************** * Revision: $Revision$ * Last changed: $Date$ */ package formatheaders.commands; import formatheaders.api.IntegrityCommands; import javafx.application.Platform; import javafx.scene.control.TextArea; /** * * @author veckardt */ public class FXLogger { private static TextArea logArea; private static IntegrityCommands api; /** * * @param api * @param logArea */ public static void init(IntegrityCommands api, TextArea logArea) { FXLogger.api = api; FXLogger.logArea = logArea; } /** * Writes a message * @param text */ public static void log(String text) { writeLogArea("", text); api.log(text, 1); } /** * Writes a debug message * @param text */ public static void debug(String text) { api.log(text, 1); } /** * Writes a message prefixed with ERROR * @param text */ public static void error(String text) { writeLogArea("ERROR", text); api.log("ERROR: " + text, 1); } /** * Writes a message prefixed with INFO * @param text */ public static void info(String text) { writeLogArea("INFO", text); api.log("INFO: " + text, 1); } private static void writeLogArea(String tag, String text) { Platform.runLater(new Runnable() { @Override public void run() { logArea.appendText("\n" + (tag.isEmpty() ? "" : tag + ": ") + text); } }); } }
#ifndef split_h #define split_h #include <vector> #include "fpClassTotals.h" #include "growingTreeElement.h" #include "fpSplitInfo.h" namespace fp { template<typename T> class fpSplit{ protected: double overallImpurity; fpClassTotals leftClasses; fpClassTotals rightClasses; std::vector<int> labels; std::vector< growingTreeElement<T> > combinedDataLabels; inline void setCombinedVecSize(){ combinedDataLabels.resize(labels.size()); } inline void zipDataLabels(const std::vector<T>& featureVals){ for(unsigned int i=0; i<labels.size(); ++i){ combinedDataLabels[i].setPair(featureVals[i],labels[i]); } } inline T midVal(int leftIndex){ return combinedDataLabels[leftIndex].midVal(combinedDataLabels[leftIndex+1]); } inline bool checkInequalityWithNext(int leftIndex){ return combinedDataLabels[leftIndex].checkInequality(combinedDataLabels[leftIndex+1]); } inline void setupForNextRun(){ //setup for next possible run leftClasses.incrementClass(combinedDataLabels.back().returnDataLabel()); rightClasses.decrementClass(combinedDataLabels.back().returnDataLabel()); //TODO ensure rightClasses is zero at this point. rightClasses = leftClasses; leftClasses.resetClassTotals(); } public: fpSplit(const std::vector<int>& labelVector): labels(labelVector){ rightClasses.findNumClasses(labels); leftClasses.setClassVecSize(rightClasses.returnClassVecSize()); this->setCombinedVecSize(); overallImpurity = rightClasses.calcAndReturnImpurity(); } inline double returnImpurity(){ return overallImpurity; } fpSplitInfo<T> giniSplit(const std::vector<T>& featureVals, int featureNum){ double tempImpurity; int numLabels = labels.size(); // timeLogger logTime; // initialize return value fpSplitInfo<T> currSplitInfo; currSplitInfo.setFeatureNum(featureNum); // zip data and labels zipDataLabels(featureVals); // sort feature Vals std::sort(combinedDataLabels.begin(), combinedDataLabels.end()); // find split for(int i=0; i<numLabels-1; ++i){ leftClasses.incrementClass(combinedDataLabels[i].returnDataLabel()); rightClasses.decrementClass(combinedDataLabels[i].returnDataLabel()); if(checkInequalityWithNext(i)){ tempImpurity = leftClasses.calcAndReturnImpurity() + rightClasses.calcAndReturnImpurity(); if(tempImpurity < currSplitInfo.returnImpurity() && tempImpurity != overallImpurity){ currSplitInfo.setImpurity(tempImpurity); currSplitInfo.setSplitValue(midVal(i)); currSplitInfo.setLeftImpurity(leftClasses.returnImpurity()); currSplitInfo.setRightImpurity(rightClasses.returnImpurity()); } } } if(currSplitInfo.returnImpurity() == overallImpurity){ std::cout << "it happened\n"; exit(1); //should never happen. Why? currSplitInfo.setImpurity(-1); } //logTime.startFindSplitTimer(); setupForNextRun(); //logTime.stopFindSplitTimer(); return currSplitInfo; } }; } //namespace #endif //split
<filename>src/np/blockchain/session1/CeaserCipher.java package np.blockchain.session1; import np.blockchain.session1.Cipher; public class CeaserCipher extends Cipher{ byte shift_value; CeaserCipher(int shift){ shift=(byte)shift; } @Override public byte[] encrypt(byte[] data) { byte[] result=data.clone(); for(int i=0;i<data.length;i++) { result[i] += shift_value; } return result; } @Override public byte[] decrypt(byte[] data) { byte[] result=data.clone(); for(int i=0;i<data.length;i++){ result[i]-= shift_value; } return result; } }
// // Get a value from a register. // uint8_t DS3234RealTimeClock::GetRegisterValue(const Registers reg) { uint8_t result; m_Port->ChipSelect(LOW); m_Port->WriteRead(reg); result = m_Port->WriteRead(0x00); m_Port->ChipSelect(HIGH); return(result); }
/** * :: DeveloperApi :: * A SparkListener that prepares information to be displayed on the BlockManagerUI. * <p> * This class is thread-safe (unlike JobProgressListener) */ public class StorageListener extends org.apache.spark.storage.BlockStatusListener { public StorageListener (org.apache.spark.storage.StorageStatusListener storageStatusListener) { throw new RuntimeException(); } public scala.collection.mutable.Map<java.lang.Object, org.apache.spark.storage.RDDInfo> _rddInfoMap () { throw new RuntimeException(); } public scala.collection.Seq<org.apache.spark.storage.StorageStatus> storageStatusList () { throw new RuntimeException(); } /** Filter RDD info to include only those with cached partitions */ public scala.collection.Seq<org.apache.spark.storage.RDDInfo> rddInfoList () { throw new RuntimeException(); } /** Update the storage info of the RDDs whose blocks are among the given updated blocks */ private void updateRDDInfo (scala.collection.Seq<scala.Tuple2<org.apache.spark.storage.BlockId, org.apache.spark.storage.BlockStatus>> updatedBlocks) { throw new RuntimeException(); } /** * Assumes the storage status list is fully up-to-date. This implies the corresponding * StorageStatusSparkListener must process the SparkListenerTaskEnd event before this listener. * @param taskEnd (undocumented) */ public void onTaskEnd (org.apache.spark.scheduler.SparkListenerTaskEnd taskEnd) { throw new RuntimeException(); } public void onStageSubmitted (org.apache.spark.scheduler.SparkListenerStageSubmitted stageSubmitted) { throw new RuntimeException(); } public void onStageCompleted (org.apache.spark.scheduler.SparkListenerStageCompleted stageCompleted) { throw new RuntimeException(); } public void onUnpersistRDD (org.apache.spark.scheduler.SparkListenerUnpersistRDD unpersistRDD) { throw new RuntimeException(); } }
4-Vinylpyridine-Modified Nickel and Cobalt Dibenzoylmethanates as New Hosts: Inclusions with Carbon Tetrachloride and Chlorobenzene Abstract Bis(4-vinylpyridine)bis(dibenzoylmethanato)metal(II), (M = Ni(II), Co(II); ViPy = 4-Vinylpyridine; DBM = C6H5COCHCOC6H5 −, dibenzoylmethanate) is a new metal-complex host. Its inclusions with carbon tetrachloride (host:guest = 1:2; triclinic, P 1, Z = 1) and chlorobenzene (host:guest = 1:1; monoclinic, P2 1 /c, Z = 4) are consistent with the van der Waals packing of neutral complex (host) and solvent (guest) molecules. In the host unit, four oxygens from two chelate DBM-units provide a square-planar environment around the metal center that is extended to octahedral coordination by two apical nitrogens from two vinylpyridine moieties in the trans-position. In the carbon tetrachloride inclusions, the host traps two guest molecules in large prolate spheroidal cavities. In the chlorobenzene inclusions, guest species are located inside 8-shaped serpentine channels along the y-axis. The nickel and cobalt versions of the inclusion compounds were found to be very similar.
<reponame>harrybrwn/vine package logging import ( "bufio" "bytes" "context" "fmt" "io" "os" "os/exec" "regexp" "strconv" "strings" "github.com/harrybrwn/config" "github.com/sirupsen/logrus" "github.com/spf13/cobra" "gopkg.in/natefinch/lumberjack.v2" ) // NewLogCmd creates a new log command from a log file func NewLogCmd(logfile *lumberjack.Logger) *cobra.Command { var ( file bool less bool num int ) c := &cobra.Command{ Use: "logs", Short: "Manage logs and log files", SilenceErrors: true, SilenceUsage: true, RunE: func(cmd *cobra.Command, args []string) (err error) { if file { fmt.Println(logfile.Filename) return nil } ctx, cancel := context.WithCancel(context.Background()) defer cancel() var proc *exec.Cmd if less { proc = exec.CommandContext(ctx, "less", logfile.Filename) proc.Stdout = cmd.OutOrStdout() return proc.Run() } proc = exec.CommandContext(ctx, "tail", "-F", logfile.Filename, "-n", strconv.Itoa(num)) proc.Stderr, proc.Stdin = cmd.ErrOrStderr(), cmd.InOrStdin() var copy = io.Copy if config.GetBool("nocolor") { copy = copyNoColor } loglvl, err := logrus.ParseLevel(config.GetString("loglevel")) if err == nil && loglvl != logrus.TraceLevel { copy = copyFilterLevels(loglvl, copy) } pipe, err := proc.StdoutPipe() if err != nil { return err } defer pipe.Close() if err = proc.Start(); err != nil { return err } go copy(os.Stdout, pipe) err = proc.Wait() if e, ok := err.(*exec.ExitError); ok && e.Error() == "signal: killed" { return proc.Process.Release() } return err }, } flags := c.Flags() flags.BoolVarP(&file, "file", "f", file, "print the path of the logfile") flags.IntVarP(&num, "num", "n", 20, "number of lines of log file shown") flags.BoolVar(&less, "less", less, "run less to look at the logs") return c } type copyFunc func(io.Writer, io.Reader) (int64, error) func composeCopies(fns []copyFunc) copyFunc { return func(io.Writer, io.Reader) (int64, error) { return 0, nil } } var colorRegex = regexp.MustCompile("[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]") // yes, i copied this from io.Copy in the io package func copyNoColor(dest io.Writer, src io.Reader) (written int64, err error) { return copyFilter(dest, src, func(b []byte) []byte { return colorRegex.ReplaceAll(b, nil) }) } func levelsStr() []string { str := make([]string, 0) for _, l := range logrus.AllLevels { str = append(str, l.String()) } return str } func copyFilterLevels(l logrus.Level, copy copyFunc) func(io.Writer, io.Reader) (int64, error) { var ( str = levelsStr() levels = strings.Join(str[:l+1], "|") re = regexp.MustCompile(fmt.Sprintf(".*(%s).*", strings.ToUpper(levels))) buf bytes.Buffer ) return func(out io.Writer, in io.Reader) (w int64, err error) { sc := bufio.NewScanner(in) for sc.Scan() { buf.Reset() b := sc.Bytes() if re.Match(b) { buf.Write(b) buf.Write([]byte{'\n'}) copy(out, &buf) } } return } } func copyFilter(dest io.Writer, src io.Reader, filter func([]byte) []byte) (written int64, err error) { buf := make([]byte, 32*1024) for { nr, er := src.Read(buf) if nr > 0 { nw, ew := dest.Write(filter(buf[0:nr])) if nw > 0 { written += int64(nw) } if ew != nil { err = ew break } // TODO: predict what the difference will be here if nr != nw { err = io.ErrShortWrite // break } } if er != nil { if er != io.EOF { err = er } break } } return }
def normalize(vectors, axis=-1): n = norm(vectors, axis=axis, keepdims=True) return np.where(n <= 0, 0, vectors / n)
RANCHI: The place British used to execute freedom fighters in pre-independent India now hosts world's largest tricolour on tallest flag-post, the 66x99 feet flag, 493 feet above surface on a 293 feet mast at Ranchi's popular Pahari Mandir. The flag, defence minister Manohar Parrikar hoisted on Saturday, flutters in the breeze soaking the place – that remembers the cruel executions – in patriotism. Many in Ranchi know Pahari Mandir as 'Fansi Dungri' (hanging point)."The country's largest flag on tallest post is also the most majestic and most beautiful," Parrikar said after unfurling the 60-kg flag atop Pahari Mandir. The event coincided with Netaji Subash Chandra Bose's birth anniversary.The majestic flag drew people at the foot-hills of Pahari Mandir as well as on roof-tops where they struggled to capture the patriotic moment in cameras. Rohan Deo Pathak, a local singer, sang a couple of patriotic numbers for a TV channel dedicating a special coverage to the event. He went on to share a selfie with flag on Facebook. "Feeling patriotic at Pahari Mandir," he wrote.The occasion moved Jharkhand governor Dropadi Murmu like many others. "This place was known as Fansi Dungri in pre-Independent India. It is known for sacrifice. After Independence Ranchi's first tri-colour was hoisted at this place to pay a tribute to the martyrs," Murmu said.Loudspeakers boomed 'ye desh hai veer jawano ka' among other songs atop the hill where many attendees appeared in flag-painted face while others wore stickers of Indian flags. It later made Parrikar remark: "The energy and enthusiasm was similar to 26 January." A glider tried to add colour to the occasion. In the charged environment CM Raghubar Das, governor Murmu shared stage with Parrikar and state leaders where students in colourful dresses stood in tricolour pattern.The authorities of Pahari Mandir Samiti, the agency behind putting up the majestic flag, claimed it is world's largest tricolour on tallest mast and have written to Limca Book of World Records and would write to Guinnes Book of World Records. A BJP leader Sanjay Seth, associated with the event, said previous highest flag-post, he said, is at 250 feet is in Faridabad and the tricolour is only 96x64 feet.The mast was developed over 40 days by Mecon, a public sector undertaking under the ministry of steel. The pole has been designed to withstand strong winds, earthquake and all possible natural damage. It is fitted with anti-lightning technology, and has aircraft warning signal. It will not harm the ecology of the hill, said J K Jha, the engineer who designed the mast.Jha told TOI the flag is made of parachute cloth and has enough clippings to ensure strong winds do not blow it away. The mast sits on around nine feet diameter pedestal fitted with rock anchors.A 70-year-old Gopal Singh, a resident of Ratu Road, said he has heard tales of British cruelty atop the hill. "The fluttering tricolour has swelled the pride Independence has given us and our forefathers have worked hard to keep it unbroken," Singh, who watched the flag being hoisted, told TOI.The tricolour can be seen from most of the places in the town, especially tall structures.