Swift - Displaying Actionsheet for Ipad and Iphone

Swift - Displaying Actionsheet for Ipad and Iphone

A simple tutorial on making an alert view of type action sheet that works for iphone and ipad.



1.) First you'll need a button where you can attach your pop over when you're using iPad (in iPhone it not necessary). Then you'll have to create an outlet for the button (in my example i named it "btn_button") so we can determine the pop over location based on where the button is placed inside the viewcontroller.

2.) Inside the button's action, paste the following lines of code:

 let optionMenu = UIAlertController(title: "Choose Your Option", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)

let option1 = UIAlertAction(title: "Option 1", style: .Default, handler: {

(alert: UIAlertAction!) -> Void in
println("Option 1")
})

let option2 = UIAlertAction(title: "Option ", style: .Default, handler: {

(alert: UIAlertAction!) -> Void in
println("Option 2")
})

let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: {
(alert: UIAlertAction!) -> Void in
println("Cancelled")
})

optionMenu.addAction(option1)
optionMenu.addAction(option2)
optionMenu.addAction(cancelAction)


if ( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.Pad )
{
if let currentPopoverpresentioncontroller = optionMenu.popoverPresentationController{
currentPopoverpresentioncontroller.sourceView = btn_button
currentPopoverpresentioncontroller.sourceRect = btn_button.bounds;
currentPopoverpresentioncontroller.permittedArrowDirections = UIPopoverArrowDirection.Up;
self.presentViewController(optionMenu, animated: true, completion: nil)
}
}else{
self.presentViewController(optionMenu, animated: true, completion: nil)
}


The code is pretty straight forward:
-First we declare a UIAlertController where we can put our buttons.
-Second we created the buttons (Option1, Option2, and Cancel) and then we add the buttons inside the alert controller.
-Last we use the UI_USER_INTERFACE_IDIOM to determine if the device/emulator is an ipad or an iphone and do the necessary presentation for each particular device.

Oljefondets informasjonsstrategi

Oljefondet må slutte å plage seg selv. Fondets informasjonsstrategi har så langt ikke resultert i annet enn mistenksomhet og mistillit.

Det er ekstremt vanskelig å få ut informasjon fra Oljefondets forvalter NBIM. DN måtte mase i ukesvis for å få ut tall på risikojustert avkastning, Det er ingen som egentlig helt forstår hvorfor NBIM ikke ville levere ut tallene, men NBIM ville altså absolutt ikke vise dem. Det var sannsynligvis en departemental instruks som til slutt tvang frem en offentliggjøring.

Å hemmeligholde denne type informasjon, som ikke er spesielt sensitiv, er en strutsestrategi. Informasjonen vil før eller senere komme ut. Den nåværende informasjonsstrategien går imidlertid ut på at fondet skal drives fra skanse til skanse først. Det ser sjeldent særlig pent ut.

I dette tilfelle nektet først fondet å legge frem tall. Så la de frem «tulletall». Så la fondet frem tall som ikke er etterprøvbare og som både mangler en viktig forklaringsfaktor («momentum) og som etterlater et stort uforklart gap sammenlignet med Hoddevik og Priestleys estimat (se figur). Med identisk datamateriale og modell burde NBIM og Hoddevik/Priestley kommet frem til identiske tall. Forskjellen burde vært 0.000%.

Tallene fondet har presentert er imidlertid basert på data som er skreddersydd for fondet, men som fondet ikke vil dele med andre. Forklaringer som fondet har gitt på hemmeligholdet er ikke troverdige. For utenforstående er det dermed umulig å finne ut hvorfor NBIM får så høy risikojustert avkastning. Denne skansen vil nok også falle, og tallene vil komme frem på et eller annet tidspunkt, og NBIM vil igjen ikke ha oppnådd annet enn å bli oppfattet som unødvendig vriene og vanskelige.

Det burde være unødvendig å minne NBIM om at de forvalter et statlig nasjonalt fond. Det er et betydelig demokratisk problem at fondet selv ikke bidrar på en positiv måte til at akademikere på utsiden kan gjøre uavhengige beregninger. Informasjon må hales ut av fondet. Slik burdet det ikke være.

For eksempel kunne ikke NBIM en gang utlevere fondets gjennomsnittlige vekslingskurser, kalt «valutakurven», til Hoddevik og Priestley. De måtte bruke store ressurser på å beregne disse om igjen. Helt unødvendig dobbeltarbeid selvsagt. At avkastningstallene oppgis i valutakurv og ikke i dollar eller kroner er fornuftig, men historiske vekslingskurser må være tilgjengelige.

Når NBIM gjør sine egne analyser med hemmelige data, så er det selvsagt helt umulig for andre å etterprøve beregningene. Det gir ikke tilstrekkelig kontroll at departementet fra tid til annen bestiller rapporter fra internasjonale forskere. Disse rapportene er hverken uavhengig eller utfyllende. Departementet betaler forskerne et formodentlig solid honorar for jobben. NBIMs tette bånd til Finansdepartementet gjør at de sannsynligvis er uformelt med på å utforme mandatene. Uavhengige analyser, slik som Hoddevik og Priestleys, er av uvurderlig nytte for å vurdere fondets prestasjoner. NBIM motarbeider aktivt dette.

Dessverre er det grunnlag for mistenksomhet. Flere eksempler viser det. «Tulletall»-saken er bare det siste i rekken. Fondet gjentar for eksempel til stadighet at passiv forvaltning ville ha kostet 0,17 % i året. Hvordan kan det da ha seg indeksforvalteren Vanguard kan klare det mye billigere for millioner av småinvestorer og samtidig tjene penger? Nøyaktighet ser ikke ut til å være noe varemerke for NBIM.

Fondet har ingenting å vinne på å bli oppfattet som vanskelig og uetterrettelig. Som et offentlig fond bør NBIM snu dagens informasjonsdoktrine på hodet. Med mindre det er sterke og reelle grunner for det motsatte bør informasjon om fondets prestasjoner være offentlig.







Poland vs the United States: suburban sprawl


This is the eighth article in a short series about Poland, Europe, and the United States. To explore the entire series, start here.




If you live in any other western country, your perception of the United States is bound to be profoundly influenced by Hollywood. You may think you're immune to it, but you are not: sure, you can sneer at the ridiculous plot holes or the gratuitous patriotism in American blockbusters - but the establishing shots of high-rise cityscapes of Manhattan or Los Angeles will be seared into your mind. These images will color your expectations and your understanding of the country in more ways than you may expect.




Because of this phenomenon, urban dwellers from Europe who come to visit the US may be in for a surprise: the country will probably feel a lot more rural than they would have thought. They will get to marvel the grand cities and the iconic skyscrapers; but chances are, this scenery will quickly morph not into the familiar urban jungle of massive apartment blocks seen throughout much of Europe, but into the endless suburban sprawl of single-family homes and strip malls.




For most Americans, this vast, low-density suburban landscape is the backdrop of their everyday lives. Take San Francisco: just 800,000 people live in the city proper. The San Francisco Bay Area, the home to 8 million residents and the location of the largest and most influential tech hub in the world, is nothing more than an enormous stretch of greenery peppered with detached homes, unassuming two-story office buildings, and roadside car dealerships. Heck, even New York City, by far the largest urban conglomeration in America, is just a blip on the radar compared to the colossal suburban sprawl that engulfs the region - stretching all the way from Massachusetts to Washington D.C.




The raw numbers paint a similar picture: in Poland, the average population density is around 125 people per square kilometer; in the more densely populated Germany, the figure is closer to 220. In comparison, with fewer than 35 people per km2, the United States comes out looking like a barren wasteland. The country has many expanses of untouched wilderness - and quite a few rural regions where the residents get by without as little as a postal address, a nearby fire station, a police department, or a hospital.




Awareness of the predominantly suburban and rural character of much of the US is vital to understanding some the national stereotypes that may seem bizarre or archaic to urban-dwelling Europeans. It certainly helps explain the limited availability of public transportation, or the residents' love for rifles and gas-guzzling pickup trucks. The survivalist "prepper" culture, focused on self-sufficiency in the face of disaster, is another cultural phenomenon that although seemingly odd, is not just pure lunacy; in the past few decades, millions of Americans had to evacuate or dig in in response to hurricanes, wildfires, earthquakes, or floods.




The stark difference between urban and rural living can also make it easier to grasp some of the ideological clashes between the big-city liberal progressives and the traditionally conservative dwellers of the so-called "flyover states". Sometimes, the conservatives are simply on the wrong side of history; but on some other occasions, the city-raised politicians, scholars, and journalists are too eager to paint the whole nation with the same brush. Take something as trivial as car efficiency standards: they will rub you one way if you take subway to the office and drive your compact car to the grocery store; and another if you ever needed to haul firewood or construction materials on the back of your Ford F-150.




For the next article in the series, click here.


Poland vs the United States: friends & acquaintances


This is the seventh article in a short series about Poland, Europe, and the United States. To explore the entire series, start here.




Cultural stereotypes are a dangerous and corrosive thing. They teach us that Poles are a tribe of thieving simpletons; or that Americans are arrogant, violent, and obese. And that's just the ethnicities that get off easy: the perception of blacks, Muslims, or European Jews can be far more vicious, often serving a pretext for violent hate crime.




At the same time, there is no denying that certain unique archetypes are etched into the fabric of every society. I'd also posit that when cultures come into contact with each other, there is an uncanny valley effect at play: the more similar the nations are, the easier it is for travelers to instinctively pick up the subtle variations - and to misread them as the personality quirks of the people they interact with.




For Poles who settle in the United States, the most striking contrast of this sort must be the persistence with which Americans want to engage in oddly personal small talk: you will be always greeted with "how are you?", be it by the cashier at a grocery store, by your mailman, by the park ranger met at a trail, or by the waiter serving your food at a restaurant. The social expectation is to share short pleasantries or announce a brief piece of good news. But if your answer is overly specific or focuses on a negative event, you may be given quizzical looks and the conversation will stall.




To many of my compatriots, the exchange - lacking any apparent purpose - feels uncomfortable and insincere. I try not to look at it in a cynical way: the upbeat chit-chat, repeated over and over again, can probably make your day a bit better and a tad more fun. This constrained form of communication also provides something to build on the next time you see that person, even if every individual interaction is necessarily non-committal and brief.




Another explanation for the forced positivity may have to do with the pervasive can-do spirit at the core of the American culture. The national ethos of self-determination and unconstrained social mobility flies in the face of the daily struggles of disadvantaged citizens - but it remains a fundamental part of the cultural identity of the United States. The American Dream manifests itself everywhere, from the country songs of the Midwest to the high-tech entrepreneurship of the Silicon Valley. Your friends, coworkers, neighbors, and even complete strangers are there to support you when true calamity strikes - but dwelling on everyday mishaps is almost universally seen as a weakness that one needs to overcome in order to succeed in life.




In this regard, the Polish culture is strikingly different. After hundreds of years of political repression and foreign control, Poles have developed a colorful tradition of sarcastic humor and idle lamentation. This coping mechanism functions to this day: to a Pole, being asked about your day is seen as an invitation to air all the petty grievances; you wouldn't expect a friend to smile, exclaim "I'm doing great!", and move on. Complaining about politics or work is how you build rapport with your peers. In fact, being overly upbeat or talking about professional success or accomplishment is likely to be met with suspicion or scorn. If you're a successful entrepreneur, you will probably open by complaining about your dealings with the Polish equivalent of the IRS.




In many ways, the Polish approach to chit-chat is more genuine and less rigid. At the same time, I feel that the negativity comes at a price; meeting a cranky clerk at a store sets the tone for the remainder of your day. The constant pessimism can also dampen some altruistic instincts: relatively few people in Poland get engaged in their communities or dedicate themselves to other forms of civic service. It is more accepted to just complain about the ways things are.




Interestingly, in the United States, the boundaries that govern the conversations with complete strangers also extend into the workplace. When interacting with casual acquaintances, sarcasm is seen as jarring, while petty grumbling is perceived as an off-putting and unproductive personality trait. Off-color humor, widely tolerated in Poland, is usually inappropriate in white collar environments; doubly so if it comes at the expense of women, immigrants, or other disadvantaged social groups.




Some Europeans characterize the workplace etiquette in the US as political correctness run amok. There are situations where political correctness can stifle free speech, but I don't think it's one of them; for most part, not hearing political rants or jokes about blondes or Jews just makes the world a bit better, even if the comments are uttered with no ill intent. Violating these rules will not necessarily get you in trouble, but in a culturally diverse society, it can make it harder to find new friends.





For the next article in the series, click here.


Poland vs the United States: civil liberties


This is the sixth article in a short series about Poland, Europe, and the United States. To explore the entire series, start here.




I opened my comparison of Poland and the US with the topic of firearm ownership. I decided to take this route in part because of how alien the US gun culture may appear to outsiders - and because of how polarizing and interesting the subject is. But in today's entry, I wanted to take a step back and have a look at the other, more traditional civil liberties that will be more familiar to folks on the other side of the pond.




Before we dive in, it is probably important to note that the national ethos of the United States is very expressly built on the tradition of radical individualism and free enterprise - as championed by thinkers such as Milton Friedman, Friedrich Hayek, or Adam Smith. Of course, many words can be written about the disconnect between this romanticized vision and complex realities of entrepreneurship or social mobility in the face of multi-generational poverty - but the perception still counts: in much of Europe, the government is seen less as a guarantor of civil liberties, and more as a provider of basic needs. The inverse is more true in the US; the armed forces and small businesses enjoy the two top spots in institutional trustworthiness surveys; federal legislators come dead last. This sentiment shapes many of the ongoing political debates - not just around individual freedoms, but also as related to public healthcare or the regulation of commerce. The virtues of self-sufficiency and laissez-faire capitalism seem far more self-evident to the citizens of the US than they are in the EU.




With that in mind, it's worthwhile to start the comparison with the freedom of speech. A cherished tradition in the western world, this liberty is nevertheless subordinate to a number of collectivist social engineering goals across the whole old continent; for example, strong prohibitions exist on the promotion of Nazi ideology or symbolism, or on the mere practice of denying the Holocaust. The freedom of speech is also broadly trumped by the right to privacy, including the hotly-debated right to be forgotten on the Internet. Other, more exotic restrictions implemented in several places in Europe include the prohibition against disrespecting the religious beliefs of others or insulting any acting head of state; in Poland, people have been prosecuted for hurling childish insults at the Pope or at the outgoing Polish president. Of course, the enforcement is patently selective: in today's political climate, no one will be charged for calling Mr. Putin a thug.




The US takes a more absolutist view of the First Amendment, with many hate groups enjoying far-reaching impunity enshrined in the judicial standards put forward not by politicians, but by the unusually powerful US Supreme Court. The notion of "speech" is also interpreted very broadly, extending to many forms of artistic, religious, and political expression; in particular, the European niqab and burka bans would be patently illegal in the United States and aren't even the subject of serious debate. The concept of homeschooling, banned or heavily regulated in some parts of Europe, is seen by some through the same constitutional prism: it is your right to teach your children about Young Earth creationism, and the right trumps any concerns over the purported social costs. Last but not least, there is the controversial Citizens United decision, holding that some forms of financial support provided to political causes can be equated with constitutionally protected speech; again, the ruling came not from the easily influenced politicians, but from the Supreme Court.




As an aside, despite the use of freedom-of-speech restrictions as a tool for rooting out anti-Semitism and hate speech in Europe, the contemporary US may be providing a less fertile ground for racism and xenophobia than at least some parts of the EU. The country still struggles with its dark past and the murky reality of racial discrimination - but despite the stereotypes, the incidence of at least some types of casual racism in today's America seems lower than in much of Europe. The pattern is also evident in political discourse; many of the openly xenophobic opinions or legislative proposals put forward by European populist politicians would face broad condemnation in the US. Some authors argue that the old continent is facing a profound new wave of Islamophobia and
hatred toward Jews; in countries such as Greece and Hungary, more than 60% of population seems to be holding such views. In Poland, more than 40% say that Jews hold too much influence in business - a surreal claim, given that that there are just several thousand Jews living in the country of 38 million. My own memories from growing up in that country are that of schoolkids almost universally using "you Jew!" as a mortal insult. The defacement of Jewish graves and monuments, or anti-Semitic graffiti, posters, and sports chants are far more common than they should be. It's difficult to understand if restrictions on free speech suppress the sentiments or make them worse, but at the very least, the success of the policies is not clear-cut.




Other civil liberties revered in the United States, and perhaps less so in Europe, put limits on the ability of the government to intrude into private lives through unwarranted searches and seizures. Of course, the stereotypical view of the US is that of a dystopian surveillance state, epitomized by the recent focus on warrantless surveillance or secret FISA courts. But having worked for a telecommunications company in Poland, my own sentiment is that in Europe, surveillance tends to be done with more impunity, far less legal oversight, and without clear delination between law enforcement and intelligence work. The intelligence community in particular is often engaged in domestic investigations against businesses, politicians, and journalists - and all across Europe, "pre-crime" policing ideas are taking hold.




In many European countries, citizens are not afforded powerful tools such as FOIA requests, do not benefit from a tradition of protected investigative journalism and whistleblowing, and can't work with influential organizations such as the American Civil Liberties Union; there is also no history of scandals nearly as dramatic and transformative as Watergate. In the States, I feel that all this helped to create an imperfect but precious balance between the needs of the government and the rights of the people - and instill higher ethical standards in the law enforcement and intelligence community; it is telling that the revelations from Snowden, while exposing phenomenal and somewhat frightening surveillance capabilities of the NSA, have not surfaced any evidence of politically-motivated investigations or other blatant impropriety in how the capabilities are being used by the agency. The individualist spirit probably helps here, too: quite a few states and municipalities go as far as banning traffic enforcement cameras because of how they rob suspects of the ability to face the accuser in court.




When it comes to some other civil traditions that are sacrosanct in Europe, the United States needs to face justified criticism. The harsh and overcrowded penal system treats some offenders unfairly; it is a product of populist sentiments influenced by the crime waves of the twentieth century and fueled by the dysfunctional War on Drugs. While Polish prisons may not be much better, some of the ideas implemented elsewhere in Europe seem to make a clear difference. They are difficult to adopt in the States chiefly because they do not fit the folksy "tough on crime" image that many American politicians take pride in.




In the same vein, police brutality, disproportionately faced by the poor and the minorities, is another black mark for individual rights. The death penalty, albeit infrequent and reserved for most heinous crimes, stands on shaky moral grounds - even if it faces steady public support. The indefinite detention and torture of terrorism suspects, with the knowledge and complicity of many other European states, deserves nothing but scorn. Civil forfeiture is a bizarre concept that seems to violate the spirit of the Fourth Amendment by applying unreasonably relaxed standards for certain types of seizures - although in all likelihood, its days are coming to an end.




As usual, the picture is complex and it's hard to declare the superiority of any single approach to individual liberties. Europe and the United States have much in common, but also differ in very interesting ways.





For the next article in the series, click here.

A bit more on firearms in the US


This is the fifth article in a short series about Poland, Europe, and the United States. To explore the entire series, start here.




Perhaps not surprisingly, my previous blog post sparked several interesting discussions with my Polish friends who took a more decisive view of the social costs of firearm ownership, or who saw the Second Amendment as a barbaric construct with no place in today's world. Their opinions reminded me of my own attitude some ten years ago; in this brief follow-up, I wanted to share several data points that convinced me to take a more measured stance.




Let's start with the basics: most estimates place the number of guns in the United States at 300 to 350 million - that's roughly one firearm per every single resident. In Gallup polls, some 40-50% of all households report having a gun, frequently more than one. The demographics of firearm ownership are more uniform than stereotypes may imply; there is some variance across regions, political affiliations, and genders - but for most part, it tends to fall within fairly narrow bands.




An overwhelming majority of gun owners cite personal safety as the leading motive for purchasing a firearm; hunting and recreation activities come strong second. The defensive aspect of firearm ownership is of special note, because it can potentially provide a very compelling argument for protecting the right to bear arms even if it's a socially unwelcome practice, or if it comes at an elevated cost to the nation as a whole.




The self-defense argument is sometimes dismissed as pure fantasy, with many eminent pundits citing one questionable statistic to support this view: the fairly low number of justifiable homicides in the country. Despite its strong appeal to ideologues, the metric does not stand up to scrutiny: all available data implies that most encounters where a gun is pulled by a would-be victim will not end with the assailant getting killed; it's overwhelmingly more likely that the bad guy would hastily retreat, be detained at gunpoint, or suffer non-fatal injuries. In fact, even in the unlikely case that a firearm is actually discharged with the intent to kill or maim, somewhere around 70-80% of victims survive.




In reality, we have no single, elegant, and reliable source of data about the frequency with which firearms are used to deter threats; the results of scientific polls probably offer the most comprehensive view, but are open to interpretation and their results vary significantly depending on sampling methods and questions asked. That said, a recent meta-analysis from Centers for Disease Control and Prevention provided some general bounds:




"Defensive use of guns by crime victims is a common occurrence, although the exact number remains disputed (Cook and Ludwig, 1996; Kleck, 2001a). Almost all national survey estimates indicate that defensive gun uses by victims are at least as common as offensive uses by criminals, with estimates of annual uses ranging from about 500,000 to more than 3 million."




An earlier but probably similarly unbiased estimate from US Dept of Justice puts the number at approximately 1.5 million uses a year.




The CDC study also goes on to say:




"A different issue is whether defensive uses of guns, however numerous or rare they may be, are effective in preventing injury to the gun-wielding crime victim. Studies that directly assessed the effect of actual defensive uses of guns (i.e., incidents in which a gun was “used” by the crime victim in the sense of attacking or threatening an offender) have found consistently lower injury rates among gun-using crime victims compared with victims who used other self-protective strategies."




An argument can be made that the availability of firearms translates to higher rates of violent crime, thus elevating the likelihood of encounters where a defensive firearm would be useful - feeding into an endless cycle of escalating violence. That said, such an effect does not seem to be particularly evident. For example, the United States comes out reasonably well in statistics related to assault, rape, and robbery; on these fronts, America looks less violent than the UK or a bunch of other OECD countries with low firearm ownership rates.




But there is an exception: one area where the United States clearly falls behind other highly developed nations are homicides. The per-capita figures are almost three times as high as in much of the European Union. And indeed, the bulk of intentional homicides - some 11 thousand deaths a year - trace back to firearms.




We tend to instinctively draw a connection to guns, but the origins of this tragic situation may be more elusive than they appear. For one, non-gun-related homicides happen in the US at a higher rate than in many other countries, too; Americans just seem to be generally more keen on killing each other than people in places such as Europe, Australia, or Canada. In addition, no convincing pattern emerges when comparing overall homicide rates across states with permissive and restrictive gun ownership laws. Some of the lowest per-capita homicide figures can be found in extremely gun-friendly states such as Idaho, Utah, or Vermont; whereas highly-regulated Washington D.C., Maryland, Illinois, and California all rank pretty high. There is, however, fairly strong correlation between gun and non-gun homicide rates across the country - suggesting that common factors such as population density, urban poverty, and drug-related gang activities play a far more significant role in violent crime than the ease of legally acquiring a firearm. It's tragic but worth noting that a strikingly disproportionate percentage of homicides involves both victims and perpetrators that belong to socially disadvantaged and impoverished minorities. Another striking pattern is that up to about a half of all gun murders are related to or committed under the influence of illicit drugs.




Now, international comparisons show general correlation between gun ownership and some types of crime, but it's difficult to draw solid conclusions from that: there are countless other ways to explain why crime rates may be low in the wealthy European states, and high in Venezuela, Mexico, Honduras, or South Africa; compensating for these factors is theoretically possible, but requires making far-fetched assumptions that are hopelessly vulnerable to researcher bias. Comparing European countries is easier, but yields inconclusive results: gun ownership in Poland is almost twenty times lower than in neighboring Germany and ten times lower than in Czech Republic - but you certainly wouldn't able to tell that from national crime stats.




When it comes to gun control, one CDC study on the topic concluded with:




"The Task Force found insufficient evidence to determine the effectiveness of any of the firearms laws or combinations of laws reviewed on violent outcomes."




This does not imply that such approaches are necessarily ineffective; for example, it seems pretty reasonable to assume that well-designed background checks or modest waiting periods do save lives. Similarly, safe storage requirements would likely prevent dozens of child deaths every year, at the cost of rendering firearms less available for home defense. But for the hundreds of sometimes far-fetched gun control proposals introduced every year on federal and state level, emotions often take place of real data, poisoning the debate around gun laws and ultimately bringing little or no public benefit. The heated assault weapon debate is one such red herring: although modern semi-automatic rifles look sinister, they are far more common in movies than on the streets; in reality, all kinds of rifles account only for somewhere around 4% of firearm homicides, and AR-15s are only a tiny fraction of that - likely claiming about as many lives as hammers, ladders, or swimming pools. The efforts to close the "gun show loophole" seem fairly sensible at the surface, too, but are of similarly uncertain merit; instead of gun shows, criminals depend on friends, family, and on more than 200,000 guns that stolen from their rightful owners every year. When breaking into a random home yields a 40-50% chance of scoring a firearm, it's not hard to see why.




Another oddball example of simplistic legislative zeal are the attempts to mandate costly gun owner liability insurance, based on drawing an impassioned but flawed parallel between firearms and cars; what undermines this argument is that car accidents are commonplace, while gun handling mishaps - especially ones that injure others - are rare. We also have proposals to institute $100 ammunition purchase permits, to prohibit ammo sales over the Internet, or to impose a hefty per-bullet tax. Many critics feel that such laws seem to be geared not toward addressing any specific dangers, but toward making firearms more expensive and burdensome to own - slowly eroding the constitutional rights of the less wealthy folks. They also see hypocrisy in the common practice of making retired police officers and many high-ranking government officials exempt from said laws.




Regardless of individual merits of the regulations, it's certainly true that with countless pieces of sometimes obtuse and poorly-written federal, state, and municipal statutes introduced every year, it's increasingly easy for people to unintentionally run afoul of the rules. In California, the law as written today implies that any legal permanent resident in good standing can own a gun, but that only US citizens can transport it by car. Given that Californians are also generally barred from carrying firearms on foot in many populated areas, non-citizen residents are seemingly expected to teleport between the gun store, their home, and the shooting range. With many laws hastily drafted in the days after mass shootings and other tragedies, such gems are commonplace. The federal Gun-Free School Zones Act imposes special restrictions on gun ownership within 1,000 feet of a school and slaps harsh penalties for as little carrying it in an unlocked container from one's home to a car parked in the driveway. In many urban areas, a lot of people either live within such a school zone or can't conceivably avoid it when going about their business; GFSZA violations are almost certainly common and are policed only selectively.




Meanwhile, with sharp declines in crime continuing for the past 20 years, the public opinion is increasingly in favor of broad, reasonably policed gun ownership; for example, more than 70% respondents to one Gallup poll are against the restrictive handgun bans of the sort attempted in Chicago, San Francisco, or Washington D.C.; and in a recent Rasmussen poll, only 22% say that they would feel safer in a neighborhood where people are not allowed to keep guns. In fact, responding to the media's undue obsession with random of acts of violence against law-abiding citizens, and worried about the historically very anti-gun views of the sitting president, Americans are buying a lot more firearms than ever before. Even the National Rifle Association - a staunchly conservative organization vilified by gun control advocates and mainstream pundits - enjoys a pretty reasonable approval rating across many demographics: 58% overall and 78% in households with a gun.




And here's the kicker: despite its reputation for being a political arm of firearm manufacturers, the NRA is funded largely through individual memberships, small-scale donations, and purchase round-ups; organizational donations add up to about 5% of their budget - and if you throw in advertising income, the total still stays under 15%. That makes it quite unlike most of the other large-scale lobbying groups that Democrats aren't as keen on naming-and-shaming on the campaign trail. The NRA's financial muscle is also frequently overstated; it doesn't even make it onto the list of top 100 lobbyists in Washington - and gun control advocacy groups, backed by activist billionaires such as Michael Bloomberg, now frequently outspend the pro-gun crowd. Of course, it would be better for the association's socially conservative and unnecessarily polarizing rhetoric - sometimes veering onto the topics of abortion or video games - to be offset by the voice of other, more liberal groups. But ironically, organizations such as American Civil Liberties Union - well-known for fearlessly defending controversial speech - prefer to avoid the Second Amendment; they do so not because the latter concept has lesser constitutional standing, but because supporting it would not sit well with their own, progressive support base.




America's attitude toward guns is a choice, not a necessity. It is also true that gun violence is a devastating problem; and that the emotional horror and lasting social impact of incidents such as school shootings can't be possibly captured in any cold, dry statistic alone. But there is also nuance and reason to the gun control debate that can be hard to see for newcomers from more firearm-averse parts of the world.




For the next article in the series, click here. Alternatively, if you prefer to keep reading about firearms, go here for an overview of the gun control debate in the US.

Competitive Innovation

In my previous post I took a crack at understanding Paul Romer's mathiness critique. As far as the post related to Romer (most of it was devoted to Brad DeLong's careless embellishment of the idea), my assessment was that Romer is basically just frustrated that his ideas have not swept away the competition in the field of growth theory. I do not believe that the academics Romer called out are defending indefensible positions for the sake of academic politics. To me, the present situation looks more like a healthy competition between theories of growth emphasizing different mechanisms. This is just what one would expect in a field where the forces at work are complicated and the answers to important questions are hard to come by.
 
Judging by his reply to my post here, it seems that Romer has a rather low opinion of me. Evidently, I am an "Euler-theorem denier." Admittedly, this is not the worst thing I've ever been called. But in addition to this, I am apparently motivated to deny the truth of this mathematical proposition because doing so signals my commitment to an academic club of serpents that includes the likes of Nobel prize-winning economists Bob Lucas and Ed Prescott. Paul, you flatter me.

I want to take some time here to address the specific charge leveled against me by Romer:

Andolfatto’s brazen mathiness involves a verbal statement about a mathematical model that flies in the face of an impossibility theorem. No model can do what he claims his does. No model can have a competitive equilibrium with price-taking behavior and partially excludable nonrival goods.

Romer's proposition is stated clearly enough. Now all we have to do is check whether it's valid or not. If I can produce a counterexample, then I will have shown Romer's proposition to be invalid. Let me now produce the counterexample.

Consider an economy where people combine raw labor (n) with skill (x) to produce labor services (e) according to the formula e = xn. Interpret n as hours worked over given period of time and assume, for simplicity, that everyone has the same n. On the other hand, people generally differ in their skill level, x. People with greater skills (or skill sets) are represented by larger values of x.

What makes people operating in the same environment more or less skilled than one other? Well, it could be several things. Consider two laborers, one of which is endowed with a physical tool that doubles labor productivity. Then we can write x = 1 for the one laborer and x = 2 for the other. Now consider two entrepreneurs, one of which is possessed with a "mental tool" (an idea, or some general know-how) that doubles labor productivity. Then we could similarly write = 1 for the one entrepreneur and x = 2 for the other.

Physical and mental tools can differ along an important dimension called "rivalry." Economists call physical objects "rival"(or "subtractable") goods because a physical tool can be in the possession of only one laborer at any given time. The same need not be true for a mental good like an idea. Suppose that "knowing how to perform a task at level x" requires knowledge of a certain recipe. Unlike a physical good, an idea is not subtracted from your mind if you share it with someone else. If I teach you my calculus tool, this in no way diminishes my capacity to use the same calculus tool (or what amounts to the same thing, a perfect replica of my calculus tool). Economists call goods with this property "non-rival" or "non-subtractable" goods.

Alright then, let's proceed to the next step. Assume that the aggregate production function takes the form Y = aE, where a > 0 is a scalar and E represents the aggregate labor input measured in "efficiency units." That is, E equals the sum of e = xn over a population of size N. Let me normalize n = 1 and define X as the sum of x over population N. In this case, E = XN.

Notice that the aggregate production function exhibits constant returns to scale in E. The function is also linear in N. Of course, the function displays increasing returns in X and N together. That is, if we double both X and N, output Y is more than doubled.

The question Romer might ask at this point is "where are the books in this economy?" What he means by this is why can't the smartest person in this economy (the one with the largest x) not publish his knowledge in a recipe book and sell it to the others for a huge gain? This is an excellent question. The answer to it is that knowledge is not always very easily communicated and absorbed by all members of society in this manner. To the extent that knowledge transfer is difficult, the smartest guy in the room has a temporary monopoly over the idea that generates the highest x. Personally, I am surprised that Romer is so offended by this assumption of a missing market. Any university professor knows that distributing the course text book does not, by itself (re: Lucas quote 2009), lead to a growth of his/her students' knowledge base. Some types of knowledge can be sold, but other types of knowledge must be absorbed through effort, not through simple purchase. It is an empirical question as to which type of knowledge transfer mechanism is more or less important.

Next, I want to impose perfect competition. I do this not because I am wedded to the idea that this is how one must model the economy. I do it because Romer claims that it cannot be done.

But wait a minute...how can I assume perfect competition when the smartest person has a monopoly over his/her x? The answer is simple. The people in this economy are competing over the supply of efficiency units of labor e. There is no monopoly over the supply of labor services, e. Under perfect competition, the equilibrium price of an efficiency unit of labor is given by w* = a.  Of course, the measured wage per unit of raw labor (w*x) differs across people according to their skill x. The person with the highest x commands the highest price per unit of raw labor.

I should like Paul to note that Euler's theorem does indeed hold in my economy. The entire output is exhausted as payments for labor services (measured in efficiency units). Would people ever devote costly effort to learn something that would give them a higher x in this competitive economy? Sure, why not? Suppose that some raw labor time can be moved away from work and into a learning activity (l). The opportunity cost of this time is the person's foregone wage w*xl. The benefit is the expected value of learning something new (a higher x).

Anyone with an elementary training in economics can plainly see that the model described above has a competitive equilibrium with price-taking behavior and partially excludable non-rival goods. Ergo, Romer is wrong.

I am led to speculate how Romer might object to my counterexample. I suspect he might claim that the x in my model is not really a non-rival good. I get the feeling he might be defining a non-rival good as an idea that can be costlessly disseminated and instantaneously absorbed throughout the population (unless the use of the idea is protected by patent, etc.). If this is the case, then the argument would seem to be one of semantics.

In any case, I have made my point. Romer's proposition above is invalid. One can model a competitive equilibrium with price-taking and partially excludable non-rival goods. This should not be taken as a criticism against Romer's preferred modeling strategy. I'm actually a fan of his research program. My complaint with Romer's mathiness critique is that it ascribes unseen and unknown ulterior motives to a class of economists that find it fruitful to view growth through the lens of competitive equilibrium.

***
PS. I see that Nick Rowe has offered a thoughtful response to Romer's "whack-a-mole" comment.

How to migrate your Godaddy web hosting to DigitalOcean

Lately I've been reading some good articles about DigitalOcean as a cheap VPS option in online hosting and so I decided to try and subscribe to one.

Since my wordpress website hosting is already expiring I decided to moved the hosting to DigitalOcean and renew the domain name in Godaddy.

Here's how I point my Godaddy domain to DigitalOcean VPS hosting and migrate my wordpress website:

*You must already have a DigitalOcean account with linked payment method (can be either a credit card or paypal).
*Copy all your wordpress files from Godaddy.
*Make a backup of your wordpress database.


  1. Create a droplet in digital ocean.
    1. Distribution = 15.04 x64
    2. Applications = Wordpress 14.04
    3. I chose $5 / month
  2. Follow this article to configure your server: https://www.digitalocean.com/community/tutorials/how-to-install-wordpress-on-ubuntu-14-04.
  3. Migrating your wordpress website:
    1. Using winscp, upload your files in your server's /var/www folder.
    2. Make sure that www-data user can write to the folders where it needed to, for example uploads. Note: use chmod. Note by default the uploaded files are owned by root, use chown and change the ownership to www-data.
      1. >chown www-data:www-data /var/www -R, change the owner and group of /var/www folder from root to www-data. This is done recursively.
      2. >chmod 774, means owner and group (read, write, execute) while others (read-only).
    3. Following the tutorial in #2, you should now have phpmyadmin installed. Restore your wordpress backup.
  4. We then need to point your domain name to the new ip address in digital ocean.
    1. To get your droplet's ip address, go to your digital ocean's droplet's page 
  5. Now that you have your ip address, go to DNS, and add a domain record like this: 
  6. We are done with digital ocean and we will now point godaddy's domain to digital ocean's server.
  7. In Godaddy expand Domains tab.
  8. Chose your domain then click Manage.
  9. In Settings tab, under Nameservers click Manage.
  10. Setup Type=Custom, then add the 3 nameservers below
    1. NS1.DIGITALOCEAN.COM
    2. NS2.DIGITALOCEAN.COM
    3. NS3.DIGITALOCEAN.COM 
  11. After adding hit SAVE.
  12. You should now see the 3 name servers in the next screen.
Wait for 5minutes, then try logging-in in your linux hosting, and in the terminal run:
>whois makeupchum.com

The command above should give you your digital ocean's ip address and name servers.

And that's it! Your wordpress website must now be running in digital ocean. That's in less than 30mins :-)

Common problems I've encountered:

  1. 2 widget were broken, need to set the content again
  2. some folders are not writeable when I uploaded need to execute chmod.
Want to try DigitalOcean? Register with this link.

Poland vs the United States: firearms


This is the fourth article in a short series about Poland, Europe, and the United States. To explore the entire series, click here.




I spent roughly half of my adult life in Poland; for the other half, we lived in the United States. Because of this, my Polish friends sometimes ask about the cultural differences between the two countries. I always struggle to answer on the spot, so I decided to explore some of the most striking dissimilarities in a series of short blog posts. It's only fitting to start with guns.




Although you won't see this brought up by any gun control advocate, Poland has long had some of the strictest firearms regimes in the world - surpassed only by a handful of countries such as Rwanda, Niger, Japan, and North Korea. The roots of this policy are difficult to pinpoint, but it may have had to do with the years of foreign partitions, followed by the Soviet-imposed communist rule; in those trying times, private militias must have been seen as a grave threat to the social order and to the personal safety of the ruling class. Whatever the original reasoning, the effects are plain to see: in today's Poland, there is almost no tradition of gun ownership or hobby shooting sports; the country averages just around one firearm per 100 residents, compared to almost seven in the UK, fifteen in Australia, sixteen in the Czech Republic, or thirty in Austria, Iceland, Finland, and Germany. It's likely that most Poles do not even know anyone who legally owns a gun.




In many ways, the United States may seem like the polar opposite: we have enough privately-owned firearms to equip every single man, woman, and child. In much of the country, there is no permitting process for new purchases and no registration requirements for handguns, rifles, or shotguns. The weapons can be bought at trade shows, given to family members, or loaned to friends. Long guns and ammo can be bought in sporting stores or at Walmart. And sure, if you want to have AR-15 just because it looks like fun, you can; indeed, many people get it for that reason alone.




In America, the right to bear arms is an ancient tradition going all the way back to the early days of the republic. Its constitutional standing is not very different from that of freedom of speech; there is ample evidence that the Founding Fathers envisioned the Second Amendment as the ultimate way to forever protect all other personal liberties, to resist feudal subjugation, and as to ensure the sovereignty of the fledgling country. Although several other, collectivist interpretations of the Second Amendment have been put forward by progressive thinkers, their efforts have not been successful; today, roughly 75% of all Americans believe that the Constitution gives them a well-defined, individual right to own a gun, and the Supreme Court has sided with their views.




In the minds of some citizens, the Second Amendment is still the only thing that stands between freedom and tyranny, be it at the hands of foreign powers or their own government run amok; but for many others, gun ownership is simply an empowering family hobby pursued at any of the tens of thousands shooting ranges all across the United States. In a country populated far less densely than Europe, there is also a clear utilitarian aspect to it all: especially for rural populations, rifles are seen as a necessity for defending one's property against wild animals or scaring away criminals or drunken thugs. Across much of the US, the right to protect yourself with deadly force - without having to retreat or to submit to an assailant - is seen as a fundamental human right.




Of course, all this comes at a price: even though it is overall a very safe country, the US leads the highly developed world in homicides, the bulk of which are committed with guns. The causes of this phenomenon are complex, deeply intertwined with the American psyche and the unique structure of the society; the fashionable practice of placing the blame squarely on the easy availability of firearms does not hold up to closer scrutiny. Nevertheless, it would be dishonest to claim that broad gun ownership comes at no cost to the American public. Some of the most vivid pictures seared into people's minds are the infrequent but soul-crushing school shootings. A more everyday occurrence are police encounters that end tragically because of the presumption that any suspects - even children - may be armed to their teeth.




Over the last century, the worries about gun violence - the bulk of which traces back to drug trade and gang activity - has led to increasing federal and state regulation of firearms. It is probable that some of these rules ended up saving lives with little practical harm to civil liberties; examples of this may include restrictions on fully-automatic weapons or the requirement for seamless background checks. But many other legislative efforts attempted to dismantle or substantially reinterpret the Second Amendment in an emotional response to individual tragedies - and without having an honest, national debate about the amendment's lasting value to the American society. One can mention Chicago, Washington D.C., and San Francisco, all of which attempted to impose blanket bans on handgun ownership. Another good example is New Orleans, where the officials went as far as going door to door and forcibly confiscating firearms in the wake of hurricane Katrina; their intentions may have been pure, but in light of the case law and the prevailing libertarian sentiments that still resonate with many Americans, the wisdom of that gun grab seemed dubious at best.




In recent years, such zealous approaches inevitably meet their end in the courtroom - as noted earlier, judges, much to gun control advocates' chagrin, see the awkwardly-worded Second Amendment as a proclamation of a very clear, individual right. If anything, the zeal of anti-gun activists has made it harder to have a reasonable discussion about gun rights, and enshrined the confusing and half-baked status quo. The constant onslaught of hastily-written legislation, coupled with erratic enforcement of the existing statutes, creates a toxic atmosphere where many firearms enthusiasts and interest groups feel that their freedom is under assault - and that the only way to avoid gradual erosion of constitutional rights is to fight each and every new proposal tooth and nail. One of the sticking points for the National Rifle Association is that federal gun registries would make it easy for the "baddies" to confiscate all firearms in the country. To many, this seemingly preposterous idea rings a lot less hollow after the New Orleans incident.




In Europe, and in Poland in particular, gun laws in the US are often seen as a deranged product of a powerful gun lobby that works against the will and to the detriment of normal citizens; some progressive politicians, scholars, and pundits in the US adopt the same view, demanding new gun restrictions without first winning the hearts and minds of fellow Americans. But when buying into this narrative, it is easy to overlook that the lobby in question is funded chiefly not by large corporations or the super-rich, but by ordinary citizens - and that it enjoys steady popular support, with approval ratings far higher than most politicians can claim.




In my younger years, I remember being entranced by "Bowling for Columbine", viscerally hating the National Rifle Association, and shaking my head in disbelief at the stereotype of gun-totting, trigger-happy Americans. Today, I see the reality as far more nuanced - and if forced to take sides in this fascinating and emotional clash between collectivism and civil rights, I'm far less certain that collectivism would get my vote.





The article continues with a closer look at the costs and politics of gun ownership in the US; for the second part, click here.

New in AFL: persistent mode


Although American Fuzzy Lop comes with a couple of nifty performance optimizations, it still relies on a fairly resource-intensive routine that is common to most general-purpose fuzzers: it continually creates new processes, feeds them a single test case, and then discards them to start over from scratch.




To avoid the overhead of the notoriously slow execve() syscall and the linking process, the fuzzer automatically leverages the forkserver optimization, where new processes are cloned from a copy-on-write master perpetually kept in a virgin state. This allows many targets to be fuzzed faster than with other, conventional tools. But even with this hack, each new input still incurs the cost of fork(). On all supported OSes with the exception of MacOS X, the fork() call is actually surprisingly fast - but certainly does not come free.




For some common fuzzing targets, such as zlib or libpng, the constant cycle of forking and initialization is a significant and avoidable bottleneck. In many cases, the underlying APIs are either stateless, or can be reliably reset to a nearly-pristine state across inputs - so at least in principle, you don't have to throw away the child process after every single run. That's where in-process fuzzing tends to shine: in this scheme, the test cases are generated inline and fed to the underlying API in a custom-written, single-process loop. The speed gains offered by in-process fuzzing can be as high as 10x, but the approach comes at a price; for example, it is easily derailed by accidental memory leaks or DoS conditions in the tested code.




Well, the good news is that starting with version 1.81b, afl-fuzz supports an optional "persistent" mode that combines the benefits of in-process fuzzing with the robustness of a more traditional multi-process tool. In this scheme, the fuzzer feeds test cases to a separate, long-lived process that reads the input data, passes it to the instrumented API, notifies the parent about successful run by stopping its own execution; eventually, when resumed by the parent, the process simply loops back to the start. You just need to write a minimalist harness to implement the loop, but AFL takes care of most of the tricky stuff, including crash handling, stall detection, and the usual instrumentation magic that AFL is designed for:




int main(int argc, char** argv) {

while (__AFL_LOOP(1000)) {

/* Reset state. */
memset(buf, 0, 100);

/* Read input data. */
read(0, buf, 100);

/* Parse it in some vulnerable way. You'd normally call a library here. */
if (buf[0] != 'p') puts("error 1"); else
if (buf[1] != 'w') puts("error 2"); else
if (buf[2] != 'n') puts("error 3"); else
abort();

}

}



For a more complete example, see experimental/persistent_demo/ and be sure to read the last section of llvm_mode/README.llvm. This feature is inspired by the work done by Kostya Serebryany on LibFuzzer (which is, in turn, inspired by AFL); additional credit goes to Christian Holler, who started a conversation that finally prompted me to integrate this mode with the tool.


How to generate wadl via maven plugin

So you've written your web service and would now want to create the wadl for it.

 Assuming you have your web project in eclipse with maven integrated this is what you have to do: 1.) Add the lines below to your pom, you may want to create it's own profile. For example api.
<plugin>
<groupId>com.sun.jersey.contribs</groupId>
<artifactId>maven-wadl-plugin</artifactId>
<version>1.18.3</version>
<executions>
<execution>
<id>generate</id>
<goals>
<goal>generate</goal>
</goals>
<phase>compile</phase>
</execution>
</executions>
<configuration>
<wadlFile>${project.build.directory}/docs/application.wadl</wadlFile>
<formatWadlFile>true</formatWadlFile>
<baseUri>http://czetsuya-tech.blogspot.com/api/rest</baseUri>
<packagesResourceConfig>
<param>com.broodcamp.api.rest</param>
</packagesResourceConfig>
<wadlGenerators>
<wadlGeneratorDescription>
<className>com.sun.jersey.server.wadl.generators.WadlGeneratorApplicationDoc
</className>
<properties>
<property>
<name>applicationDocsFile</name>
<value>${project.basedir}/src/main/resources/application-wadl-doc.xml</value>
</property>
</properties>
</wadlGeneratorDescription>
<wadlGeneratorDescription>
<className>com.sun.jersey.server.wadl.generators.WadlGeneratorGrammarsSupport
</className>
<properties>
<property>
<name>grammarsFile</name>
<value>${basedir}/src/main/resources/application-wadl-grammar.xml</value>
</property>
</properties>
</wadlGeneratorDescription>
</wadlGenerators>
</configuration>
</plugin>

2.) Looking at the plugin configuration above, we now have 2 define 2 files:
application-wadl-doc.xml
<?xml version="1.0" encoding="UTF-8"?>
<applicationDocs targetNamespace="http://wadl.dev.java.net/2009/02">
<doc xml:lang="en" title="czetsuya-tech api">czetsuya-tech api</doc>
</applicationDocs>

application-wadl-grammar.xml
<?xml version="1.0" encoding="UTF-8" ?>
<grammars xmlns="http://wadl.dev.java.net/2009/02" />

3.) Now all you need to do is run the command below in command prompt:
>mvn -Papi clean compile com.sun.jersey.contribs:maven-wadl-plugin:generate
// note that we use api profile as defined above.

In the after-mathiness of discontent

If you're like me, you're probably still trying to wrap your mind around the debate on "mathiness" in the economics profession. I haven't put an inordinate amount of time into the project, but I have made an honest effort trying to understand the nature of Paul Romer's lamentations.

Just what is mathiness, anyway? I'm not sure that a precise and commonly-accepted definition exists. It's not surprising that such a catchy word was soon interpreted in myriad of conflicting ways. This is what happens with words.

To his credit, Romer soon recognized that the word he invented was being interpreted in ways he did not mean. He offers a sort of mea culpa here: Mathiness and Academic Identity. It is definitely a clarification (and I think, a softening) of his initial position. Here are what I take to be its two main points:
So my objection to mathiness is not a critique of the assumptions or structure of the models that others propose. It is a critique of a style that lets economists draw invalid inferences from the assumptions and structure of a model; a style that authors can use to persuade the reader (and themselves) to adopt conclusions that do not follow by the rules of logic; a style that tolerates wishful thinking instead of precise, clearly articulated reasoning. The mathiness that I point to in the Lucas (2009) paper...involves hand-waving and verbal evasion that is the exact opposite of the precision in reasoning and communication exemplified by Debreu/Bourbaki, and I’m for precision and clarity.
I wrote that the economists I criticize for using mathiness are engaged in a campaign of ACADEMIC politics, not one of national politics. Whatever was true in the past, the now fight is over ACADEMIC group identity. For example, one of the things that the people I criticize are campaigning for is a methodological restriction to models with price-taking. For them, price-taking is dogma. To make the case for this restriction, they are not presenting scientific arguments grounded in logic and evidence.
Hmm. He's critical of a style that lets economists draw incorrect inferences from the assumptions of a model. This is in contrast, I suppose, to all the other styles that permit people to draw incorrect inferences from the assumptions of their pet theories. He gives the example of Lucas (2009), to which I will return in a moment. The other charge is that some economists (them, not us of course) are "dogmatic." They campaign for and adopt methodological restrictions, like price-taking behavior, even when the logic and evidence does not permit it.

The two points above are linked to the same phenomenon: the apparent unwillingness of Romer's competitors in the field of growth theory to see the error of their ways and the superiority of his preferred approach. Mathiness is impeding scientific progress in the field of growth theory (and possibly throughout the economics profession as well).

What is the basis for these charges? As an outsider in the field of growth theory, it's hard for me to say (though I do have a paper in the area, which I'll talk about below). I think that Deitz Vollrath has a reasonable take on the issue here: More on Mathiness. Thankfully, we have Brad DeLong (Putting Economic Models in Their Place) doing his best to embellish the critique and apply it more broadly to macroeconomic theory--a subject more familiar to me.

Let's start with DeLong, who states:
He (Romer) seems, to me at least, to be very worried principally about two aspects of modern economic discourse. The first is to take what is true about one restricted class of theories and generalize it, claiming it is true of all theories and of the world as well.
Is there really any economist who behaves in this manner? Do we all not already know that our assumptions are provisional? That we may make one set of assumptions to address some questions and another set of assumptions to address other questions--that we have no grand unifying theory? So who, pray tell do these folks have in mind? Well, Paul Romer's thesis adviser, for one. Here, they quote Lucas (2009) who writes:
Some knowledge can be ‘embodied’ in books, blueprints, machines, and other kinds of physical capital, and we know how to introduce capital into a growth model, but we also know that doing so does not by itself [my italics] provide an engine of sustained growth. 
Now which parts of the quote above constitute a violation of scientific inquiry in your mind? Probably none. But I think it was the last part that got Romer's goat because he might have interpreted it to mean that "we know that Romer's models do not embody a mechanism that can provide an engine of sustained growth." I don't know--that's not the way I interpret the passage. Let's suppose Lucas had instead written "...but we also know that doing so does not necessarily provide an engine of sustained growth." Would that have been better? Can we all just be friends now?

I think it may be instructive to read the section from which the quote was lifted:


Is this really something to get so riled up over? Romer pg. 91 charges Lucas with making "untethered verbal claims"--an opinion he is of course free to hold. But I contend that it is just an opinion. Moreover, it's an opinion over the use of English, not math. It would have been far more useful and compelling, I think, if Romer had instead critiqued the model's internal logic and its ability to interpret the data. Isn't this the way science is supposed to progress? (Romer might reply that he's tried, but that his supervisor just won't listen because he's so dogmatic. I'll return to this possibility below.)

In any case, nowhere do I see evidence of DeLong's outlandish claim that Lucas is peddling an hypothesis he asserts to be true of all theories and of the world as well. But DeLong continues as follows:
Thus what Lucas claims must be true about the world as a matter of correct theory--that the big secret to successful economic growth cannot lie in creating and acquiring the kind of knowledge that gets "'embodied' in books, blueprints, machines..."--rests on the barely-examined decision to restrict attention to only a few kinds of models.
My goodness...this Lucas character...who does he think he is? You know, I have an idea. Why don't we actually go read the offending article and see what he's really up to? To whet your appetite, here's the introductory paragraph:


You know, call me crazy, but that opening passage does not sound like a call to arms to me. Lucas starts off with an interesting question. He bows respectfully to existing growth theory (including Romer's brand). He notes that they are based on important features of reality and that they are interesting theories. It's just that to him...[now, I want you to brace yourself and to please forgive the man...he is, after all, just an academic trying to explore alternative interpretations of the way the world works]...you see, to him, the existing theories of growth are not central (i.e., they are missing something that Lucas thinks is more important).

Lucas then proceeds in this highly provocative way: "In this paper I introduce and partially develop a new model of technical change..." From the way DeLong is writing, you'd think that Lucas had instead written "In this paper, I introduce and develop the grand unifying theory of economic growth and development. I await my second Nobel prize."

You can see how much fun I am having with this. Let me continue, along with DeLong, who writes:
The problem comes with the second principal aspect of "mathiness": to claim that one and only one mode of interaction and one and only one mode of individual decision-making is admissible at the foundation level of economic models. Here Romer attacks the assumption that the only allowable interaction is one of price-taking behavior: selling (or buying) as much as one wants at whatever the single fixed price currently offered by the market is. And here I would attack the assumption that individual decision-making is always characterized by rational expectations.
While there are certainly economists who make liberal use of the price-taking assumption in their research, there are equally many who do not. And I am not aware of any economist who would make the claim that the only allowable interaction is one of price-taking behavior. Many economists do feel more strongly about the desirability of imposing "rational expectations." But there is, of course, a vibrant community of those who feel otherwise. And it's not as if people who employ non-rational expectations models are ostracized from the community--unless you call being appointed a central bank president a form ostracism (see, for example, this piece by Jim Bullard).

Why do people have such a bee in their bonnet when it comes to the assumption of price-taking behavior? It's just a pricing protocol (a mechanism that determines prices). Many macro models, especially in the search and matching literature, use bilateral bargaining protocols to determine prices. Monopolistic competition is an assumed market structure together with an assumed pricing protocol. The pricing protocol there is usually quite restrictive: a monopolistic competitor is only permitted to charge a single price for his product. That is, nonlinear pricing schedules (which would increase both profit and social welfare) are assumed away--despite the overwhelming evidence of their use (e.g., retail and wholesale establishments often apply price discounts on large quantities purchased.)

[Aside: Many people are under the impression that monopoly is necessarily inefficient. This is not a valid conclusion. The conclusion follows from an auxiliary assumption that rules out an optimal nonlinear pricing protocol. Walter Oi makes this point in what is surely one of the best titles ever for an economics article: A Disneyland Dilemma: Two-Part Tariffs for a Mickey Mouse Monopoly.]

For Romer, the issue has to do with (I think) of how to reconcile the costly acquisition of nonrivalous (nonexcludable) ideas with perfect competition. DeLong hints at this when he writes:
Thus Paul Romer sees, in growth theory, the current generation of neoclassical economists grind out paper after paper imposing on the world "the restriction of 0 percent excludability of ideas required for [the] Marshallian external increasing returns" necessary for there to even be a price-taking equilibrium.
But DeLong (and Romer) are (I think) wrong on this dimension, at least, on a technical level. It is in fact possible to write down a growth a model where nonrivalous ideas are partially excludable (subject to costly acquisition) in a competitive equilibrium with price-taking behavior. My paper here (with Glenn MacDonald) constitutes one such example.

[Aside: In an extension of my model with Glenn, entrepreneurs are motivated to discover a technological advancement that, conditional on discovery, is assumed to diffuse rapidly among a small but measurable set of firms. This "small" group of firms on the technological frontier is "large" enough to assume price-taking behavior. The technology leaders earn profits (return on their knowledge capital) while laggards attempt to imitate the leaders--an effort that collectively generates the classic S-shaped diffusion dynamic--a phenomenon ignored by most growth models--including Romer's. An alternative and possibly more appealing set up would have been to permit one firm to have a short-lived monopoly right over a technological discovery. I think it's doubtful that any of our main results would have changed under this alternative specification. It's definitely an interesting question to explore and the alternative specification may have implications for questions that we were not interested in pursuing. The point I want to stress is that we did not assume price-taking behavior out of respect for a dogma. It just turned out to be a convenient way to approach things. And I think the approach is still fine, depending on the set of questions the researcher wants to focus on. Telling me that I must behave otherwise in the interest of science seems rather...what's the word I'm looking for here...I think it starts with a D...].

To many people, the assumption of price-taking behavior and rational expectations is thought to imply no useful role for government policy. In fact, nothing could be further from the truth. It is well-known that the equilibria of noncooperative games are generically suboptimal (so that well-designed interventions can be welfare-improving). For that matter, the equilibrium of a monopolistically competitive model can be efficient (and therefore warrant no government intervention). Adopting any one of these assumptions a priori is not, by itself, going to lead to a predetermined policy recommendation. And yet, DeLong seems to suggest that this is indeed the case when he writes:
And I see, in macroeconomics, paper after paper and banker after banker and industrialist after industrialist and technocrat after technocrat and politician after politician claiming that everything that governments might to to speed recovery must be counterproductive, or at least too risky--because that is what is in the case in a very restricted class of rational-expectations models.  
DeLong claims to see (without providing examples), in macroeconomics, "paper after paper" claiming that everything governments do is worse than useless. As evidence for this this, he cites two economists writing in the 1930s. Why not take a look at what people are publishing in high-level journals today? Here is just one example, drawn from the "freshwater" based Journal of Monetary Economics for March 2015. Among the papers published in this issue, I see:

1. Optimal Taxation with Home Production
2. Macroeconomic Regimes
3. Managing Markets with Toxic Assets
4. Financial Stress and Economic Dynamics: The Transmission of Crises
5. Liquidity, Assets and Business Cycles

I'll let this evidence speak for itself. What of his suggestion that the "austerity" forces are motivated by what is true in a restricted class of rational-expectations models? I'm afraid it's just another preposterous statement on his part. As he notes, recommendations of "austerity" were being made even in the 1930s. But that was well before rational-expectations models even existed. I might add that economists today frequently recommend government interventions that rely on rational expectations (e.g., Michael Woodford's "forward guidance" policy proposal).

Let me conclude now by returning to Romer. I'm still not absolutely sure what the mathiness critique is really all about. I think that Romer might just be frustrated (possibly with some justification) that his ideas haven't swept away his competition. Because his ideas are so firmly rooted in logic and evidence, the only thing that can evidently explain the continued resistance is academic politics shrouded in a cloak of mathiness.

Well, that's one interpretation and, who knows, maybe there's an element of truth to it. But my preferred interpretation is that what we seem to have here is simply a healthy clash of ideas competing in the marketplace for ideas. Let's not get too frustrated when our preferred (and obviously superior) theory does not sweep away the competition.

___________________________________________________
Steve Williamson has his own interesting take on the issue here