text:
The Nebulous Kingdom
Homicides & Income Inequality
I just attended a day-long conference on the relationship between income inequality and social dysfunction. The most interesting findings were from Martin Daly and his work on homicide.
Essentially, Daly's argument is that homicide rates are strongly related to Darwinistic, or what he calls "ecological and economic," reasons. He showed some very compelling data, which I'll post if I can get the slides.
A summary of his findings:
Most killers are (young) males
Across countries, most killers are men. These men tend to kill other men, especially unrelated men. The main exceptions are countries where homicide is rare, the effect in these cases being that as male-on-male homicides decline, other types of homicides – which stay relatively constant – become more prominent. Male-on-unrelated-male killings make up the great majority of homicides and are also the most variable component of the homicide rate. Women, when they kill, do tend to kill other women, but relative to men, they are much less likely to commit homicides.
Daly believes that the reasons are tied to biology. Historically, compared to women, men had a higher likelihood of dying childless, higher maximum fitness (and higher variability in fitness), and greater association between social rank and their ability to reproduce. Together, this resulted in more same-sex competition and less deterrence by danger.
This argument is supported by the age graphs of men who kill unrelated men. Across nations, they look nearly identical, sharp almost-vertical cliffs between the ages of 14 and 24 with steep drop-offs after that age and descending throughout the average male life. Most killers are young males.
Men kill each other for competitive reasons
The most significant reason why men kill each other is social competition, in the form of a response to status challenge, rivalry over a women, or disrespect ("dissing").
The next most significant motive is material competition, in the form of robbery or business (e.g. drug) rivalry.
Risk factors for homicide
Daly believes that killers tend to be men who are so undeterred by danger that they'll risk their lives in competitive contests. In the words of Bob Dylan,"when you got nothin', you got nothin' to lose."
Unemployment is a sizable risk factor for being the perpetrator of homicide. Interestingly, unemployment is also a risk factor for being the victim of homicide, a possible explanation being that people tend to interact with others like them.
Being unmarried is another risk factor. That's specifically not married, meaning that even if you're in a serious relationship, you're still in the risky pool. The rate of homicide for men who become divorced and widowed returns to the unmarried rate.
Generally, the more inequitable men's access to "resources" (which apparently include child-bearing wives), the more dangerous disenfranchised men become.
A bit of math
Just in case you were wondering, inequality is calculated through the Gini coefficient of income inequality, which seems to be the gold standard for these things.
The equation is as follows:
Gini coefficient of income inequality = Area 1 / (Area 1 + Area2)
Where: the y-axis is the cumulative proportion of income from 0 to 1 and the x-axis is income units (households) arrayed from poorest to wealthiest. The line of perfect equality would be the straight y = x line, meaning that every household's income adds to the cumulative total some constant amount. The sum total of the area of the triangle Area 1 + Area 2 is the denominator. However, perfect equality never happening in the "wild," the Lorenz curve represents the reality of the distribution. The area between the line of perfect equality and the Lorenz curve becomes the numerator.
It's not income; it's income inequality
So you might be wondering, is it really an issue of inequality and status, or is it simply poverty and its ills at work? (This is what I was thinking.)
The data is quite compelling. The number-one predictor of homicide rates across 50 US states is income inequality (with an r = 0.72, for those of you who care about these things). Average income is not a predictor at all of homicide rates (r = -0.17). [By the way, if you would like to avoid being the victim of homicide, don't visit Louisiana and Mississippi. Go to North Dakota instead... though death by boredom is probably not that much more fun.]
But isn't there some correlation between poverty and inequality? Aren't poor states the most unequal?
There is some moderate correlation between poverty and inequality, but there's no reason it has to be so. Daly, who happens to be Canadian, then looked at Canadian provinces, where the poor provinces are the most equitable and the rich provinces are the most inequitable. Here, income inequality was still the main predictor of homicide rates (r = 0.82) across 10 provinces. Income was not at all a good predictor of the homicide rate; in fact, the lowest income provinces had the least homicides, arguably because they are the most equal.
When you combine Canada and US data, they fall into line -- though Canada generally has lower inequality and lower homicide rates, its worst provinces about on par with the best US states.
Culture doesn't seem to be a major factor
Some might ask, well, how about culture? Some cultures are just generally more war-like, even barbaric. You would expect to see a higher homicide rate there. Haven't cultural transmission dynamics broken the links between violence and the economic / ecological basis?
Well, let's look at the notoriously gun-toting U.S. South and their "culture of honor".
Southerners tend to:
Oppose gun control more
Favor death penalty more
Be more supportive of military spend
Approve of corporal punishment more
Be more lenient to wife-beaters
Show more sympathy to pleas of "provocation"
[R. Nisbett & D. Cohen (1996), Culture of Honor]
You would perhaps expect homicides in the South to be greater than the North, due, at least in part, to culture. However, when you plot the graph, "Southern" tendency to homicide actually becomes about income inequality (r = 0.725).
Daly believes that behaviors of low-status individuals are adaptive and economic, not just pathological. Cultures have a degree of inertia but they do change. Younger generations will reject the attitudes and values of their elders if, and only if, it makes sense. Homicide rates in the US, for instance, dropped 40 points (from 100) between 1990 and the present, far less than one generation. Dramatic change can happen relatively fast.
Some counterarguments…and their counter-counters
Nisbett (whose conclusion was that higher homicides in the South was due to path-dependent culture transmission that continued after the initial conditions no longer existed) objected to the inclusion of both black and white men in Daly's analysis. After all, there was so much complexity due to past slavery, current race relations and disparate income levels. However, when Daly restricted the analysis to white men, income inequality was still a strong predictor of homicides (r = 0.68), while income was not a predictor at all.
Another counterargument is that there has recently been a general upward monotonic trend in inequality in both the US and UK. At the same time, homicide rates in both nations have been on the decline. What gives?
Daly suggests that this is due to a demographic shift away from young males in both these nations with the aging population. As you might recall, killers tend to be young males. After the Gini coefficient for income inequality, the proportion of 15-34 year old men in the population is the best explanation for the residual variance. If you take a look at nations with higher income inequality, the decline in homicide rate due to changing demographics is not as steep as you would expect. Inequality essentially puts brakes on the some of the benefits of the demographic shift.
This is direct contradiction with Steven Levitt, who dismisses demographics as one of the reasons behind the decline in crime and focuses on other factors, including and notoriously, abortion. Daly suggested that a reduction in the number of young males should result in a more-than-linear drop in homicide rate. If you do the thought experiment of imagining a city where people are roaming around like little Brownian particles, and two men of a certain age need to bump into each other to result in a homicide, you would expect if you removed a sizable number of young males that dyadic interactions would be reduced more than linearly with the number of men removed.
There also may be cohort effects, meaning that the generation into which you are born has an impact on your later success in life (on average). For instance, studies have shown that large cohort size (such as the Boomer generation) affect the availability of work opportunity, the level of competitive intensity, and the general amount of adversity experienced by the average person within that cohort. It is plausible that young males in recent times, who were born into a smaller and therefore less competitive cohort, would generally commit homicides less as a group – especially when you consider that men tend to commit homicides for competitive reasons. In Japan, when you look at the total homicide data over age ranges, you would see the same peak for young males as other nations but a flatter, more gradual drop-off. But when you look at specific generations, you see a much sharper effect in all cohorts but which is more pronounced and taller (i.e. more homicides) for older pre-WWII generations. When you combine cohorts, the now older, more competitive cohorts create a deceptively flatter chart. In general, cohort effects offer another explanation for the recent divergence in homicide rates and income inequality.
Perhaps people who don't finish their antibiotics can feel less guilty:
Nobel Prize Laureate Kary Mullis says,
"When Alexander Fleming first discovered penicillin, his boss, Almoth Roth said bacteria would become resistant to it. It took longer than Roth thought, but it is happening...If you take penicillin, you excrete half of it. It goes down into the sewer in low, sub-clinical doses. It doesn't kill all the things in the sewer, but it definitely makes them start developing a resistance to penicillin. Most antibiotic resistance may not arise in our own bodies but elsewhere."
http://www.edge.org/documents/archive/edge315.html
Murdoch's Walls and Balls
Two of Rupert Murdoch's UK newspapers will be behind a paywall starting in June. I don't agree with everything that Jeff Jarvis has written on Murdoch (http://www.guardian.co.uk/commentisfree/2010/mar/26/rupert-murdoch-pathetic-paywall), least of all his description of the state of Murdoch's "balls" (or lack thereof), but I'm in consensus with him that Murdoch doesn't seem to fully grasp the economics of content on the web.
1. General news content is cheap
This is especially true in the United Kingdom, where you can pick up a rag at the tube for free. General news is widely duplicated and readily available through multiple Internet outlets.
2. People will still be willing to pay for content but only (and at the risk of sounding clichéd) high-quality content
I cannot stress the term high-quality enough. It seems sometimes that the average newspaperman believes that he is producing high-quality content. Not true. High-quality is a portion of the Economist, the New Yorker, the Wall Street Journal, and the New York Times.
Truly average news doesn't always provide value for the attention it gets, much less any incremental fees. Those papers will have to settle for the few advertising pennies they earn, the handful of paper subscriptions they'll get from people over the age of 50, and any government subsidies they can wangle (I hope not). Putting average content behind a paywall (ahem) is cutting your own throat.
3. You don't know what is high-quality until you read it – and by then it's too late to charge for it
People will only pay for content when they believe that it will be high-quality. The only way to ensure that is to have an established high-quality brand, of which there are truly very few (think the Economist), or to build such a brand by using "personalities" (think Paul Krugman) and/or giving away content.
A content business model based solely on "personalities" is unlikely to be lucrative, however, since the personalities, as owners of the scarce resource, will capture most of the value. Giving away content to build a brand has worked very well for niche content providers such as STRATFOR or John Mauldin, who keep selected content behind a paywall but give away a high proportion of their material. Their examples point the way for owners of a differentiated "expertise" or specialized arena to sell efficiently what they know into the market for knowledge. (This also opens up interesting possibilities for someone that can provide infrastructure for this growing tiny niche-content provider model.) It is still not completely clear, however, whether the content giveaway model can be lucrative in the mass-market.
4. User interface – micropayments or distribution channel - can help (but it's not the endgame)
If you make it easy for people to pay, there will be more people who are willing to pay. You show me a snippet that engages my interest and make it easy for me to pay a dime, perhaps I'll pay that dime. Easy is one-click, no login, no credit card number required, no visible third-party involved. Easy is harder to do than it looks. And you still have to engage my interest, which is getting harder to do with the flurry of socially mediated content coming my way.
Some newspapers with a credible brand will be able to take existing subscribers and move them onto a digital subscription on a Kindle-like device. Even with a generous estimate of 2 million Kindles sold (http://digitalbookworld.com/2010/how-many-kindles-have-really-been-sold/), that's still only 0.7% of the US population. This is a stopgap, not a business model.
5. The old models are going to be defunct (duh)
Look at the data:
http://www.naa.org/TrendsandNumbers/Advertising-Expenditures.aspx
In 2009, newspaper advertising revenues were at their lowest since 1995. You can blame it on the recession, but they peaked in 2004 and have been sliding ever since.
As a share of U.S. media advertising expenditures, the slide looks even worse, though I would take this with a grain of salt (a lot has happened since 1949):
http://www.niemanlab.org/images/Share-of-market-4908.PNG
Will all newspapers be dead? No. Is the model dying? Look around at the dinosaur carcasses.
What's left? Yikes. I hope a true re-imagining of the business model that takes into account the new economics and a return to quality "print" journalism. We will see.
Being Sick
It always starts with a general feeling of malaise. For someone who very rarely gets sick, there's a tendency to bluster your way through it. "I'm fine." "I never get sick." "I'm from pioneer stock." "I'm sure it's nothing." "I'm pretending it's not happening." "I'll suck it up." "Mommy."
We all know what it's like to get very sick. It is a horrific condition. How your whole world narrows in focus to this physical unwellness, and it throws into stark relief how little much else matters when your physical self is suffering. When it happens, it's a quick catapult off the mountain of Maslow's Hierarchy to land face-down at its base, breathless and aching. You go from pondering the social life of information to lying curled up in bed with your only wish just to be well. We always take for granted the is-ness (health) when it's been awhile since we've experienced the not-ness (not healthy).
Everyone who is not pathological wants to be well. We share this very basic need because of our common humanity. The corpus of human knowledge doesn't always have the tools to make us well. But sometimes it does. When we see others suffering and have the tools to alleviate the suffering, we have to make a decision on whether we will use them. What makes us human is our empathy for each other, especially when we know what it is like.
As a nation with limited resources, it is a hard choice to take away from one person and give to another. Or it should be a hard choice, one we don't make lightly. We said when this country was founded that every person was entitled to life, liberty and the pursuit of happiness. Different political parties might put a different spin on the interpretation, but I think the founders intended this as assurance that no one would take away our birthright, not that we would depend on government and the kindness of others for these entitlements. We are responsible for maintaining our birthright and no one else. Our happiness and very lives are bound up in our free will, in our ability to find spaces and create, to shape the trajectory of our own lives, to choose. Some people define poverty as the lack of choice.
So let us not fool ourselves – every time we take away from one person and give to another, we steal options from individuals. When we rob Peter to pay Paul, we shouldn't forget that Peter gets hijacked. There is a cost, a tradeoff. This is not frivolous. But if you do the thought experiment of closing your eyes and imagining a world with zero taxes, then 10% taxes, then 30% taxes, then 70% taxes, then 100% taxes – really, take that moment and ponder on the chaos of zero taxes and the enslavement of 100% taxes, and the relative miseries and enablements in-between – you'll understand that the conversation is not about the extremes but about that tradeoff. We forget this sometimes when we take a principled stance.
If nearly all people who get sick want to be well, if addressing sickness will cost an individual enormous amounts of money unexpectedly, if we as human beings have said that we must offer succor when we see others in a truly desperate state of suffering, then we need to come together and figure out how to share that risk. We don't always know who will get sick and how sick they will get. This is at the heart of why we have government in the first place. This is one of the millennia-old reasons why we are social creatures. Risk-sharing is why we began to live in groups.
We need to make hard decisions about what we will pay for and what will be left to the private sector, but we have to go beyond as well. Consider our creaky hulk of a health care system, a monster and a travesty. Imagine how inconvenient and unpleasant the average health-care interaction is, compared to, say, a trip to the Apple store or a purchase on Amazon. It burdens us all. Health care, like education, is not simple but should be administratively simple. We need to strip away all the barnacles that are not related to the business of providing the right care to the right patients in the right place in the least amount of time possible. We've solved much harder administrative problems in other arenas, e.g. Amazon, Dell, Southwest, Li & Fung. We have the foundational technology but we need to actually use it in the delivery of health care. We need to carefully unravel the tangled web of regulation that inhibits innovation; offer transparent, credible and understandable information to patients; streamline and standardize the currently shoddy business of diagnosis; use expensive doctors for specialized activities (e.g. surgery, specialty, rare conditions); provide data and tools to compare quality of care across providers; provide toolkits to patients to manage their own care (from home, if possible); restructure payment around health rather than services; and establish public metrics for everyone.
It's obvious that the recently passed health care reform is far from perfect. We have a ways to go to get from here to there. But where we were going was unsustainable and law-making has always been a shaky zig-zag of a walk. At least we are moving. Unfortunately, human beings tend to respond only to constraints and we are now facing constraints of gargantuan proportions.
Value Investing from GMO
http://www.simoleonsense.com/miguel-barbosa-interviews-james-montier-part-1-value-investing-tools-techniques-for-intelligent-investing/
Risk is not the same as volatility
"The idea that the risk of an investment, or indeed, a portfolio of investments can be reduced to a single number is utter madness. In essence, the problem with risk management is that is assumes that volatility equals risk. Nothing could be further from the truth. Volatility creates opportunity."
Reverse-engineer DCF to check implied growth rates
"This effectively takes the market price, and backs out the growth that would be required to justify the current price. I can then compare that implied growth against a historical distribution of all company growth rates over time and see whether there is any chance of that growth actually being achieved... I tend to use a three stage model, I use the analyst inputs for the first three years, and a trend GDP related growth rate for the terminal years, and then imply what the market implies for the middle period of growth.
For instance, at the moment the mining sector implies 12% growth p.a. each and every year for the next two decades! That is a cyclical sector with an implied growth rate double a generous estimate of nominal GDP growth. Cyclicals masquerading as growth stocks rarely end well for investors."
Think of risk as a trinity
"I don't think of risk as a number, but rather as a permanent impairment of capital (as Ben Graham put it). Now that permanent impairment can be generated by three potential sources (which aren't mutually exclusive). Firstly, there is valuation risk – you can simply overpay for an asset. Secondly, there is fundamental or business risk – something goes wrong with the underlying economics of the asset. Thirdly, financing risk or leverage (which no matter how hard you try can't make a bad investment good, but can make a good investment bad)."
Process is important
"Process is the one aspect of investing that we can control. Yet all too often we focus on outcomes rather than process. Yet ironically, the best way of getting good outcomes is to follow a sound process. The research shows that holding people accountable for outcomes tends to lead to suboptimal performance, generally because they spend all their time worrying about the things they can't control. I'd advise a far better approach to assess people on the criteria of adherence to process."
Here's his stock screen
"The stock must be cheap (with an earnings yield at least twice the AAA boind yield), it must be returning cash to shareholders (with a dividend yield of at least 2/3rds of the AAA bond yield), and it must have limited leverage (with total debt less than 2/3rds of tangible book value). I added one extra criterion, a Graham and Dodd PE (current price over a 10 year moving average of earnings) of less than 16x times. I added this is to prevent us from buying cyclicals which had enjoyed a short sharp run up in earnings, but didn't have sustainable earnings power."
Short-sellers act as our conscience
"Short sellers are amongst the most fundamental investors you'll come across. They understand the ins and outs of a business better than just about everyone else. They are highly skilled at figuring out poor economics when they see if. They act as acting police, helping to uncover fraud – something that the regulators used to do (a very long time ago). My own work on short selling has focused on a number of areas. In general, shorts tend to come into a couple of categories: bad businesses (i.e. poor economics), bad accounting (obvious), bad management (the guys at the top haven't got a clue). In addition I often look for several traits, such as expensive, unrealistic growth expectations, too much debt, and poor capital discipline (i.e. needless and tangential M&A).
I also created a measure called the C-score (C is for cheating or cooking the books). It aims to look for the quantitative red flags which often accompany bad accounting:
1. A growing difference between net income and cash flow from operations.
2. Day sales outstanding is increasing.
3. Growing days sales of inventory
4. Increasing other current assets to revenues.
5. Declines in depreciation relative to gross property plant and equipment.
6. High total asset growth."
Managers can be sociopaths
"There is some intriguing work arguing that many managers share a lot of traits with psychopaths (minus the violent tendencies). The checklist I use is...essentially a screen for narcissism, I'm trying to weed out those who are so caught up in their own self importance that they wouldn't see a problem coming even if [it bit] them on the ass."
Strategy in Game Theory
I've been reading an Matt Ridley's enlightening The Origins of Virtue, in which there's a long discussion on the logic of cooperation. For years now, I've thought that the Tit-for-Tat strategy from Robert Axelrod's tournament represented the best strategy. Essentially Tit-for-Tat is: you begin by cooperating but are quick to retaliate if the other person defects, and then you revert back to cooperating.
As Axelrod says, "What accounts for Tit-for-tat's robust success is its combination of being nice, retaliatory, forgiving and clear. Its niceness prevents it from getting into unnecessary trouble. Its retaliation discourages the other side from persisting whenever defection is tried. Its forgiveness helps restore mutual cooperation. And its clarity makes it intelligible to the other player, thereby eliciting long-term cooperation."
In a world with a mix of strategies and at least a few people playing Tit-for-Tat, Tit-for-Tat will always beat the consistently evil. It is also worthy to note that Tit-for-Tat only makes sense in a series of games, and that in a single game, it fails against "nasty" strategies. Given that we happen to live in a world with a time dimension, though, this seems to be a somewhat academic point.
The dark side of Tit-for-Tat, as Ridley notes in his book, is that if two players operating under Tit-for-Tat meet each other, and one of them accidentally defects, then a continuous series of mutual recriminations begins from which there is no escape. This is how blood feuds start and why they never end. So Tit-for-Tat was discovered to be not evolutionarily stable.
Martin Nowak designed a new tournament where nothing was certain and everything was statistically driven, including 'random' mistakes and tactics. The system could 'learn,' evolving over time. In this world, a new strategy prevailed called Generous-Tit-for-Tat. Generous will randomly forgive single mistakes one-third of the time. To forgive all single defections (called Tit-for-Two-Tats) is to invite exploitation, but to do it randomly broke cycles of recrimination. So Generous could beat Tit-for-Tat - but Novak then discovered that Generous could be beat by nicer strategies, but then these strategies could be beat by the perfectly cooperative strategy, which in turn could be beat by the perfectly nasty strategy. So this was not evolutionarily stable either.
Eventually, Karl Sigmund and Martin Nowak came upon the Pavlov strategy, which essentially meant that when the player wins, he continues behaving the same; when the player loses, he shifts tactics. It's also called the Win-Stay, Lose-Shift. Essentially, you don't change until something is wrong. Pavlov builds cooperation, tends to punish when partners defect, and then forgives. But it also screws naive suckers by defecting (and winning) consistently. So 'it creates a cooperative world, but doesn't allow that world to decay into a too-trusting Utopia where free-riders can flourish.' In a learning world, Pavlov is evolutionarily stable.
It makes me wonder about what lessons there are to be learned here about the stability of different political systems. Communism's principles are close to the 'perfectly cooperative' strategy. But it is beat easily by an invasion of the 'perfectly nasty' strategy of tyranny. If you agree that capitalism is like the Tit-for-Tat strategy, then it can be highly effective but is dominated by more cooperative strategies. Ridley implies, however, that Tit-for-Tat, by doing a effective job of punishing, demolishes nasty strategies and clears the way for nicer (but not naive) strategies to dominate. So basically, you should be as nice as you can possibly be without inhibiting feedback and learning.
Response from Josh Buckholtz (see post on Sociopaths and Psychopaths)
"Thanks for your interest in our work. Your idea about environmental alteration of dopamine function by early life trauma is very interesting. While we know that both genes and environment both play a strong – and interacting — role in predisposing antisocial behavior, very little is known about how genes and environment affect the brain to bring about psychopathy. There is some work in animals suggesting that stressful events occurring early in life affect the dopamine system, but its not yet known if these effects meaningfully relate to actual human behavioral disorders. This is a question that's being actively pursued in our and others labs, so hopefully we'll have some insight in the future!
Thanks very much for your question.
Josh"
Sociopaths and Psychopaths
I've lately become interested in sociopathy. A strange interest you might say. For a long time now, though, I've been noodling over the quality of empathy. We are biologically wired for it with von Economo mirror neurons in our brain, which are the basis for emotional imagination (http://www.smithsonianmag.com/science-nature/The-Social-Brain.html). These neurons allow us to learn from the experiences from others, literally feeling what they feel (or what we think they feel). To be able to get the lessons without making the mistakes is a huge evolutionary advantage. From a business standpoint, empathy with your customers helps you sell better, and empathy with your employees makes you a better manager. Many belief systems have a Golden Rule-like dictum - "Do unto others as you would have them do unto you." Philosophically, I believe that empathy is the basis of our humanity. In a sense, I wasn't born human, I became human. Or more accurately, I am always becoming human.
Sociopaths have an extremely low level of empathy by definition, far on the end of the scale. Not all sociopaths are serial murderers. They do tend to be manipulative, however, seeing other people as part of a system to be optimized. Some, however, do become psychopaths. According to one study (which I can't find right now but will link to if I can dig it up), psychopathic behavior is driven by both genetic predisposition to sociopathy and environmental factors such as childhood abuse. From what I can recall, the paper said that genetic or environmental factors alone don't explain psychopathic behavior in the data - psychopathic behavior requires the combination of the two.
Then I saw this article:
http://futurity.org/top-stories/psychopaths-brains-seek-rewards-at-all-costs/
Excerpt: "We found that a hyper-reactive dopamine reward system may be the foundation for some of the most problematic behaviors associated with psychopathy, such as violent crime, recidivism, and substance abuse."
According to this article, it seems that the wiring of the dopamine system can be modified through environmental factors, such as substance abuse. It made me think: Is it possible that the dopamine system of psychopaths has been altered by a consistent pattern of abuse or trauma, that, when combined with genetic factors result in psychopathic behavior? Perhaps the body is responding to abuse or trauma by increasing the amount of dopamine, as a survival tactic.
I don't know the answer but I sent an email to Joshua Buckholtz, who did the research. Will post if he responds.
In a world of massive externalities..
There's a term used in philosophy and social psychology - "positivist" - which, according to Wikipedia, is a perspective which "holds that the only authentic knowledge is that which is based on sense experience and positive verification." This perspective is obviously aligned with the principles of science and has held sway throughout the twentieth century.
Today positivism is considered in the halls of social science as narrow, limited and really a bit antiquated. So I find myself and my modes of thinking a bit antiquated, since I can't manage to subscribe to deconstructionism, postmodernism and the host of other –isms that have taken over. I understand their impetus but not their usefulness.
And I wonder whether it is time for a new perspective, one that can encompass the vast amount of uncertainty we face, in a "real" as well as emotional, psychological and social sense, while being of use in navigating the world and our lives.
I think of this in the context of externalities, or referring back to Wikipedia, spillovers of an economic transaction that have "an impact on a party that is not directly involved in the transaction." I had a pretty good foundational education in mainstream "freshwater" economics, one based on theory and models and which would be considered quite positivist. In mainstream economics, externalities tend to be a side topic that is often assumed away as minor or localized. Nowadays, however, externalities seem – well, important. If you look at some of the arenas where the United States is failing miserably relative to socialized nations, i.e. non-university education, health care, environmental issues, these all have sizable externalities. Socialized systems have made implicit decisions about what negative externalities are untenable and instituted a policy net of seemingly minor moral hazards. When negative externalities become so large as to be untenable, such as the systemic failure of the financial system, then we institute moral hazard in the form of bailouts. And then we try to install a morass of regulation to mitigate the moral hazard we've created, likely triggering - in a host of ways we've yet to discover – the Law of Unintended Consequences.
The intertwining of the global financial system is perhaps just an example and a metaphor for an even larger trend towards interconnection and increasing externalities. After all, as we live more closely in urban mega-cities and interact more regularly over the internet and web-enabled mobile devices, it makes sense that both positive and negative externalities – that is, the impact of transactions on parties outside those transactions – would increase. In this world, the price mechanism fails more often. Our models fail more often. In this world of increasing uncertainty, where positive verification isn't to be had, the positivist view seems less useful. This is important - once externalities gets to a certain level, it seems inevitable that our society will try to gain greater control of its constituents, to avoid inflicting the social cost of negative externalities or incent behavior which results in positive externalities. This points to a trend towards greater regulation and loss of individual liberty.
Unless – we can think of a new way of looking at things, a mechanism to complement the price mechanism when it fails. Some have suggested a reputation mechanism, though we haven't attained the level of connectedness and transparency to make this efficacious. We should perhaps start thinking about this though…
I'm interested in uncertainty, time, trust, consistency, strategy, economics, empathy, philosophy, education, technology, story-telling, and fractals.
Subscribe gently by email
My Favorite Curators
Edge.org
STRATFOR
Futurity.org
Domain-B.com
FORA.tv
PopTech!
PIMCO Investment Outlooks
GMO Client Reports
Someecards.com
MRN Research Papers
Chicago Booth eNewsletters
McKinsey Quarterly
Boldtype / Artkrush
Chicago Booth Podcast
The Atlantic Council
TED.com
The Ideas Project
Long Now Foundation
Oaktree Capital Memos
LSE Public Lectures
Bubblegeneration
NetAge
John Seely Brown
John Hagel
HBR – The Big Shift
LookBook.nu
Frontline PBS
Royal Society for the Arts
Best of Craigslist
Texts from Last Night
FMyLIfe
MyLifeisAverage
Lamebook


text:
Beautiful Corals in Home Aquariums Can Poison You
By Rachael Rettner 13 August 2015
(Image: © Marius Meyer/Shutterstock.com)
Aquarium enthusiasts and people who work in aquarium stores should be aware that some types of coral produce dangerous toxins that can be hazardous to your health, according to a new report.
The report, from the Centers for Disease Control and Prevention, describes 10 cases of toxin poisoning in Alaska between 2012 and 2014 that were linked to zoanthid corals, a common type of coral in home aquariums. Some zoanthid contain high levels of palytoxin, a toxin that can cause life-threatening symptoms if people touch, inhale or ingest it, the CDC said.
"Many aquarium store employees and marine aquarium hobbyists are not aware of palytoxin as a potentially serious hazard associated with handling some zoanthid corals," the report said. "General recommendations on coral handling and decontamination practices would be helpful for hobbyists, commercial coral growers, and the public health and clinical provider communities." [Images: Colorful Corals of the Deep Barrier Reef]
Public health officials in Alaska began an investigation into toxin poisoning after a man was hospitalized — and two of his housemates experienced serious symptoms — following the introduction of zoanthid corals into their home aquarium. The patients had fever, weakness, cough and muscle pain, and a reported a bitter metallic taste in the mouth. All three patients recovered within two days.
Although none of the patients had direct contact with the coral, they appear to have inhaled the toxin, the researchers said. The toxin could have been released when some of the coral polyps broke off during the transfer of the coral to the aquarium. The corals can also produce aerosolized toxins when people use hot water or scrub to remove zoanthids from tanks, the researchers said.
The store that sold the patients their coral also reported that multiple staff members had experienced similar symptoms in the recent past, including a metallic taste, cough, joint pain, flank pain, fever and feeling cold during the night. One staff member said he or she had experienced symptoms of toxin poisoning nine times.
The shop owner also told health officials that in 2012, a man and his pregnant wife were hospitalized after the husband cleaned a fish tank with zoanthids. Although the wife did not help with the cleaning, she walked by the area several times. The couple were in the intensive care unit for several days. The wife delivered her baby, but the infant was three months premature. The child survived, and did not appear to suffer from adverse health effects, although the husband reported that he still had lung problems two years later, the report said.
The toxin from zoanthids can be neutralized by soaking the coral for 30 minutes in household bleach and water. In addition, contaminated items should be soaked in diluted bleach before disposal, the report said. Activities that could produce aerosols should be undertaken with caution, they said. When decontaminating areas that may have been exposed to the toxin, patients were advised to use protective equipment, including a face mask, goggles and overalls.
The study was published in the Aug. 14 issue of the CDC journal Morbidity and Mortality Weekly Report.
Follow Rachael Rettner @RachaelRettner. Follow Live Science @livescience, Facebook & Google+. Original article on Live Science.
Woman's garden 'stepping stone' turns out to be an ancient Roman artifact

redpajama_set_name: RedPajamaCommonCrawl


text:
Q: Recall arbitrary positional argument I'm trying to recall an argument based on another, i.e.
\newcommand{\switchtwo}[3]{#(#3)}

should return #1 if the third argument is 1 and #2 if the third argument is 2. Is there any way to do this?

A: You can build an internal command of the right form
\documentclass{article}

\def\switchtwo#1#2#3{%
\def\tmp##1##2{###3}%
\tmp{#1}{#2}}

\usepackage[T1]{fontenc}

\begin{document}

\switchtwo{aaa}{bbb}{1}

\switchtwo{\string\or}{\string\fi}{2}

\end{document}

A: \newcommand{\switchtwo}[3]{#(#3)}— The syntax you have in mind implies the possibility of using #⟨whatsoever⟩ for "dynamically" denoting arguments of a macro at times when that macro is expanded.
This is not possible in (La)TeX:
Only at the time of defining a macro you can use #1 and #2 etc for denoting its parameters.
Denoting one of its arguments by #⟨whatsoever⟩ at the time of expanding is not possible.
At the time of expanding, the ⟨parameter-text⟩ of a macro's definition is taken for a set of directives for one by one gathering arguments from the token-stream:
When expansion of \switchto takes place, LaTeX gathers the arguments from the token-stream: First it gathers from the token-stream that argument/that set of tokens that is denoted by the definition-text's parameter #1. Then it gathers from the token-stream that argument/that set of tokens that is denoted by the definition-text's parameter #2.  Then it gathers from the token-stream that argument/that set of tokens that is denoted by the definition-text's parameter #3. Then it inserts these sets of tokens into the replacement-text which it returns to the token-stream.
What can you do in LaTeX?
David Carlisle showed in his answer how to use  ##⟨whatsoever⟩ within the definition-text of a macro for "dynamically denoting" one of the arguments of another macro, a temporary macro, at the time of defining that other/temporary macro.
Approaches focused at defining temporary macros cannot be used in expansion-contexts.
Other possibilities (that can be used in expansion-contexts as well) are:
As long as it is ensured that the third argument is a ⟨number⟩ in the sense of The TeXbook—the precise meaning of the quantity ⟨number⟩ is discussed in The TeXbook, Chapter 24: Summary of vertical mode —, you can probably do something like this:
\documentclass{article}

\makeatletter
\newcommand{\switchtwo}[3]{%
  \romannumeral0\ifnum\number\number0#3=1 \expandafter\@firstoftwo\else\expandafter\@secondoftwo\fi
  {\expandafter\@firstoftwo\@secondoftwo}{%
    \ifnum\number\number0#3=2 \expandafter\@firstoftwo\else\expandafter\@secondoftwo\fi
    {\expandafter\@secondoftwo\@secondoftwo}%
    {\@firstoftwo}%
  }%
  { Error: Arg 3 is neither 1 nor 2}{{ #1}{ #2}}%
}%
\makeatother

\begin{document}

\switchtwo{A}{B}{1}

\switchtwo{A}{B}{2}

\switchtwo{A}{B}{3}

\switchtwo{A}{B}{}

\hrulefill

\newcounter{foobar}

\setcounter{foobar}{1}%
\switchtwo{A}{B}{\number\value{foobar}}

\setcounter{foobar}{2}%
\switchtwo{A}{B}{\number\value{foobar}}

\setcounter{foobar}{3}%
\switchtwo{A}{B}{\number\value{foobar}}

\end{document}

In the example above \romannumeral0... is not used for obtaining the roman-numeral-representation of a number. \romannumeral0... is used for triggering a lot of expansion-work during the search for more digits or a space-token that will be discarded as it just terminates the digit-sequence and therefore also terminates the search for more digits. It is ensured that after all this expansion-work a space-token is found, which terminates the digit-sequence 0. Therefore after all the expansion-work a non-positive number is found while \romannumeral will silently swallow non-positive numbers without returning any tokens at all.
Be aware that a reliable test whether an arbitrary token sequence in \switchtwo's third argument forms a valid ⟨number⟩ in the sense of The TeXbook is not feasible:
An arbitrary token sequence might form an arbitrary expansion-based algorithm. Therefore such a test includes testing whether the result of an arbitrary expansion-based algorithm forms a valid ⟨number⟩ in the sense of The TeXbook. This in turn implies testing whether an arbitrary expansion-based algorithm terminates at all (without error-messages). This in turn implies solving the halting problem. Alan Mathison Turing proved in 1936 that a general algorithm to solve the halting problem for all possible program-input pairs does not exist.

In case you prefer checking whether the set of tokens contained in \switchto's third argument (without whatsoever expansion/evaluation) consists either exactly of the catcode-12-(other)-character-token 1 or exactly of the catcode-12-(other)-character-token 2 or of something else, this can be done by means of delimited arguments:
\documentclass{article}

\makeatletter
%%-----------------------------------------------------------------------------
%% Check whether argument is empty:
%%.............................................................................
%% \UD@CheckWhetherNull{<Argument which is to be checked>}%
%%                     {<Tokens to be delivered in case that argument
%%                       which is to be checked is empty>}%
%%                     {<Tokens to be delivered in case that argument
%%                       which is to be checked is not empty>}%
%%
%% The gist of this macro comes from Robert R. Schneck's \ifempty-macro:
%% <https://groups.google.com/forum/#!original/comp.text.tex/kuOEIQIrElc/lUg37FmhA74J>
\newcommand\UD@CheckWhetherNull[1]{%
  \romannumeral0\expandafter\@secondoftwo\string{\expandafter
  \@secondoftwo\expandafter{\expandafter{\string#1}\expandafter
  \@secondoftwo\string}\expandafter\@firstoftwo\expandafter{\expandafter
  \@secondoftwo\string}\@firstoftwo\expandafter{} \@secondoftwo}%
  {\@firstoftwo\expandafter{} \@firstoftwo}%
}%
%%-----------------------------------------------------------------------------
%% \UD@DigitFork{<Argument which is to be checked>}%
%%              {<Tokens to be delivered in case that argument
%%                which is to be checked is formed by a set of
%%                tokens which contains only the catcode-12-character 1>}%
%%              {<Tokens to be delivered in case that argument
%%                which is to be checked is formed by a set of
%%                tokens which contains only the catcode-12-character 2>}%
%%              {<Tokens to be delivered in case that argument
%%                which is to be checked is formed by a set of
%%                tokens which is empty or contains something else>}%
%%
\@ifdefinable\UD@GobbleToExclam{\long\def\UD@GobbleToExclam#1!{}}%
\@ifdefinable\UD@DigitSelect{\long\def\UD@DigitSelect#1!!1!2!#2#3!!!!{#2}}%
\newcommand\UD@DigitFork[4]{%
  \expandafter\UD@CheckWhetherNull\expandafter{\UD@GobbleToExclam#1!}{%
    \UD@DigitSelect
    !#1!1!2!{#4}% empty
    !!#1!2!{#2}% 1
    !!1!#1!{#3}% 2
    !!1!2!{#4}% something else without !
    !!!!%
  }{#4}% something else with !
}%
%%-----------------------------------------------------------------------------
%% \switchto
\newcommand\switchtwo[3]{%
  \romannumeral0\UD@DigitFork{#3}{ #1}{ #2}{ Error: Arg 3 is neither 1 nor 2}%
}%
\makeatother

\begin{document}

\switchtwo{A}{B}{1}

\switchtwo{A}{B}{2}

\switchtwo{A}{B}{3}

\switchtwo{A}{B}{}

\hrulefill

Be aware that this variant of \verb|\switchto| does not evaluate its third argument
and that the token-set \verb|\number\value{foobar}| in any case neither does
equal the token \texttt{1$_{12}$} nor does equal the token \texttt{2$_{12}$}:

\newcounter{foobar}

\setcounter{foobar}{1}%
\switchtwo{A}{B}{\number\value{foobar}}

\setcounter{foobar}{2}%
\switchtwo{A}{B}{\number\value{foobar}}

\setcounter{foobar}{3}%
\switchtwo{A}{B}{\number\value{foobar}}

\end{document}

By the way:
None of the tests presented in this answer defines temporary macros.
Therefore the tests presented in this answer are suitable for expansion-contexts also.
E.g., you can do things like \csname @\switchtwo{first}{second}{1}oftwo\endcsname{first}{second}.
With the tests presented in this answer, the placement of the first and second argument of \switchtwo is done in a way where unbalanced \csname/\endcsname/\if.../\or/\else/\fi in the arguments don't disturb.
E.g., you can do things like \csname @\switchtwo{\ifx AA}{\ifx AB}{1}first\else second\fi oftwo\endcsname{first}{second}.
But be aware that brace/group-nesting is independent from \if....\else..\fi-matching and that therefore such things can disturb the \if....\else..\fi-matching of surrounding \if....\else..\fi-constructs.

A: You can use \ifcase:
\newcommand{\switchtwo}[3]{%
  \ifcase#3 \or#1\or#2\fi
}

The macro will return nothing if the third argument is neither 1 nor 2, but you'll get errors or garbage if the third argument is not an integer.
Your idea can't work, because the positional arguments in a definition are stored in a special way and you can't mix the replacement text with them.

A: Your question is about selecting some arguments.
The question can be considered a special case of the question of selecting the Kth argument from L consecutive non-delimited arguments.
In case you are interested in that, I can offer an expandable routine \KeepKthOfLArguments which lets you do that.
\documentclass[a4paper, landscape]{article}

\makeatletter
%%=============================================================================
%% Layout of this example:
%%=============================================================================
\pagestyle{plain}%
\@ifundefined{pageheight}{}{\pageheight=\paperheight}%
\@ifundefined{pdfpageheight}{}{\pdfpageheight=\paperheight}%
\@ifundefined{pagewidth}{}{\pagewidth=\paperwidth}%
\@ifundefined{pdfpagewidth}{}{\pdfpagewidth=\paperwidth}%
\oddsidemargin=1.5cm
\topmargin=\oddsidemargin
\textwidth=\paperwidth
\advance\textwidth-2\oddsidemargin
\marginparsep=.375cm
\marginparwidth=\oddsidemargin
\advance\marginparwidth-2\marginparsep
\advance\oddsidemargin-1in
\evensidemargin=\oddsidemargin
\headheight=0ex
\headsep=0ex
\textheight=\paperheight
\advance\textheight-2\topmargin
\footskip=.5\topmargin
\advance\footskip.5\ht\strutbox
\advance\topmargin-1in
%%-----------------------------------------------------------------------------
\makeatother

\makeatletter
%% Code for \KeepKthOfLArguments:
%%=============================================================================
%% Paraphernalia:
%% \UD@firstoftwo, \UD@secondoftwo, \UD@PassFirstToSecond, \UD@CheckWhetherNull
%%=============================================================================
\newcommand\UD@firstoftwo[2]{#1}%
\newcommand\UD@secondoftwo[2]{#2}%
\newcommand\UD@PassFirstToSecond[2]{#2{#1}}%
%%-----------------------------------------------------------------------------
%% Check whether argument is empty:
%%.............................................................................
%% \UD@CheckWhetherNull{<Argument which is to be checked>}%
%%                     {<Tokens to be delivered in case that argument
%%                       which is to be checked is empty>}%
%%                     {<Tokens to be delivered in case that argument
%%                       which is to be checked is not empty>}%
%%
%% The gist of this macro comes from Robert R. Schneck's \ifempty-macro:
%% <https://groups.google.com/forum/#!original/comp.text.tex/kuOEIQIrElc/lUg37FmhA74J>
\newcommand\UD@CheckWhetherNull[1]{%
  \romannumeral0\expandafter\UD@secondoftwo\string{\expandafter
  \UD@secondoftwo\expandafter{\expandafter{\string#1}\expandafter
  \UD@secondoftwo\string}\expandafter\UD@firstoftwo\expandafter{\expandafter
  \UD@secondoftwo\string}\expandafter\expandafter\UD@firstoftwo{ }{}%
  \UD@secondoftwo}{\expandafter\expandafter\UD@firstoftwo{ }{}\UD@firstoftwo}%
}%
%%=============================================================================
%% Keep only the K-th of L consecutive undelimited arguments.
%%   ( IF K < 1 OR K > L just remove L consecutive undelimited arguments. )
%%=============================================================================
%% \KeepKthOfLArguments{<integer number K>}%
%%                     {<integer number L>}%
%%                     <sequence of L consecutive undelimited arguments>
%%
%% If L < 1 yields nothing.
%% Else:
%%   If K >= 1 and K < L  yields:
%%     <K-th undelimited argument from <sequence of L consecutive undelimited
%%      arguments>>
%%   If K < 1 or K > L
%%     (-> there is no K-th argument in the
%%         <sequence of L consecutive undelimited arguments> )
%%   yields nothing  but removal of <sequence of L consecutive
%%          undelimited arguments>
\newcommand\KeepKthOfLArguments[2]{%
  \romannumeral0%
  % #1: <integer number K>
  % #2: <integer number L>
  \expandafter\UD@KeepKthOfLArgumentsKSmallerOneFork
  \expandafter{\romannumeral\number\number#1 000\expandafter}%
  \expandafter{\romannumeral\number\number#2 000}%
}%
%%-----------------------------------------------------------------------------
\newcommand\UD@KeepKthOfLArgumentsKSmallerOneFork[2]{%
  % #1: <K letters m>
  % #2: <L letters m >
  \UD@CheckWhetherNull{#1}{% K is smaller than one:
    \UD@KeepKthOfLArgumentsRemoveNArguments{#2}{ }{}%
  }{% K is not smaller than one:
    \expandafter\UD@PassFirstToSecond
    \expandafter{%
      \UD@firstoftwo{}#1%
    }{%
      \UD@KeepKthOfLArgumentsEvaluateLMinusKDifferenceLoop{#1}{#2}%
    }{#2}%
  }%
}%
%%-----------------------------------------------------------------------------
\newcommand\UD@KeepKthOfLArgumentsEvaluateLMinusKDifferenceLoop[4]{%
  % #1: <K letters m>
  % #2: <L letters m>
  % (For detecting whether K>L or K<=L, during the loop letters m will
  %  be removed both from #1 and #2 until at least one of these arguments
  %  is empty.
  %  When the loop terminates with 0<K<=L, #1 will be empty and #2
  %  will hold an amount of letters m corresponding to the the
  %  difference L-K.
  %  When the loop terminates with K>L, #1 will not be empty and #2
  %  will be empty.
  % )
  % #3: <K-1 letters m>
  % #4: <L letters m>
  % (#3 and #4 will be left untouched during the loop so they can be
  %  used for performing appropriate action when loop terminates as
  %  it is known whether K>L.)
  \UD@CheckWhetherNull{#1}{% We have K<=L:
     \UD@KeepKthOfLArgumentsRemoveNArguments{%
       #3%
      }{%
       \UD@KeepKthOfLArgumentsRemoveNArguments{#2}{ }%
      }{}%
  }{%
    \UD@CheckWhetherNull{#2}{% We have K>L:
      \UD@KeepKthOfLArgumentsRemoveNArguments{#4}{ }{}%
    }{% We don't know yet whether K<=L or K>L, thus remove letters m and
      % do another iteration:
      \expandafter\UD@PassFirstToSecond
      \expandafter{%
        \UD@firstoftwo{}#2%
      }{%
        \expandafter\UD@KeepKthOfLArgumentsEvaluateLMinusKDifferenceLoop
        \expandafter{%
          \UD@firstoftwo{}#1%
        }%
      }{#3}{#4}%
    }%
  }%
}%
%%-----------------------------------------------------------------------------
%% \UD@KeepKthOfLArgumentsRemoveNArguments{<N letters m>}%
%%                                        {<argument 1>}%
%%                                        {<argument 2>}%
%%                                        <sequence of consecutive
%%                                         undelimited arguments>
%%.............................................................................
%% Removes the first N undelimited arguments from the <sequence of
%% consecutive undelimited arguments>, then inserts
%% <argument 1><argument 2>
%%
%% On the one hand when providing <argument 2> empty, you can use
%% <argument 1> for nesting calls to \UD@KeepKthOfLArgumentsRemoveNArguments.
%% On the other hand you can provide a <space token> for stopping
%% \romannumeral-expansion as  <argument 1> and have the
%% macro grab the <K-th undelimited argument> from the <sequence of L
%% consecutive undelimited arguments> as <argument 2>.
%%
\newcommand\UD@KeepKthOfLArgumentsRemoveNArguments[3]{%
  %% #1: <N letters m>
  %% #2: <Argument 1>
  %% #3: <Argument 2>
  \UD@CheckWhetherNull{#1}{#2#3}{%
    \UD@firstoftwo{%
      \expandafter\UD@KeepKthOfLArgumentsRemoveNArguments
      \expandafter{%
        \UD@firstoftwo{}#1%
      }{#2}{#3}%
    }%
  }%
}%
%%-----------------------------------------------------------------------------
%% End of code for \KeepKthOfLArguments.
\makeatother

\begin{document}
\footnotesize

\noindent\texttt{%
  \string\KeepKthOfLArguments\allowbreak\{1\}\allowbreak\{30\}\allowbreak\{Word 1\}\allowbreak\{Word 2\}%
  \allowbreak\{Word 3\}\allowbreak\{Word 4\}\allowbreak\{Word 5\}\allowbreak\{Word 6\}\allowbreak\{Word 7\}%
  \allowbreak\{Word 8\}\allowbreak\{Word 9\}\allowbreak\{Word 10\}\allowbreak\{Word 11\}\allowbreak\{Word 12\}%
  \allowbreak\{Word 13\}\allowbreak\{Word 14\}\allowbreak\{Word 15\}\allowbreak\{Word 16\}\allowbreak\{Word 17\}%
  \allowbreak\{Word 18\}\allowbreak\{Word 19\}\allowbreak\{Word 20\}\allowbreak\{Word 21\}\allowbreak\{Word 22\}%
  \allowbreak\{Word 23\}\allowbreak\{Word 24\}\allowbreak\{Word 25\}\allowbreak\{Word 26\}\allowbreak\{Word 27\}%
  \allowbreak\{Word 28\}\allowbreak\{Word 29\}\allowbreak\{Word 30\}%
} yields:
\KeepKthOfLArguments{1}{30}{Word 1}{Word 2}{Word 3}{Word 4}{Word 5}{Word 6}%
                           {Word 7}{Word 8}{Word 9}{Word 10}{Word 11}{Word 12}%
                           {Word 13}{Word 14}{Word 15}{Word 16}{Word 17}{Word 18}%
                           {Word 19}{Word 20}{Word 21}{Word 22}{Word 23}{Word 24}%
                           {Word 25}{Word 26}{Word 27}{Word 28}{Word 29}{Word 30}%

\newcount\loopcnt
\loopcnt=2 %
\loop
  \vskip\partopsep\vskip\topsep
  \noindent\texttt{%
    \string\KeepKthOfLArguments\allowbreak\{\number\loopcnt\}\allowbreak\{30\}\allowbreak\{Word 1\}\allowbreak\{Word 2\}%
    \allowbreak\{Word 3\}\allowbreak\{Word 4\}\allowbreak\{Word 5\}\allowbreak\{Word 6\}\allowbreak\{Word 7\}%
    \allowbreak\{Word 8\}\allowbreak\{Word 9\}\allowbreak\{Word 10\}\allowbreak\{Word 11\}\allowbreak\{Word 12\}%
    \allowbreak\{Word 13\}\allowbreak\{Word 14\}\allowbreak\{Word 15\}\allowbreak\{Word 16\}\allowbreak\{Word 17\}%
    \allowbreak\{Word 18\}\allowbreak\{Word 19\}\allowbreak\{Word 20\}\allowbreak\{Word 21\}\allowbreak\{Word 22\}%
    \allowbreak\{Word 23\}\allowbreak\{Word 24\}\allowbreak\{Word 25\}\allowbreak\{Word 26\}\allowbreak\{Word 27\}%
    \allowbreak\{Word 28\}\allowbreak\{Word 29\}\allowbreak\{Word 30\}%
  } yields:
  \KeepKthOfLArguments{\number\loopcnt}{30}{Word 1}{Word 2}{Word 3}{Word 4}{Word 5}{Word 6}%
                             {Word 7}{Word 8}{Word 9}{Word 10}{Word 11}{Word 12}%
                             {Word 13}{Word 14}{Word 15}{Word 16}{Word 17}{Word 18}%
                             {Word 19}{Word 20}{Word 21}{Word 22}{Word 23}{Word 24}%
                             {Word 25}{Word 26}{Word 27}{Word 28}{Word 29}{Word 30}%
  \par
\ifnum\loopcnt<30 \advance\loopcnt by 1 %
\repeat

\vskip\partopsep\vskip\topsep
\noindent\verb|\KeepKthOfLArguments| does deliver the result after two
expansion-steps:

\begin{verbatim}
\expandafter\expandafter\expandafter\def
\expandafter\expandafter\expandafter\test
\expandafter\expandafter\expandafter{%
  \KeepKthOfLArguments{3}{11}{A}{B}{C}{D}{E}{F}{G}{H}{I}{J}{K}%
}%
\end{verbatim}

\expandafter\expandafter\expandafter\def
\expandafter\expandafter\expandafter\test
\expandafter\expandafter\expandafter{%
  \KeepKthOfLArguments{3}{11}{A}{B}{C}{D}{E}{F}{G}{H}{I}{J}{K}%
}%
\noindent\texttt{\string\test: \meaning\test}%

\end{document}

Using the routine \KeepKthOfLArguments you could define \switchtwo as follows:
\newcommand\switchtwo[3]{\KeepKthOfLArguments{#3}{2}{#1}{#2}}%

redpajama_set_name: RedPajamaStackExchange


text:
SUBTITLE IV
SUBCHAPTER II
§ 5318A
31 U.S. Code § 5318A - Special measures for jurisdictions, financial institutions, international transactions, or types of accounts of primary money laundering concern
(a) International Counter-Money Laundering Requirements.—
(1) In general.—
The Secretary of the Treasury may require domestic financial institutions and domestic financial agencies to take 1 or more of the special measures described in subsection (b) if the Secretary finds that reasonable grounds exist for concluding that a jurisdiction outside of the United States, 1 or more financial institutions operating outside of the United States, 1 or more classes of transactions within, or involving, a jurisdiction outside of the United States, or 1 or more types of accounts is of primary money laundering concern, in accordance with subsection (c).
(2) Form of requirement.—The special measures described in—
subsection (b) may be imposed in such sequence or combination as the Secretary shall determine;
paragraphs (1) through (4) of subsection (b) may be imposed by regulation, order, or otherwise as permitted by law; and
subsection (b)(5) may be imposed only by regulation.
(3) Duration of orders; rulemaking.—Any order by which a special measure described in paragraphs (1) through (4) of subsection (b) is imposed (other than an order described in section 5326)—
shall be issued together with a notice of proposed rulemaking relating to the imposition of such special measure; and
may not remain in effect for more than 120 days, except pursuant to a rule promulgated on or before the end of the 120-day period beginning on the date of issuance of such order.
(4) Process for selecting special measures.—In selecting which special measure or measures to take under this subsection, the Secretary of the Treasury—
shall consult with the Chairman of the Board of Governors of the Federal Reserve System, any other appropriate Federal banking agency (as defined in section 3 of the Federal Deposit Insurance Act) [1] the Secretary of State, the Securities and Exchange Commission, the Commodity Futures Trading Commission, the National Credit Union Administration Board, and in the sole discretion of the Secretary, such other agencies and interested parties as the Secretary may find to be appropriate; and
(B) shall consider—
whether similar action has been or is being taken by other nations or multilateral groups;
whether the imposition of any particular special measure would create a significant competitive disadvantage, including any undue cost or burden associated with compliance, for financial institutions organized or licensed in the United States;
the extent to which the action or the timing of the action would have a significant adverse systemic impact on the international payment, clearance, and settlement system, or on legitimate business activities involving the particular jurisdiction, institution, class of transactions, or type of account; and
the effect of the action on United States national security and foreign policy.
(5) No limitation on other authority.—
This section shall not be construed as superseding or otherwise restricting any other authority granted to the Secretary, or to any other agency, by this subchapter or otherwise.
(b) Special Measures.—The special measures referred to in subsection (a), with respect to a jurisdiction outside of the United States, financial institution operating outside of the United States, class of transaction within, or involving, a jurisdiction outside of the United States, or 1 or more types of accounts are as follows:
(1) Recordkeeping and reporting of certain financial transactions.—
(A) In general.—
The Secretary of the Treasury may require any domestic financial institution or domestic financial agency to maintain records, file reports, or both, concerning the aggregate amount of transactions, or concerning each transaction, with respect to a jurisdiction outside of the United States, 1 or more financial institutions operating outside of the United States, 1 or more classes of transactions within, or involving, a jurisdiction outside of the United States, or 1 or more types of accounts if the Secretary finds any such jurisdiction, institution, class of transactions, or type of account to be of primary money laundering concern.
(B) Form of records and reports.—Such records and reports shall be made and retained at such time, in such manner, and for such period of time, as the Secretary shall determine, and shall include such information as the Secretary may determine, including—
the identity and address of the participants in a transaction or relationship, including the identity of the originator of any funds transfer;
the legal capacity in which a participant in any transaction is acting;
the identity of the beneficial owner of the funds involved in any transaction, in accordance with such procedures as the Secretary determines to be reasonable and practicable to obtain and retain the information; and
a description of any transaction.
(2) Information relating to beneficial ownership.—
In addition to any other requirement under any other provision of law, the Secretary may require any domestic financial institution or domestic financial agency to take such steps as the Secretary may determine to be reasonable and practicable to obtain and retain information concerning the beneficial ownership of any account opened or maintained in the United States by a foreign person (other than a foreign entity whose shares are subject to public reporting requirements or are listed and traded on a regulated exchange or trading market), or a representative of such a foreign person, that involves a jurisdiction outside of the United States, 1 or more financial institutions operating outside of the United States, 1 or more classes of transactions within, or involving, a jurisdiction outside of the United States, or 1 or more types of accounts if the Secretary finds any such jurisdiction, institution, or transaction or type of account to be of primary money laundering concern.
(3) Information relating to certain payable-through accounts.—If the Secretary finds a jurisdiction outside of the United States, 1 or more financial institutions operating outside of the United States, or 1 or more classes of transactions within, or involving, a jurisdiction outside of the United States to be of primary money laundering concern, the Secretary may require any domestic financial institution or domestic financial agency that opens or maintains a payable-through account in the United States for a foreign financial institution involving any such jurisdiction or any such financial institution operating outside of the United States, or a payable through account through which any such transaction may be conducted, as a condition of opening or maintaining such account—
to identify each customer (and representative of such customer) of such financial institution who is permitted to use, or whose transactions are routed through, such payable-through account; and
to obtain, with respect to each such customer (and each such representative), information that is substantially comparable to that which the depository institution obtains in the ordinary course of business with respect to its customers residing in the United States.
(4) Information relating to certain correspondent accounts.—If the Secretary finds a jurisdiction outside of the United States, 1 or more financial institutions operating outside of the United States, or 1 or more classes of transactions within, or involving, a jurisdiction outside of the United States to be of primary money laundering concern, the Secretary may require any domestic financial institution or domestic financial agency that opens or maintains a correspondent account in the United States for a foreign financial institution involving any such jurisdiction or any such financial institution operating outside of the United States, or a correspondent account through which any such transaction may be conducted, as a condition of opening or maintaining such account—
to identify each customer (and representative of such customer) of any such financial institution who is permitted to use, or whose transactions are routed through, such correspondent account; and
(5) Prohibitions or conditions on opening or maintaining certain correspondent or payable-through accounts.—
If the Secretary finds a jurisdiction outside of the United States, 1 or more financial institutions operating outside of the United States, or 1 or more classes of transactions within, or involving, a jurisdiction outside of the United States to be of primary money laundering concern, the Secretary, in consultation with the Secretary of State, the Attorney General, and the Chairman of the Board of Governors of the Federal Reserve System, may prohibit, or impose conditions upon, the opening or maintaining in the United States of a correspondent account or payable-through account by any domestic financial institution or domestic financial agency for or on behalf of a foreign banking institution, if such correspondent account or payable-through account involves any such jurisdiction or institution, or if any such transaction may be conducted through such correspondent account or payable-through account.
(c) Consultations and Information To Be Considered in Finding Jurisdictions, Institutions, Types of Accounts, or Transactions To Be of Primary Money Laundering Concern.—
In making a finding that reasonable grounds exist for concluding that a jurisdiction outside of the United States, 1 or more financial institutions operating outside of the United States, 1 or more classes of transactions within, or involving, a jurisdiction outside of the United States, or 1 or more types of accounts is of primary money laundering concern so as to authorize the Secretary of the Treasury to take 1 or more of the special measures described in subsection (b), the Secretary shall consult with the Secretary of State and the Attorney General.
(2) Additional considerations.—In making a finding described in paragraph (1), the Secretary shall consider in addition such information as the Secretary determines to be relevant, including the following potentially relevant factors:
(A) Jurisdictional factors.—In the case of a particular jurisdiction—
evidence that organized criminal groups, international terrorists, or entities involved in the proliferation of weapons of mass destruction or missiles have transacted business in that jurisdiction;
the extent to which that jurisdiction or financial institutions operating in that jurisdiction offer bank secrecy or special regulatory advantages to nonresidents or nondomiciliaries of that jurisdiction;
the substance and quality of administration of the bank supervisory and counter-money laundering laws of that jurisdiction;
the relationship between the volume of financial transactions occurring in that jurisdiction and the size of the economy of the jurisdiction;
the extent to which that jurisdiction is characterized as an offshore banking or secrecy haven by credible international organizations or multilateral expert groups;
whether the United States has a mutual legal assistance treaty with that jurisdiction, and the experience of United States law enforcement officials and regulatory officials in obtaining information about transactions originating in or routed through or to such jurisdiction; and
the extent to which that jurisdiction is characterized by high levels of official or institutional corruption.
(B) Institutional factors.—In the case of a decision to apply 1 or more of the special measures described in subsection (b) only to a financial institution or institutions, or to a transaction or class of transactions, or to a type of account, or to all 3, within or involving a particular jurisdiction—
the extent to which such financial institutions, transactions, or types of accounts are used to facilitate or promote money laundering in or through the jurisdiction, including any money laundering activity by organized criminal groups, international terrorists, or entities involved in the proliferation of weapons of mass destruction or missiles;
the extent to which such institutions, transactions, or types of accounts are used for legitimate business purposes in the jurisdiction; and
the extent to which such action is sufficient to ensure, with respect to transactions involving the jurisdiction and institutions operating in the jurisdiction, that the purposes of this subchapter continue to be fulfilled, and to guard against international money laundering and other financial crimes.
(d) Notification of Special Measures Invoked by the Secretary.—
Not later than 10 days after the date of any action taken by the Secretary of the Treasury under subsection (a)(1), the Secretary shall notify, in writing, the Committee on Financial Services of the House of Representatives and the Committee on Banking, Housing, and Urban Affairs of the Senate of any such action.
(e) Definitions.—Notwithstanding any other provision of this subchapter, for purposes of this section and subsections (i) and (j) of section 5318, the following definitions shall apply:
(1) Bank definitions.—The following definitions shall apply with respect to a bank:
(A) Account.—The term "account"—
means a formal banking or business relationship established to provide regular services, dealings, and other financial transactions; and
includes a demand deposit, savings deposit, or other transaction or asset account and a credit account or other extension of credit.
(B) Correspondent account.—
The term "correspondent account" means an account established to receive deposits from, make payments on behalf of a foreign financial institution, or handle other financial transactions related to such institution.
(C) Payable-through account.—
The term "payable-through account" means an account, including a transaction account (as defined in section 19(b)(1)(C) of the Federal Reserve Act), opened at a depository institution by a foreign financial institution by means of which the foreign financial institution permits its customers to engage, either directly or through a subaccount, in banking activities usual in connection with the business of banking in the United States.
(2) Definitions applicable to institutions other than banks.—
With respect to any financial institution other than a bank, the Secretary shall, after consultation with the appropriate Federal functional regulators (as defined in section 509 of the Gramm-Leach-Bliley Act), define by regulation the term "account", and shall include within the meaning of that term, to the extent, if any, that the Secretary deems appropriate, arrangements similar to payable-through and correspondent accounts.
(3) Regulatory definition of beneficial ownership.—
The Secretary shall promulgate regulations defining beneficial ownership of an account for purposes of this section and subsections (i) and (j) of section 5318. Such regulations shall address issues related to an individual's authority to fund, direct, or manage the account (including, without limitation, the power to direct payments into or out of the account), and an individual's material interest in the income or corpus of the account, and shall ensure that the identification of individuals under this section or subsection (i) or (j) of section 5318 does not extend to any individual whose beneficial interest in the income or corpus of the account is immaterial.
(4) Other terms.—
The Secretary may, by regulation, further define the terms in paragraphs (1), (2), and (3), and define other terms for the purposes of this section, as the Secretary deems appropriate.
(f) Classified Information.—
In any judicial review of a finding of the existence of a primary money laundering concern, or of the requirement for 1 or more special measures with respect to a primary money laundering concern, made under this section, if the designation or imposition, or both, were based on classified information (as defined in section 1(a) of the Classified Information Procedures Act (18 U.S.C. App.),[2] such information may be submitted by the Secretary to the reviewing court ex parte and in camera. This subsection does not confer or imply any right to judicial review of any finding made or any requirement imposed under this section.
(Added Pub. L. 107–56, title III, § 311(a), Oct. 26, 2001, 115 Stat. 298; amended Pub. L. 108–177, title III, § 376, Dec. 13, 2003, 117 Stat. 2630; Pub. L. 108–458, title VI, § 6203(e), (f), Dec. 17, 2004, 118 Stat. 3747; Pub. L. 109–293, title V, § 501, Sept. 30, 2006, 120 Stat. 1350.)
[1]  So in original. Probably should be followed by a comma.
[2]  So in original. A second closing parenthesis probably should precede the comma.
Section 3 of the Federal Deposit Insurance Act, referred to in subsec. (a)(4)(A), is classified to section 1813 of Title 12, Banks and Banking.
Section 19(b)(1)(C) of the Federal Reserve Act, referred to in subsec. (e)(1)(C), is classified to section 461(b)(1)(C) of Title 12, Banks and Banking.
Section 509 of the Gramm-Leach-Bliley Act, referred to in subsec. (e)(2), is classified to section 6809 of Title 15, Commerce and Trade.
Section 1(a) of the Classified Information Procedures Act, referred to in subsec. (f), is section 1(a) of Pub. L. 96–456, which is set out in the Appendix to Title 18, Crimes and Criminal Procedure.
2006—Subsec. (c)(2)(A)(i). Pub. L. 109–293, § 501(1), substituted "or entities involved in the proliferation of weapons of mass destruction or missiles" for "or both,".
Subsec. (c)(2)(B)(i). Pub. L. 109–293, § 501(2), inserted ", including any money laundering activity by organized criminal groups, international terrorists, or entities involved in the proliferation of weapons of mass destruction or missiles" before semicolon at end.
2004—Pub. L. 108–458, § 6203(e), amended section catchline generally. Prior to amendment, catchline read as follows: "Special measures for jurisdictions, financial institutions, or international transactions of primary money laundering concern".
Subsec. (a)(4)(A). Pub. L. 108–458, § 6203(f)(1), substituted "(as defined in section 3 of the Federal Deposit Insurance Act)" for ", as defined in section 3 of the Federal Deposit Insurance Act,".
Subsec. (a)(4)(B)(iii). Pub. L. 108–458, § 6203(f)(2), substituted "class of transactions, or type of account" for "or class of transactions".
Subsec. (b)(1)(A). Pub. L. 108–458, § 6203(f)(3), substituted "class of transactions, or type of account to be" for "or class of transactions to be".
Subsec. (e)(3). Pub. L. 108–458, § 6203(f)(4), inserted "or subsection (i) or (j) of section 5318" after "identification of individuals under this section".
2003—Subsec. (f). Pub. L. 108–177 added subsec. (f).
Amendment by Pub. L. 108–458 effective as if included in Pub. L. 107–56, as of the date of enactment of such Act, and no amendment made by Pub. L. 107–56 that is inconsistent with such amendment to be deemed to have taken effect, see section 6205 of Pub. L. 108–458, set out as a note under section 1828 of Title 12, Banks and Banking.
Determination With Respect to Primary Money Laundering Concern of Russian Illicit Finance
Pub. L. 116–283, div. H, title XCVII, § 9714(a)–(e), Jan. 1, 2021, 134 Stat. 4838, as amended by Pub. L. 117–81, div. F, title LXI, § 6106(b)(2), Dec. 27, 2021, 135 Stat. 2387, provided that:
"(a) Determination.—If the Secretary of the Treasury determines that reasonable grounds exist for concluding that one or more financial institutions operating outside of the United States, or 1 or more classes of transactions within, or involving, a jurisdiction outside of the United States, or 1 or more types of accounts within, or involving, a jurisdiction outside of the United States is of primary money laundering concern in connection with Russian illicit finance, the Secretary of the Treasury may, by order, regulation, or otherwise as permitted by law—
require domestic financial institutions and domestic financial agencies to take 1 or more of the special measures described in section 5318A(b) of title 31, United States Code; or
prohibit, or impose conditions upon, certain transmittals of funds (to be defined by the Secretary) by any domestic financial institution or domestic financial agency, if such transmittal of funds involves any such institution, class of transaction, or type of account.
"(b) Classified Information.—
In any judicial review of a finding of the existence of a primary money laundering concern, or of the requirement for 1 or more special measures with respect to a primary money laundering concern made under this section, if the designation or imposition, or both, were based on classified information (as defined in section 1(a) of the Classified Information Procedures Act (18 U.S.C. App.), such information may be submitted by the Secretary to the reviewing court ex parte and in camera. This subsection does not confer or imply any right to judicial review of any finding made or any requirement imposed under this section.
"(c) Availability of Information.—
The exemptions from, and prohibitions on, search and disclosure provided in section 5319 of title 31, United States Code, shall apply to any report or record of report filed pursuant to a requirement imposed under subsection (a) of this section. For purposes of section 552 of title 5, United States Code, this subsection shall be considered a statute described in subsection (b)(3)(B) of that section.
"(d) Penalties.—
The penalties provided for in sections 5321 and 5322 of title 31, United States Code, that apply to violations of special measures imposed under section 5318A of title 31, United States Code, shall apply to violations of any order, regulation, special measure, or other requirement imposed under subsection (a) of this section, in the same manner and to the same extent as described in sections 5321 and 5322.
"(e) Injunctions.—
The Secretary of the Treasury may bring a civil action to enjoin a violation of any order, regulation, special measure, or other requirement imposed under subsection (a) of this section in the same manner and to the same extent as described in section 5320 of title 31, United States Code."
[Section 9714 of Pub. L. 116–283 consists of subsecs. (a) to (g). Subsecs. (a) to (e) are set out above. Subsecs. (f) and (g), formerly (b) and (c), are not classified to the Code.]
"Federal Functional Regulator" Includes Commodity Futures Trading Commission
For purposes of Pub. L. 107–56 and any amendment by Pub. L. 107–56, the term "Federal functional regulator" includes the Commodity Futures Trading Commission, see section 321(c) of Pub. L. 107–56, set out as a note under section 5318 of this title.


text:
Anyphaena es un género de arañas araneomorfas de la familia Anyphaenidae. Se encuentra en América, Eurasia y Oriente Medio.

Especies
Según The World Spider Catalog 12.0:

Referencias

Enlaces externos

 ION
 Nomenclator Zoologicus

redpajama_set_name: RedPajamaWikipedia


text:
// Copyright 2014 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.devtools.build.lib.runtime;

import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.devtools.build.lib.actions.AggregatedSpawnMetrics;
import com.google.devtools.build.lib.actions.SpawnMetrics;
import java.time.Duration;

/**
 * Aggregates all the critical path components in one object. This allows us to easily access the
 * components data and have a proper toString().
 */
public class AggregatedCriticalPath {
  public static final AggregatedCriticalPath EMPTY =
      new AggregatedCriticalPath(Duration.ZERO, AggregatedSpawnMetrics.EMPTY, ImmutableList.of());

  private final Duration totalTime;
  private final AggregatedSpawnMetrics aggregatedSpawnMetrics;
  private final ImmutableList<CriticalPathComponent> criticalPathComponents;

  public AggregatedCriticalPath(
      Duration totalTime,
      AggregatedSpawnMetrics aggregatedSpawnMetrics,
      ImmutableList<CriticalPathComponent> criticalPathComponents) {
    this.totalTime = totalTime;
    this.aggregatedSpawnMetrics = aggregatedSpawnMetrics;
    this.criticalPathComponents = criticalPathComponents;
  }

  /** Total wall time spent running the critical path actions. */
  public Duration totalTime() {
    return totalTime;
  }

  public AggregatedSpawnMetrics getSpawnMetrics() {
    return aggregatedSpawnMetrics;
  }

  /** Returns a list of all the component stats for the critical path. */
  public ImmutableList<CriticalPathComponent> components() {
    return criticalPathComponents;
  }

  public String getNewStringSummary() {
    Duration executionWallTime =
        aggregatedSpawnMetrics.getTotalDuration(SpawnMetrics::executionWallTime);
    Duration overheadTime =
        aggregatedSpawnMetrics.getTotalDuration(SpawnMetrics::totalTime).minus(executionWallTime);
    return String.format(
        "Critical path %.2fs (setup %.2fs, action wall time %.2fs)",
        totalTime.toMillis() / 1000.0,
        overheadTime.toMillis() / 1000.0,
        executionWallTime.toMillis() / 1000.0);
  }

  @Override
  public String toString() {
    return toString(false, true);
  }

  private String toString(boolean summary, boolean remote) {
    StringBuilder sb = new StringBuilder("Critical Path: ");
    sb.append(String.format("%.2f", totalTime.toMillis() / 1000.0));
    sb.append("s");
    if (remote) {
      sb.append(", ");
      sb.append(getSpawnMetrics().toString(totalTime(), summary));
    }
    if (summary || criticalPathComponents.isEmpty()) {
      return sb.toString();
    }
    sb.append("\n  ");
    Joiner.on("\n  ").appendTo(sb, criticalPathComponents);
    return sb.toString();
  }

  /**
   * Returns a summary version of the critical path stats that omits stats that are not useful to
   * the user.
   */
  public String toStringSummary() {
    return toString(true, true);
  }

  /**
   * Same as toStringSummary but also omits remote stats. This is to be used in Bazel because
   * currently the Remote stats are not calculated correctly.
   */
  public String toStringSummaryNoRemote() {
    return toString(true, false);
  }
}

redpajama_set_name: RedPajamaGithub


text:
#include "../tbb/tbb_assert_impl.h" // Out-of-line TBB assertion handling routines are instantiated here.
#include "tbb/tbb_stddef.h"

#if _MSC_VER && !__INTEL_COMPILER
#pragma warning( push )
#pragma warning( disable : 4100 )
#endif
#include <hwloc.h>
#if _MSC_VER && !__INTEL_COMPILER
#pragma warning( pop )
#endif

#include <vector>

// Most of hwloc calls returns negative exit code on error.
// This macro tracks error codes that are returned from the hwloc interfaces.
#define assertion_hwloc_wrapper(command, ...) \
        __TBB_ASSERT_EX( (command(__VA_ARGS__)) >= 0, "Error occurred during call to hwloc API.");

namespace tbb {
namespace internal {

//------------------------------------------------------------------------
// Information about the machine's hardware TBB is happen to work on
//------------------------------------------------------------------------
class platform_topology {
    friend class numa_affinity_handler;

    // TODO: add the `my_` prefix to the members
    hwloc_topology_t topology;
    hwloc_cpuset_t   process_cpu_affinity_mask;
    hwloc_nodeset_t  process_node_affinity_mask;
    std::vector<hwloc_cpuset_t>  affinity_masks_list;

    std::vector<int> default_concurrency_list;
    std::vector<int> numa_indexes_list;
    int  numa_nodes_count;

    enum init_stages { uninitialized,
                       started,
                       topology_allocated,
                       topology_loaded,
                       topology_parsed } initialization_state;

    // Binding threads to NUMA nodes that locates in another Windows Processor groups
    // is allowed only if machine topology contains several Windows Processors groups
    // and process affinity mask wasn`t limited manually (affinity mask cannot violates
    // processors group boundaries).
    bool intergroup_binding_allowed(size_t groups_num) { return groups_num > 1; }

    platform_topology() : topology(NULL),
                          process_cpu_affinity_mask(NULL),
                          process_node_affinity_mask(NULL),
                          numa_nodes_count(0),
                          initialization_state(uninitialized) {}

public:
    typedef hwloc_cpuset_t             affinity_mask;
    typedef hwloc_const_cpuset_t const_affinity_mask;

    static platform_topology& instance() {
        static platform_topology topology;
        return topology;
    }

    bool is_topology_parsed() { return initialization_state == topology_parsed; }

    void initialize( size_t groups_num ) {
        if ( initialization_state != uninitialized )
            return;
        initialization_state = started;

        // Parse topology
        if ( hwloc_topology_init( &topology ) == 0 ) {
            initialization_state = topology_allocated;
            if ( hwloc_topology_load( topology ) == 0 ) {
                initialization_state = topology_loaded;
            }
        }

        // Fill parameters with stubs if topology parsing is broken.
        if ( initialization_state != topology_loaded ) {
            if ( initialization_state == topology_allocated ) {
                hwloc_topology_destroy(topology);
            }
            numa_nodes_count = 1;
            numa_indexes_list.push_back(-1);
            default_concurrency_list.push_back(-1);
            return;
        }

        // Getting process affinity mask
        if ( intergroup_binding_allowed(groups_num) ) {
            process_cpu_affinity_mask  = hwloc_bitmap_dup(hwloc_topology_get_complete_cpuset (topology));
            process_node_affinity_mask = hwloc_bitmap_dup(hwloc_topology_get_complete_nodeset(topology));
        } else {
            process_cpu_affinity_mask  = hwloc_bitmap_alloc();
            process_node_affinity_mask = hwloc_bitmap_alloc();

            assertion_hwloc_wrapper(hwloc_get_cpubind, topology, process_cpu_affinity_mask, 0);
            hwloc_cpuset_to_nodeset(topology, process_cpu_affinity_mask, process_node_affinity_mask);
        }

        // If system contains no NUMA nodes, HWLOC 1.11 returns an infinitely filled bitmap.
        // hwloc_bitmap_weight() returns negative value for such bitmaps, so we use this check
        // to change way of topology initialization.
        if (hwloc_bitmap_weight(process_node_affinity_mask) < 0) {
            numa_nodes_count = 1;
            numa_indexes_list.push_back(0);
            default_concurrency_list.push_back(hwloc_bitmap_weight(process_cpu_affinity_mask));

            affinity_masks_list.push_back(hwloc_bitmap_dup(process_cpu_affinity_mask));
            initialization_state = topology_parsed;
            return;
        }

        // Get number of available NUMA nodes
        numa_nodes_count = hwloc_bitmap_weight(process_node_affinity_mask);
        __TBB_ASSERT(numa_nodes_count > 0, "Any system must contain one or more NUMA nodes");

        // Get NUMA logical indexes list
        unsigned counter = 0;
        int i = 0;
        int max_numa_index = -1;
        numa_indexes_list.resize(numa_nodes_count);
        hwloc_obj_t node_buffer;
        hwloc_bitmap_foreach_begin(i, process_node_affinity_mask) {
            node_buffer = hwloc_get_obj_by_type(topology, HWLOC_OBJ_NUMANODE, i);
            numa_indexes_list[counter] = static_cast<int>(node_buffer->logical_index);

            if ( numa_indexes_list[counter] > max_numa_index ) {
                max_numa_index = numa_indexes_list[counter];
            }

            counter++;
        } hwloc_bitmap_foreach_end();
        __TBB_ASSERT(max_numa_index >= 0, "Maximal NUMA index must not be negative");

        // Fill concurrency and affinity masks lists
        default_concurrency_list.resize(max_numa_index + 1);
        affinity_masks_list.resize(max_numa_index + 1);

        int index = 0;
        hwloc_bitmap_foreach_begin(i, process_node_affinity_mask) {
            node_buffer = hwloc_get_obj_by_type(topology, HWLOC_OBJ_NUMANODE, i);
            index = static_cast<int>(node_buffer->logical_index);

            hwloc_cpuset_t& current_mask = affinity_masks_list[index];
            current_mask = hwloc_bitmap_dup(node_buffer->cpuset);

            hwloc_bitmap_and(current_mask, current_mask, process_cpu_affinity_mask);
            __TBB_ASSERT(!hwloc_bitmap_iszero(current_mask), "hwloc detected unavailable NUMA node");
            default_concurrency_list[index] = hwloc_bitmap_weight(current_mask);
        } hwloc_bitmap_foreach_end();
        initialization_state = topology_parsed;
    }

    ~platform_topology() {
        if ( is_topology_parsed() ) {
            for (int i = 0; i < numa_nodes_count; i++) {
                hwloc_bitmap_free(affinity_masks_list[numa_indexes_list[i]]);
            }
            hwloc_bitmap_free(process_node_affinity_mask);
            hwloc_bitmap_free(process_cpu_affinity_mask);
        }

        if ( initialization_state >= topology_allocated ) {
            hwloc_topology_destroy(topology);
        }

        initialization_state = uninitialized;
    }

    void fill(int& nodes_count, int*& indexes_list, int*& concurrency_list ) {
        __TBB_ASSERT(is_topology_parsed(), "Trying to get access to uninitialized platform_topology");
        nodes_count = numa_nodes_count;
        indexes_list = &numa_indexes_list.front();
        concurrency_list = &default_concurrency_list.front();
    }

    affinity_mask allocate_process_affinity_mask() {
        __TBB_ASSERT(is_topology_parsed(), "Trying to get access to uninitialized platform_topology");
        return hwloc_bitmap_dup(process_cpu_affinity_mask);
    }

    void free_affinity_mask( affinity_mask mask_to_free ) {
        hwloc_bitmap_free(mask_to_free); // If bitmap is NULL, no operation is performed.
    }

    void store_current_affinity_mask( affinity_mask current_mask ) {
        assertion_hwloc_wrapper(hwloc_get_cpubind, topology, current_mask, HWLOC_CPUBIND_THREAD);

        hwloc_bitmap_and(current_mask, current_mask, process_cpu_affinity_mask);
        __TBB_ASSERT(!hwloc_bitmap_iszero(current_mask),
            "Current affinity mask must intersects with process affinity mask");
    }

    void set_new_affinity_mask( const_affinity_mask new_mask ) {
        assertion_hwloc_wrapper(hwloc_set_cpubind, topology, new_mask, HWLOC_CPUBIND_THREAD);
    }

    const_affinity_mask get_node_affinity_mask( int node_index ) {
        __TBB_ASSERT((int)affinity_masks_list.size() > node_index,
            "Trying to get affinity mask for uninitialized NUMA node");
        return affinity_masks_list[node_index];
    }
};

class binding_handler {
    // Following vector saves thread affinity mask on scheduler entry to return it to this thread
    // on scheduler exit.
    typedef std::vector<platform_topology::affinity_mask> affinity_masks_container;
    affinity_masks_container affinity_backup;

public:
    binding_handler( size_t size ) : affinity_backup(size) {
        for (affinity_masks_container::iterator it = affinity_backup.begin();
             it != affinity_backup.end(); it++) {
            *it = platform_topology::instance().allocate_process_affinity_mask();
        }
    }

    ~binding_handler() {
        for (affinity_masks_container::iterator it = affinity_backup.begin();
             it != affinity_backup.end(); it++) {
            platform_topology::instance().free_affinity_mask(*it);
        }
    }

    void bind_thread_to_node( unsigned slot_num, unsigned numa_node_id ) {
        __TBB_ASSERT(slot_num < affinity_backup.size(),
            "The slot number is greater than the number of slots in the arena");
        __TBB_ASSERT(platform_topology::instance().is_topology_parsed(),
            "Trying to get access to uninitialized platform_topology");
        platform_topology::instance().store_current_affinity_mask(affinity_backup[slot_num]);

        platform_topology::instance().set_new_affinity_mask(
            platform_topology::instance().get_node_affinity_mask(numa_node_id));
    }

    void restore_previous_affinity_mask( unsigned slot_num ) {
        __TBB_ASSERT(platform_topology::instance().is_topology_parsed(),
            "Trying to get access to uninitialized platform_topology");
        platform_topology::instance().set_new_affinity_mask(affinity_backup[slot_num]);
    };

};

extern "C" { // exported to TBB interfaces

void initialize_numa_topology( size_t groups_num,
                               int& nodes_count, int*& indexes_list, int*& concurrency_list ) {
    platform_topology::instance().initialize(groups_num);
    platform_topology::instance().fill(nodes_count, indexes_list, concurrency_list);
}

binding_handler* allocate_binding_handler(int slot_num) {
    __TBB_ASSERT(slot_num > 0, "Trying to create numa handler for 0 threads.");
    return new binding_handler(slot_num);
}

void deallocate_binding_handler(binding_handler* handler_ptr) {
    __TBB_ASSERT(handler_ptr != NULL, "Trying to deallocate NULL pointer.");
    delete handler_ptr;
}

void bind_to_node(binding_handler* handler_ptr, int slot_num, int numa_id) {
    __TBB_ASSERT(handler_ptr != NULL, "Trying to get access to uninitialized metadata.");
    __TBB_ASSERT(platform_topology::instance().is_topology_parsed(),
        "Trying to get access to uninitialized platform_topology.");
    handler_ptr->bind_thread_to_node(slot_num, numa_id);
}

void restore_affinity(binding_handler* handler_ptr, int slot_num) {
    __TBB_ASSERT(handler_ptr != NULL, "Trying to get access to uninitialized metadata.");
    __TBB_ASSERT(platform_topology::instance().is_topology_parsed(),
        "Trying to get access to uninitialized platform_topology.");
    handler_ptr->restore_previous_affinity_mask(slot_num);
}

} // extern "C"

} // namespace internal
} // namespace tbb

#undef assertion_hwloc_wrapper


text: export {DragulaSample} from './dragula.component';