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.