Quit smoking in one step

As you might imagine from the title, I’m an ex smoker. I smoked for about 5 years, around half a pack a day on average for the last 3 years of smoking, gone cold turkey 8 months ago. The article name is a joke, the only real step you need to do is never smoke another cigarette. Congratulations, you are now an ex smoker. I’ll try to articulate my thoughts about the whole experience, how I started, why I stopped and what kind of impact did it have on my life.

TL;DR version: if you’re smoking you need to stop as soon as humanly possible. It’s hard for some people, it is easy for some – I was fortunate enough to be in the latter group.

Some facts, por favor?

Smoking is not a habit as some like to say. Masturbating before you go to bed is a habit, twirling your hair is a habit, picking your nose in public is a habit. Wikipedia says: “Addiction is a state characterized by compulsive engagement in rewarding stimuli, despite adverse consequences.” Yes, smoking is a full blown addiction just like those alcoholics, crack cocaine users, heroin junkies and so on. Being addicted to nicotine is far more socially acceptable, and up until very recently in our history was practically considered cool. I don’t think I need to go into much detail as how it’s bad for the smoker. The cigarette risk is cumulative and everyone is very prone to dismiss it since it’s relatively harmless in the very short run. You can’t OD on the cigarette, or smoke so much that you’re unable to come in at work in the morning. A lifelong chain smoker can smoke up to a million cigarettes. Try to imagine them all on the floor of your apartment.

Smoking in Croatia is very widespread; it’s allowed in all the bars, pubs, discos, cafes, etc. The estimated numbers in the country are that the third of the adult population are smokers. That number is absolutely devastating for a country which has a modest population of about 4 million and has more than 8000 deaths deaths per year attributed directly to smoking tobacco. Lung cancer was practically unheard of in the medical community before cigarettes were brought en masse to the general public. I realize you have to die of something, and not all cancer can be attributed to smoking. This is one of those very rare times in life where you can avoid a terrible disease easily – by not smoking. Cancer is not the only unwanted side-effect, you can get chronic obstructive pulmonary diseases, cardiovascular issues, etc. The list is pretty long, and as an average smoker you can definitely expect to have a shorter lifespan on average compared to your fellow nonsmoker. It’s not a 100% chance that you’ll develop cancer, or COPD, or whatever. It’s more like around 50% that you’ll have some adverse effects of the constant smoking which will dramatically decrease your quality of life, decrease your lifespan or even die from it before your time. Feel like rolling the dice?

Why smoke & how does the addicted mind work?

Sure, I’ve laid down all the facts, smoking is terrible, smoking is destructive, smoking is expensive. You might ask: “MrKitty, if you’re so smart why did you smoke the 10000-15000 cigarettes, a conservative estimate? Dumbass.” To this, I have no real answer or explanation, other than – I got addicted like all the other poor bastards. What current smokers and never-smokers have to understand, addiction is surprisingly transparent to the addict. I didn’t really comprehend the reality of my addiction until well after I had stopped completely. When you’re a smoker, the cigarette becomes like a natural extension of you. Of course you’re gonna light one up after lunch, at coffee, at a pub, while drinking beer, walking home etc. You find solace in the cigarette, you find companionship as dumb as it sounds. All of this is, of course, complete and utter horseshit. You don’t find anything in the cigarette, other than the need for more cigarettes and more anxiety. You start smoking these things after a while without even getting any kind of a kick. Your body builds up such a tolerance that you basically only replenish the nicotine in your body without the nice feelings it once had brought you.

Ask any smoker why they smoke despite knowing all the bad stuff about the “habit”. You’ll almost always get the answer “Because I get a kick out of it!” They don’t especially like it, they’re trapped in a vicious cycle of maintaining nicotine levels in their bodies. There is no satiating the hunger, it’s almost always there.

Taken from http://whyquit.com/pr/122711.html
Taken from http://whyquit.com/pr/122711.html

It’s 3:30AM, the club is almost closed. My smoker friends are all out of cigarettes and I maliciously laugh at them. The last one was shared and smoked between the two of them. They’re so used to the cigarettes with their beers that they’re totally cranky now even though they HAVE JUST SMOKED the last cigarette. So, the club is closing, I finished my beer, I say it’s time to call it a night, I stutter to my bike and I go home. But no, the two of them decide to take a walk to the gas station which is some 2 kilometers away from the club and in the wrong direction from their homes to buy a pack of cigarettes or two, and of course proceed to smoke it. Even though it’s the weekend and 4 AM in the morning, they’ve had busy days and they could have just gone home, but no… they went in the cold and bought cigarettes. Yeah, they’re getting their kick all right. If they ever read this post, they’ll recognize themselves, no hard feelings guys. :)

I know I’m taking the moral high ground now, but in my defense I was never so irrational about this stuff. If the cigs ran out, oh well, they ran out, I’d just buy some more in the morning don’t you worry. The addict rationalizes his addiction by calling it a habit, and claiming it somehow improves their lives and their social life. It does nothing of the sort. I gradually started smoking, it was just a couple of cigarettes here and there, nothing special. Little by little I increased the dosage. The little voice inside me kept telling me that this is wrong, but I somehow didn’t care. Cigarette smoking has a level of self-destructiveness attached to it. At first I’d get sick from the smoking, but I kept on pushing like a brave little soldier. So you get used to them, you buy them as soon as they run out, you can’t imagine drinking a fucking cup of coffee without a cigarette, or a beer. Anything, really, you always find some reason to smoke. You justify and rearrange your whole day to smoke. It is a disaster if you leave the house without the pack and lighter.

How and why did you quit, MrKitty?

In the last months it really started to bother me. I’ve been feeling nauseous a lot of the time, I was feeling physically weak. Nothing that can’t be cured with a cigarette, of course. A friend of mine and his girlfriend came to visit me over one weekend in May. Of course, we smoked, we drank, we went out. That Sunday I had an uneasy ache in my lungs. I felt that I really poisoned myself this time. I saw them out of the building, and bummed a cigarette from my friend while they were waiting for the taxi to take them to the bus station as they were leaving. Wow, that cigarette really didn’t hit the spot. In the elevator ride up I decided, okay, I’m qutting. For reals this time, honest to $DEITY!

I had tried quitting already two years before that. I somehow overestimated myself, I got this shit. I can do it. I’ll just smoke a couple over the weekend with the guys, no big deal. Yeah, that didn’t work out. I held out a couple of weeks and basically continued where I had left off. Not sure what was my rationalization then, but it was apparently enough to keep smoking. The first couple of days were no problem. I had missed the smoking to some extent, but it wasn’t terrible. I noticed how much of my daily routine was revolving around smoking. I suddenly didn’t take smoke breaks with my coworkers. I decided to make a compromise, I’ll continue some of this routine so I’d go out with them to keep them company while refraining from smoking myself. I didn’t rob myself of anything I’d been doing before. I still went out to bars, went out to coffee, beers etc. When I was drunk, I would definitely get the urge. Someone is always smoking, you’re always in temptation to have “just one”. If you’re serious about quitting, you need to buckle down and ride it out. Yeah, you’ll want to smoke, you can’t get rid of it. But sooner or later, you find something, and you’ll start appreciating life more as a non smoker.

I started picturing myself getting sick, having to explain to my now small son why I’m dying of lung cancer or something. You might call that hypochondriacal, but if I go down the line of smoking that is a more likely scenario than I would like to have for myself. Well, I said fuck that! This is something that I’ve been putting off long enough, maybe I should just bite the bullet and ride that shit out. So the days went on by, I had no real cravings during the day. The thought of taking up a smoke was following me like a spectre for some time. My friends that would usually smoke with me had to learn that I don’t smoke anymore. The addiction was strong in me after all, its amazing how it haunted my thoughts, how much time I actually spent thinking about cigarettes. I didn’t want to smoke them, but I was always compelled to think about it, getting all euphoric at times that I’m not a smoker anymore. Like a curse had been lifted from me, I’m finally free.

Pros & Cons, in alphabetical order?

Cons:

  • None

Pros:

  • Your taste buds and smells totally awaken. You get used to it, but in the meantime everything smells and tastes delightful. Enjoy it until it becomes the norm. (aprox. 1 – 4 weeks from the last cig)
  • Your stamina is increased by a lot, unbelievable (a couple of months since stopping)
  • You start living a different life, I’ll cautiously say, a healthier life. (from the last cigarette until you die)
  • Financial gain. Cigarettes are expensive, wherever you are, it’s always affordable in the end, but they’re not too cheap.
  • Too many for this puny bullet list.

E-cigarettes?

While they may be free of the 4000 chemicals the anti-smoking lobby is always mentioning, it’s still nicotine and you don’t want to feed the addiction, get rid of it completely, so you don’t succumb to temptation of having that “just one” real cigarette. I know people that have gone onto the E-cigarette, only to chain smoke a pack or two because they were “stressed”. Newsflash, the stress mostly stems from the fact that you’re going through nicotine withdrawal most of the time, and the E-cigarettes do nothing but pump you full of nicotine and are prolonging your misery.

The industry?

They’re mostly big international conglomerates with a lot of cash flow basically selling us an addictive, expensive, highly dangerous poison. It’s somehow OK, while a little weed is a Problem. I guess the taxation of cigarettes comes in nicely, so everyone is happy. It’s okay not to give these guys money. Here’s a John Oliver video covering it, he’ll say it better than me.

Jeff might be sick from all the smoking.
Jeff might be sick from all the smoking.

Any conceivable conclusion?

A colleague of mine at work unwittingly gave me the inspiration to really try quitting. He too, was addicted, and doesn’t smoke anymore. So, it can actually be done? Be a non smoker? I’ve browsed through a website called whyquit.com. A relatively weird site, it looks like it came from the nineties, and it probably is. The guy behind it is called Joel Spitzer. He never smoked which is weird when you hear at first. How can he know anything about it? Well, he can, he never smoked and right off the bat he’s better than you, harsh as it sounds. He has an almost evangelistical approach to treating this addiction, and I feel like he’s a good person. It’s hard to say about people like Joel, you get bits and pieces from the distant American culture, but this guy seems all right. He talks about it from a very nice angle. Here is his palmolive bottle demonstartion. He finishes all his videos with “Never take another puff!”

Whether your motivation is the cash influx, or something else it doesn’t matter, it’s hard to give up the drug. Joel says in one of his videos that if you’re going into smoking, you are putting yourself at very real, albeit distant in time risk. Sure, you might live through your life as a two packs a day smoker and die on your 92nd birthday, or you might die from lung cancer at the ripe age of 54. I’ll go with the option that at least precludes lung cancer and a whole palette of nasty ailments. :)

I realize I may come off as a bit sanctimonious, that was never my intention. If you got any smarts, you’ll drop it cold turkey and never look back. Try to lose the nicotine, everyone has got to find their own way. There is no downside to quitting smoking, always keep that in mind. Smokers are addicts and overcoming an addiction is not easy. I bet a lot of people made it their resolution to stop. My only advice is to try cold turkey, convince yourself of whatever you need in order to stay clean.

How am I now?

I don’t think about smoking anymore. I have a lot of smoker friends, they smoke their stuff, I don’t and that’s pretty much it. The memories of me smoking are becoming unreal, have I ever smoked? It left a little bit of emotional scarring I must confess. Not sure why, I’m probably not going to have health issues, but still, it’s unbelievable that I fell victim to such a dangerous, highly addictive substance. At least I learned a valuable lesson from all of this, I managed to get myself addicted and get myself out of it. Perhaps I’ll be more careful next time with something else. In the meantime, I’m watching my son grow older, enjoying time with my lovely wife and generally taking care of myself and enjoying life as much as possible. If I’m not gonna do it, who is?

A trip to the island of Žirje

This post recounts the day when I took a trip with my brother on the 31st of July, 2015. We always had a wish to go to Žirje, just to visit it. It’s located about 22 km southwest from the town of Šibenik, and is pretty much only accessible by ferry or a catamaran. They have regular lines pretty much all year. Or if you have a boat, just go there.

My brother visits me and my family during the summer, so we get to hang out for a while. This time he brought his bike along with him, so we decided to make it a biking trip. We stocked up on essentials, stuff like sandwiches, water, spare tires, pumps, and a lot of enthusiasm. We went to the Jadrolinija’s ticket office, bought tickets for us and the bikes and went aboard. The rest of the article will be focused on the photos we took and to try to describe my limited history with the island and how it made me feel now.

The weather didn’t really inspire a lot of hope. It was an almost overcast sky, with raindrops swiveling around occasionally. Still, we went to buy the tickets, stock up for everything and catch the ferry. We got aboard the ferry, and proceeded to eat some of the food we had bought earlier. This is a pretty scenic ride actually, and it scenically takes almost 2 hours. But hey, in good company, that’s not so bad. You get a little bit out of your routine, and experience something different whilst stuck on the ferry.

It was windy, but fortunately the clouds were letting up and the day it was actually starting to feel like a regular summer day. Žirje is the furthermost island in the Šibenik’s archipelago, not counting a tiny rock that’s technically even farther than the island itself. This wasn’t my first time taking this ferry to the island. I’ve ridden this exact same ferry at least two or three round trips. The whole trip is 1h 45m one way. I was a part of a crew that was led by the city museum to restore the parts of an entrance to an old fortress that’s located on the south-eastern side of the island.

Finally we get off the ferry, the last preparations are taking place – it’s time to roll. The island itself is very peaceful as there aren’t that many people around even though the summer tourist season is basically at its peak. Žirje is populated with people that own houses and live in Šibenik and come to the island during the weekends, and some people that live year-long, but those are very few. There are people outside of the local convenience store that are chugging beers, elderly sitting and chatting. We start biking, first off we have 50 or 60 meters of uphill climb, but this is nothing. The temperature is almost ideal, very few cars around with wind in our hair, we enjoy the island’s serenity.

When I was working on the island the museum rented a small prefab home that is usually used over the summer for tourists. The owner spoke of how they got the home there in one piece on a huge truck that had a crane and simply placed it on the pre-prepared concrete foundations with working power lines, septic disposal, and of course water. We brought our materials on a truck, concrete, lime and sand. We unloaded all of this at the base of the fortress and hired a local man with a 4×4 Ford jeep of some sort. The car was manufactured in the 1940s and was still in working order more or less. We needed to make 5 or 6 trips altogether to get all the stuff up there. The jeep managed to climb the uncomfortably steep rocky path, and it took us about 5-6 batches to get everything near the entrance to the fortress. The path itself was uncomfortable even on foot. Each morning we’d get up, drive to the fortress which was a couple of kilometers away, place some rocks and wait around until 1PM to go back to the house and have lunch that the boss was cooking for us. A pretty sweet deal, and we were getting paid for it too.

We decided to find the prefab home where I was staying. The wind turbine and more solar panels have not been installed, as the shady proprietor was telling us he’ll install. 5 years have passed since I was last on the island. We went on to find a beach to take a swim and refresh ourselves. The sea was very warm, and there was absolutely no one around. I’ve not been too many times on a beach that had a body of water that was this clean, translucent, colorful. There were some waves about, and the sea bed was very natural, but this meant very sharp underwater reefs combined with all the perturbations, we had to be careful not to fuck ourselves up and cut this trip short. After drying up a bit, we changed back to biking clothes and went on to explore the island some more. We had about 6 or 7 ours all in all, so we couldn’t afford to lounge on this wonderful beach. We got on an unpaved road which are plentiful on the island, and are actively maintained by the local population and various civic departments.

After some riding we decided it’s time to head out to the fortress. Unfortunately, the fortress itself is completely unmarked at the island, and isn’t really visible almost right until you’re on top of it. Since I was working there for a couple of weeks, I knew where it was. We were cycling on beautiful unpaved roads, with the occasional stop to have some cooled beer we held in our saddle bags. Since it was hot and we were physically active the beers would really hit the spot. We left the bikes where it was appropriate and went ahead to climb the path that the old 4×4 jeep managed to get through. The path was completely unrecognizable. It’s incredible how much vegetation reclaims the area that was cleared away so we can actually go through with the jeep. It’s a 5 minute walk or so, not too steep. The view from the fortress is incredible. You can see the open sea with Italy on the other side of it. Of course the curvature of the Earth is concealing Italy’s mainland. Since the visibility was perfect, various distant islands were just barely visible. Geeks that we are, we have maps on our LG G2’s (we have the exact same phone) and were trying to figure out exactly what island we were seeing.

We took our time on the fortress, and I was telling stories the mason was telling me while we were working there. The man did a lot of archaeological excavations in his time, and this wasn’t my first time working with him. Aside from a big wall, only the foundations of the fortress remain. You can make out the rooms. Incredibly, the fortress had plumbing, and even heating. You can see the canals that were running between the rooms. Fascinating stuff, I can picture in my mind the people that are long dead now that had lives, jobs, responsibilities that were walking around this same place. We’re at least 1500 years apart. Who knows how their workday went on in this fortress. They had names, they had girlfriends, some of them were gay, some of them were unhappy, some of them had love problems, while others were just great and most likely all of them stared at one point or another at the same infinitely straight line of the open sea. The history of the fortress is relatively wacky, as it turns out this particular fortress was built and used at the end of the Byzantine power in the early 6th century century. After Justinian’s death, the funding and supply chain stopped and the fortress was abandoned. It’s estimated that the fortress was operational for 15-20 years, and the fact that no soldier graves were found around the fortress seems to support that. The fortress was one of many that was placed around the Adriatic sea to secure trading lines between Italy and Byzantium.

Upon leaving the old abandoned military installation we went to the next abandoned military installation on the island. This one is slightly newer, dating back from the Yugoslav People’s Army. It’s located a couple of kilometers of dirt roads and is on a hill, maybe a hundred meters of elevation or so. We braved the hill without stopping, it was pretty steep but luckily paved so it’s that much easier. We actually encountered a car while going uphill. Funnily, the car had New York license plates. These people were from far away. They were probably visiting their ancestors’ houses, as there was a lot of emigration from the island and in general from these areas to the new world at the turn of the 20th century and later. There was a surprising amount of hikers going around the island, mostly foreign people.

The man I was working with was in the army when the base was actually functional and was serving there. It had a big ass artillery mounted, and some anti-aircraft guns among other things. This was designated to defend against incoming ships, as it was strategically placed. The cannon even had a pivotal role in our own independence war, it was used to shoot at the incoming tanks that were coming in to the Šibenik bridge threatening to attack Šibenik. These were hairy times, and this guy was there when it all happened. The stories about that war are almost always weird and not objective, but this man wasn’t prone for telling bullshit as much as I could gather. The gun, and all of the equipment were stripped away in the nineties after the war was over. You could see only the protruding wires at places. This hasn’t been functional in some time, vegetation is growing all over the place, slowly reclaiming it. Just like the Byzantine fortress.

We came down from the military base, and went to a road that led to the army barracks. It too is mostly unused, however some people seemed to have establish a place for themselves nearby. The entire walkway between the barracks was completely filled with the stuff that fell from the nearby pine trees. The whole thing had a serene quality, the stony floor looked undisturbed for years and years. We took out another beer and a banana, chatted for a while. Suddenly a big dog started barking from the house above. The dog is so used to the solitude, or no one coming near the house that it took some time for him to actually hear us and start barking. This was our cue to leave, apart the incessant barking we were ready to move on. Hunger had started to set in. It was time to find some food, and we were headed back to Muna, that’s where the ferry lands.

After work and after lunch we’d drink some wine and play cards, or listen to music on the computer. The house didn’t have electricity from the grid, but from solar panels. The panels were basically good enough for some light and to charge our phones – if it wasn’t cloudy during the day. I was texting with my girlfriend a lot, and my coworkers made fun of me for it. We played a lot of chess too, and just talked a lot. They called me Vladimir the invincible since the three of them could never beat me at chess. I’m a below average player, I guess they were even worse than that. During the night we’d set out baits for conger eels, 5 or 6 of them. Most of the time we’d catch something, and sometimes nothing. The nights were great, it was so incredibly quiet. There was no light pollution or pollution of any kind in the air. The center of the Milky Way galaxy was clearly visible, the giant disk of stars, dust, planets, black holes was clearly visible in the sky. The vast distance is difficult to comprehend, and I had a first class view of it. You can never really see it in cities or even smaller settlements because of street lighting. I haven’t had a clear view of the Milky Way ever since then.

Muna is a very small settlement, it has a shop, a ticket shop for the ferry and houses, a restaurant or two. We sat down at one of the restaurants and ordered coffee for starters and asked them for the wifi password. The prices seemed a bit high, so we decided to try our luck elsewhere. We used the wifi to find information about restaurants on the island. There was a restaurant a couple of kilometers away. The reviews of the place were good so we paid for the coffee and left. The restaurant was somehow farther than we had imagined. I ran into two friends from Šibenik. One of the women has a family house there and they were lounging about. It was unusual for me to bump into anyone I know on this island, but it’s not so far fetched since I know she has a house there, but I wasn’t thinking about her the whole time. At last, we found the restaurant, and it was actually open. I went in, Hrvoje followed me a minute later, he was securing the bikes. A woman was eating something at one of the tables, plenty of room for us. The owner’s son approached me and told me he was sorry, but they’re all full and cant’t really feed us. Hrvoje came in and I told him sarcastically that there’s no room for us, even though there’s no one in the restaurant. He further explained that they had an event later on with many guests. We had an hour and a half until the ferry departs. An older man, obviously the owner came and said we could sit down, but the time frame was unrealistic for them to cook us anything. Oh well, we’ll just get something to eat at the store.

A decision was made to go for another swim in front of the restaurant. We had a lot of time on our hands, and Muna isn’t too far away. The sun was slowly setting, but it was still warm. The sea was at an ideal temperature. We jumped, swam and dove a lot. I really wanted to stay some more, but time was slipping away and the ferry wouldn’t wait for us.

Even though the sea was basically perfect. I’m not sure what it was, but that’s one of the best times I had at a beach. I’ve been to the beach countless times that summer, but that particular time was simply amazing. The unrelenting passage of time forced us to vacate the pier and start our trek towards the ferry. All this island beauty left us really hungry now. We got into the convenience store to get something to eat. Anything to eat, really. The nice ladies at the shop were sympathetic to our cause, but they had no bread to sell us. One of them must have took pity on us, because she gave us a loaf of bread that was reserved for someone else, but they never showed up. Great, we bought some yogurt, some cheese, some salami and went to the ferry. We got on board and ate it. The entire day of cycling on nothing other than a sandwich at the start of the day, a couple of bananas and some beer. We lounged around the outside deck and watched the flickering lights of the settlements nearby Šibenik. The sun was going down fast.

Everything is sort of slower on islands in general, especially this one since it’s so distant. Žirje is basically dead. I don’t think a lot of people live there, and those that do are elderly. This used to be a bustling port, an island with strategic importance and a population to match. The island is now sparsely populated, and apart from the tourism there’s nothing job-wise. The connection to Šibenik is not all that great which surely plays a role.

The ride back was uneventful. The sun has completely gone down and we’re back in town. The bustling streets, the loads of foreigners walking about the streets. It’s summertime in Šibenik, and it really shows. They bring in hard currency and helps the economy, and it can’t hurt to have a lot of foreign people visiting. Tourism always reflects well for local businesses and practices, it promotes a bit of a metropolitan and urban culture to our small town. Šibenik used to be a powerhouse in terms of various industries, economy, tourism etc. Over the decades Šibenik’s influence and power dwindled, Split and Zadar took over as more important towns. The bike ride to home took another 15 minutes or so. We still had energy. We got something to eat when we got home, and got ready to go to a concert. A legendary Zagreb punk band was coming to Šibenik to play. We were very tired by the time the concert started. The music seemed bland and outright annoying, and the light show was killing me.

It was really time to call it a day around midnight. We came to the concert by car which was parked relatively nearby. I bumped into a couple of more friends. Hrvoje was grumbling that I know a lot of people and bump into someone all the time, and accuses me of spending too much time with each one. I always like to chit chat with people I haven’t seen in a while. You catch up fast, but it takes at least a couple of minutes.

I like the fact that Žirje is so unknown, and that pretty much only locals go there. The island is perfect for biking, and it might even be a better idea to rent something there and stay a couple of days to enjoy it fully. There are no discos there, no fancy restaurants, just the island and its many beaches. I definitely recommend everyone to visit the next time they’re in the area!

This is a picture dump with captions from the trip:

Kuhano vino, iliti Glühwein

Kuhano vino, iliti Glühwein

gluehwein

Posljednjih godina kuhano vino je postalo omiljeno piće božićnih sajmova širom Hrvatske, tako da je ovo zimsko kontinentalno piće prodrlo i do tople Dalmacije. Na sjeveru Hrvatske se nerijetko kuha i doma, ali najčešće u minimalističkoj varijanti, samo sa šećerom i klinčićima. Kako je autor ovog bloga u mladosti posjećivao minhenske božićne štandove i uživao u njihovom gustom i toplom Glühweinu čiji miris se širi gradom, a okus bogat voćem i začinima još dugo pamti, ovaj članak će opisati pravljenje kuhanog vina te vrste.

KUHANO VINO

za 1.5L vina, oko 10 porcija
vrijeme pripreme: 30 minuta

1 limun
2 naranče, ne prevelike
3 štapića cimeta (npr. Kotany)
10 klinčića
5 sjemenki kardamoma (opcionalno)
300g šećera
3dl vode
2 butelje (1.5L) suhog crnog vina
1dl žestice, npr. neutralnije rakije (izbjegavati travaricu) ili vinjaka

  1. Nožem za guljenje povrća ogulite koru s naranči i limuna i stavite je u lonac. Zatim ih iscijedite i to također ubacite u lonac. Dodajte i začine, šećer i vodu. Stavite lonac da jaku vatru i pustite da provri. Kuhajte na laganoj vatri 20-ak minuta, dok oko pola tekućine ne ishlapi.

  2. Ulijte vino i žesticu, lagano promiješajte, i zagrijavajte dok se ne pojave mjehurići. Uklonite s vatre prije nego što tekućina provri.

Kuhano vino poslužite vruće. Možete ga podgrijavati ili održavati vrućim na vrlo laganoj vatri, pazeći da nikako ne počne kipjeti.

About the “ineffectiveness of torture”

A friend of mine posted a commentary about the ongoing torture debate. He was appalled about people arguing that torture doesn’t work. “Why stop there,” he asks. “Does rape work? Let’s have a debate! Is genocide effective? Get some pundits to discuss pros and cons! Does sexual abuse of children yield results? Get some experts on screen!” This line of inquiry prompted me to consider whether the ineffectiveness of torture is ever an acceptable argument against it.

To consider the issue on a broader level, one can imagine “pundits” of other times hotly debating effectiveness of slavery, systemic censorship, forced prison labor, or gladiator battles.

The debate over torture has revealed the ugly fact that torture is widely supported by Americans, and the support has risen in the last several years. I see it as a result of a careful propaganda campaign that made skillful use of the naive portrayals of torture popular in fiction, and especially in pulp. Fiction tends to show torture as the only measure available to defeat infinitely evil opponents. This is so wide-spread that the tvtropes site documents a number of torture-related tropes, such as the “ticking time bomb”. When Americans support torture, they envision this scenario, a fact the agencies promoting their own use of torture happily embraced. If one’s thinking is confined to the ticking time bomb scenario, their moral judgment (and, one might add, decency and good taste) is suspended; they ask themselves nonsensical questions with leading answers, such as “would you torture one person to save a hundred?” (or a thousand, million, etc.) The fact that this scenario is an unrealistic fictional invention fueled by non-fictional propaganda machinery never enters their mind.

Given the way Americans think about torture, it is probably simply easier, and more efficient in the short term, to point out the ineffectiveness of torture than to debunk the ticking-time-bomb image. But in the long run, I would argue that relying on the ineffectiveness argument is an extremely bad idea. Imagine future interrogators and their teams of psychologists and rogue doctors perfecting techniques to use torture effectively and start extracting reliable information from tortured enemies and suspects. An argument against torture hinging on its ineffectiveness would immediately fall apart.

The dilemma whether to use scientific data to back up what is essentially an ethical choice is present elsewhere. For example, lack of measurable differences between races has been cited as argument against racism, sometimes extended to a complete dismissal any notion of race as a “social construct”, like ethnicity. But what if geneticists do discover measurable and important differences between races? Basing what is essentially an ethical judgment on scientific data positions it on thin ice because all scientific views can (and must be allowed to) change. This is why I am against drawing the ineffectiveness argument into the discussion against torture, even if it appears useful in the short term.

Simple symmetric encryption

Encryption. It’s one of those words that programmers and sysadmins dread. Always the complications, always the overhead. There is an entire science and math behind encryption, and if you think about it more closely, it makes sense that it’s so complicated. Imagine that you are in a room full of people and you need to say something to your wife that you don’t want anyone else to understand, but they’re all listening. “Honey, are we having sex tonight? Please? – C’mon, we had sex two weeks ago, what do you want from me?”, the wife answers. But if the conversation goes like “Ubarl, ner jr univat frk gbavtug? Cyrnfr? – P’zba, jr unq frk gjb jrrxf ntb, jung qb lbh jnag sebz zr?”, it would be much harder to understand. This is a simple ROT13, but chances are people won’t understand and chances are you won’t be able to pronounce it anyway. Computer encryption works similarly, but needs to set the encryption keys in plain view of everyone, but the implementation is beyond the scope of this article. Take a look at this article for a better explanation.

The cloud & you

In a recent post I spoke briefly about encryption and the omnipresent cloud, but didn’t really get into it. The article is entertaining the idea that you keep a monthly snapshot of all your pictures or something else valuable on a cloud provider, like Dropbox or Google Drive. The point is, keeping possibly sensitive data somewhere that any bored sysadmin can casually go over your files is a bad idea. All you have is their pinky swear that they won’t do such a thing. Your account can get hacked, as we all saw is perfectly possible with the recent “The Fappening” incident. It’s a bad personal security breach. The best course of action is to nip this scenario in the bud, and simply encrypt your stuff before sending over to a cloud provider.

How to easily encrypt your files? The easiest method is using a symmetrical encryption with openssl. You could use GPG, have a complete set of private/public keys, etc. This complicates matters considerably, and you’re screwed if you lost your private key. If this is a case where you offload an encrypted tarball somewhere, and you lost your equipment, better have that 4096-bit key memorized. What we’ll do instead, is use a regular strong password. Remember, we’re not trying to make it as secure as possible, we’re just making it so not every Tom, Dick and Harry from your friendly cloud provider can view your files if they feel like it. This is by far the fastest and easiest way.

Encrypting:

$ tar c documents | openssl aes-256-cbc -in /dev/stdin -out documents.tar.ssl
enter aes-256-cbc encryption password:
Verifying - enter aes-256-cbc encryption password:

That’s it! Your files have been encrypted. Feel free to throw in z or j to tar because openssl won’t compress data. Also, openssl salts by default, so you don’t have to worry about that. Upload the tarball and you’re done. Of course, keep the password to at least 8 characters, no dictionary words, birthdays, use special characters, etc.

Decrypting:

$ openssl aes-256-cbc -d -in documents.tar.ssl | tar x
enter aes-256-cbc decryption password:

This will decrypt your files. There is one big caveat with this. Say your photographs, or important personal projects consume a lot of space, like 20 GB and have a lot of files. Making a single encrypted tarball every month is OK, but uploading a brand new snapshot from your Cable/ADSL line isn’t. I personally use pycryto, it’s a python script I wrote to recursively encrypt all the files within the current directory, delete the original by default, and replace them with .enc files which are encrypted with your password. The timestamps and permissions are preserved, but in the metadata of the files themselves, not contained in the encrypted files. Even still, it’s very rsyncable like this. I have a copy of my photographs on this very server.

Conclusion – if there is any

Why go through all this trouble? They’re just pictures? That part is true, if it’s only pictures, and not an offsite backup of your important work projects that might not be viewable for everyone. It’s more of a principle. And I realize that this way is not cryptographically the best way possible to encrypt your data, but I feel that it’s good enough so it’s not viewable by default. Plaintext sucks. Also, there’s a pretty good chance no one will ever get to see your files, because they don’t do it in general. I’m a sysadmin too, I have access to sensitive data, but I view it as important cargo. I don’t give a flying fuck what’s in it, I really don’t. It’s all just so unimportant for me to actually take a peak. There’s nothing to gain. I have a job to do. I’ve had various jobs throughout my life, from splitting rocks in a quarry, to basic ship maintenance (sanding the chemicals that make it harder for underwater life to latch on to the ship), hauling around cargo, mostly menial jobs. But I’ve always held the same stance. There is nothing to gain from stealing or cheating anything or anyone, you’ll only get a bad rap if you’re caught, and you have to look yourself in the mirror even if you don’t get caught. Not sure how the people that engage in those activities reconcile with their inner-self.

Encrypt files recursively with openssl

I wrote this program because I had a great idea to offload encrypted versions of my data, but conserving the full directory structure, keeping the permissions and timestamps. This way you can do incremental encrypted snapshots to an untrusted remote server. Always rsync the directory you wish to encrypt someplace else locally, and then run this script.

$ pycrypto.py -e 

This encrypts everything in the "." directory, recursively, and removes the original files. Pass the -n switch to not remove the files.

$ pyrcypto.py -d

This will decrypt everything within "." directory, with the .enc extension. Please be aware that because of the nature of the encryption used, there is no sanity check. If you enter the wrong password while decrypting, the files will be “decrypted” with the wrong password. You’ll get the files, but it won’t be the files you have encrypted in the first place. I’ve considered using a hashing method, but this comprimises security and slows down the process considerably and this was designed to be fast. You can download pycrypto here.

#!/usr/bin/env python2

"""
This script encrypts files in the current (.) directory, including 
hidden files using the AES encryption. The original timestamps are 
preserved and the original files are deleted. A .enc suffix is added 
at the end of each encrypted file. The purpose of the program is to 
encrypt the data, while preserving the original directory structure 
and timestamps so you can safely rsync it to an unsecure location. 
The passphrase needs to be either 16, 24 or 32 bytes long.

You will need to have python-crypto installed on your system, most
distributions have it in their repositories.
"""

from Crypto.Cipher import AES
from stat import *

import os, random, struct, optparse, sys, getpass

# Define options
parser = optparse.OptionParser(usage="%prog --encrypt | --decrypt")
parser.add_option('-e', '--encrypt', dest='enc', action="store_true",
       help='Encrypt the entire current directory including files in'
       ' subtrees and hidden files')
parser.add_option('-d', '--decrypt', dest='dec', action="store_true",
       help='Decrypt the entire current directory including files in'
       ' subtrees and hidden files')
parser.add_option('-v', '--verbose', dest='verb', action="store_true",
       help='Verbose mode')
parser.add_option('-n', '--no-remove', dest='delete', action="store_true",
       help='Do not remove input files once encrypted or decrypted')       
options, files = parser.parse_args()

FILES=[]

def pad_password(pwd):
    "Pad the password to lengths 16, 24, or 32, as needed for AES encryption."
    for size in 16, 24, 32:
        if len(pwd) <= size:
            return pwd + 'x' * (size - len(pwd))
    raise ValueError("password must be 32 characters, or shorter")



def encrypt_file(key, in_filename, out_filename, atime, mtime, perm, chunksize=64*1024):
    if options.verb:
        sys.stdout.write("Encrypting %s\n" % in_filename[2:])
    iv = ''.join(chr(random.randint(0, 0xFF)) for i in range(16))
    encryptor = AES.new(key, AES.MODE_CBC, iv)
    filesize = os.path.getsize(in_filename)

    with open(in_filename, 'rb') as infile:
        with open(out_filename, 'wb') as outfile:
            outfile.write(struct.pack('<Q', filesize))
            outfile.write(iv)

            while True:
                chunk = infile.read(chunksize)
                if len(chunk) == 0:
                    break
                elif len(chunk) % 16 != 0:
                    chunk += ' ' * (16 - len(chunk) % 16)

                outfile.write(encryptor.encrypt(chunk))
    os.utime(out_filename, (atime, mtime))
    os.chmod(out_filename, perm)
    if options.delete == None:
       os.remove(in_filename)


def decrypt_file(key, in_filename, out_filename, atime, mtime, perm, chunksize=24*1024):
    if options.verb:
        sys.stdout.write("Decrypting %s\n" % in_filename[2:])

    with open(in_filename, 'rb') as infile:
        origsize = struct.unpack('<Q', infile.read(struct.calcsize('Q')))[0]
        iv = infile.read(16)
        decryptor = AES.new(key, AES.MODE_CBC, iv)

        with open(out_filename, 'wb') as outfile:
            while True:
                chunk = infile.read(chunksize)
                if len(chunk) == 0:
                    break
                outfile.write(decryptor.decrypt(chunk))

            outfile.truncate(origsize)
    os.utime(out_filename, (atime, mtime))
    os.chmod(out_filename, perm)
    if options.delete == None:
       os.remove(in_filename)

if options.enc and options.dec:
    sys.stderr.write("Please use -e or -d")
    sys.exit(1)

if options.enc == None and options.dec == None:
    sys.stderr.write("Please use -e or -d\n")
    sys.exit(1)

for dirname, dirnames, filenames in os.walk('.'):
    for filename in filenames:
        FILES.append(os.path.join(dirname, filename))

if options.enc:
    pwd = pad_password(getpass.getpass())
    for i in FILES:
       if os.path.islink(i):
           continue 
       encrypt_file(pwd, i, i+".enc",
       os.path.getatime(i), os.path.getmtime(i), os.stat(i)[ST_MODE])

if options.dec:
   pwd = pad_password(getpass.getpass())       
   for i in FILES:
       if os.path.islink(i):
           continue 
       decrypt_file(pwd, i, i[:-4], 
       os.path.getatime(i), os.path.getmtime(i), os.stat(i)[ST_MODE])

International file names in cross-platform programs

I work for a company that builds simulation software with the front-end GUI developed mostly in Python. This document is a slightly modified version of a guide written for the GUI developers to ensure that file names with international characters work across the supported platforms. Note that this document is specifically about file names, not file contents, which is a separate topic.

Introduction

Modern operating systems support use of international characters in file and directory names. Users not only routinely expect being able to name their files in their native language, but also being able to manipulate files created by users of other languages.

Historically, most systems implemented file names with byte strings where the value of each byte was restricted to the ASCII range (0-127). When operating systems started supporting non-English scripts, byte values between 128 and 255 got used for accented characters. Since there are more than 128 such characters in European languages, they were grouped in character encodings or code pages, and the interpretation of a specific byte value was determined according to the currently active code page. Thus a file with the name specified in Python as '\xa9ibenik.txt' would appear to an Eastern-European language user as Šibenik.txt, but to a Western-European as ©ibenik.txt. As long as users from different code pages never exchanged files, this trick allowed smuggling non-English letters to files names. And while this worked well enough for localization in European countries, it failed at internationalization, which implies exchange and common storage of files from different languages and existence of bilingual and multilingual environments. In addition to that, single-byte code pages failed to accomodate East Asian languages, which required much more than 128 different characters in a single language. The solution chosen for this issue by operating system vendors was allowing the full Unicode repertoire in file names.

Popular operating systems have settled on two strategies for supporting Unicode file names, one taken by Unix systems, and the other by MS Windows. Unix continued to treat file names as bytes, and deployed a scheme for applications to encode Unicode characters into the byte sequence. Windows, on the other hand, switched to natively representing file names in Unicode, and added new Unicode-aware APIs for manipulating them. Old byte-based APIs continued to be available on Windows for backward compatibility, but could not be used to access files other than those with names representable in the currently active code page.

These design differences require consideration on the part of designers of cross-platform software in order to fully support multilingual file names on all relevant platforms.

Unicode encodings

Unicode is a character set designed to support writing all human languages in present use. It currently includes more than 100 thousand characters, each assigned a numeric code called a code point. Characters from ASCII and ISO 8859-1 (Western-European) character sets retained their previous numeric values in Unicode. Thus the code point 65 corresponds to the letter A, and the code point 169 corresponds to the copyright symbol ©. On the other hand, the letter Š has the value 169 in ISO 8859-2, the value 138 in Windows code page 1250, and code point 352 in Unicode.

Unicode strings are sequences of code points. Since computer storage is normally addressed in fixed-size units such as bytes, code point values need to be mapped to such fixed-size code units, or encoded. Mainstream usage has stabilized on a small number of standard encodings.

UTF-8

UTF-8 is an encoding that maps Unicode characters to sequences of 1-4 bytes. ASCII characters are mapped to their ASCII values, so that any ASCII string is also a valid UTF-8 string with the same meaning. Non-ASCII characters are encoded as sequences of up to four bytes.

Compatibility with ASCII makes UTF-8 convenient for introducing Unicode to previously ASCII-only file formats and APIs. Unix internationalization and modern Internet protocols heavily rely on UTF-8.

UTF-16

The UTF-16 encoding maps Unicode characters to 16-bit numbers. Characters with code points that fit in 16 bits are represented by a single 16-bit number, and others are split into pairs of 16-bit numbers, the so-called surrogates.

Windows system APIs use UTF-16 to represent Unicode, and the documentation often refers to UTF-16 strings as “Unicode strings”. Java and DotNET strings also use the UTF-16 encoding.

UTF-32

The UTF-32 encoding maps characters to 32-bit numbers that directly correspond to their code point values. It is the simplest of the standard encodings, and the most memory-intensive one.

System support for Unicode

Windows

Windows file names are natively stored in Unicode. All relevant Win32 calls work with UTF-16 and accept wchar_t * “wide string” arguments, with char * “ansi” versions provided for backward compatibility. Since file names are internally stored as Unicode, only the Unicode APIs are guaranteed to operate on all possible files. The char based APIs are considered legacy and work on a subset of files, namely those whose names can be expressed in the current code page. Windows provides no native support for accessing Unicode file names using UTF-8.

The Win32 API automatically maps C API calls to wide (UTF-16) or single-byte variants according to the value of the UNICODE preprocessor symbol. Functions standardized by C, C++, and POSIX have types specified by the standard and cannot be automatically mapped to Unicode versions. To simplify porting, Windows provides proprietary alternatives, such as the _wfopen() alternative to C fopen(), or the _wstat() alternative to POSIX stat(). Like Win32 byte-oriented functions, the standard functions only work for files whose names can be represented in the current code page. Opening a Japanese-named file on a German-language workstation is simply not possible using standard functions such as fopen() (except by resorting to unreliable workarounds such as 8+3 paths). This is a very important limitation which affects the design of portable applications.

Standard C++ functions, such as std::fstream::open, have overloads for both char * and wchar_t *. Programmers that want their programs to be able to manipulate any file on the file system must make sure to use the wchar_t * overloads. The char * overloads are also limited to opening non-Unicode file names.

Unix

The Unix C library does support the wchar_t type for accessing file contents as Unicode, but not for specifying file names. The operating system kernel treats file names as byte strings, leaving it up to the user environment to interpret them. This interpretation, known as the “file name encoding”, is defined by the locale, itself configured with LC_* environment variables. Modern systems use UTF-8 locales in order to support multilingual use.

For example, when a user wishes to open a file with Unicode characters, such as Šibenik.txt, the application will encode the file name as a UTF-8 byte string, such as "\xc5\xa0ibenik.txt", and pass that string to fopen(). Later, system functions like readdir() will retrieve the same UTF-8 file name, which the application’s file chooser will display to the user as Šibenik.txt. As long as all programs agree on the use of UTF-8, this scheme supports unrestricted use of Unicode characters in file names.

The important consequence of this design is that storing file names as Unicode in the application and encoding them as UTF-8 when passing them to the system will only allow manipulating files whose names are valid UTF-8 strings. To open an arbitrary file on the file system, one must store file names as byte strings. This is exactly the opposite of the situation on Windows, a fact that portable code must take into account.

Python

Beginning with version 2.0, Python optionally supports Unicode strings. However, most libraries work with byte strings natively (often using UTF-8 to support Unicode), and using Unicode strings is slower and leads to problems when Unicode strings interact with ordinary strings.

On Windows, Python internally uses the legacy byte-based APIs when given byte strings and Windows-specific Unicode APIs when given Unicode strings. This means that Unicode files can be manipulated as long as the programmer remembers to create the correct Unicode string. It is not only impossible to open some files using the bytes API, they are misrepresented by functions such as os.listdir::

>>> with open(u'\N{SNOWMAN}.txt', 'w'):
...   pass   # create a file with Unicode name
... 
>>> os.listdir('.')
['?.txt']
>>> open('?.txt')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: '?.txt'

Opening the directory in Windows Explorer reveals that Python created the file with the correct name. It is os.listdir and its constraint to return byte strings when given a byte string that creates the problem. os.listdir(u'.') returns the usable [u'\u2603.txt'].

Python 3

Python 3 strings are Unicode by default, so it automatically calls the Unicode versions of Win32 calls and does not exhibit bugs like the listdir bug shown above. On the other hand, Python 3 needs special provisions to map arbitrary Unix file names to Unicode, as described in PEP 383.

File names in applications

Portable programs that want to enable the user to create arbitrary file names must take care how to create and access them. Using portable IO libraries such as gio and Qt resolves many of these problems automatically, but these libraries carry a lot of weight that is unacceptable in many situations. Also, those libraries often don’t interact well with “traditional” C code that accepts file names. In this chapter we present an implementation strategy that enables correct use of Unicode file names with minimal intrusion to the code base.

Since file names are natively bytes on some platforms and Unicode on others, a cross-platform application must choose between these representations. Using Unicode makes programming somewhat easier on platforms with native Unicode APIs, while using UTF-8 bytes has the advantage on platforms with native bytes APIs.

What representation works best depends on the application’s surroundings and the implementation platform. A Python 3 or Java application running on a web server is probably best served by using Unicode consistently and not bothering with Unix non-UTF-8 file names at all. On the other hand, a GTK application, a Python 2 application, or an application needing to interface with C will be off with UTF-8, which guarantees interoperability with the world of bytes, while retaining lossless conversion to Unicode and back.

This guide presents a programming model based on UTF-8 as the file name representation. UTF-8 was chosen for AVL simulation GUIs due to ease of interoperability with various C APIs, including GTK itself. This choice is also shared by the gio library and other modern Unix-based software. Of course, use of UTF-8 is not limited just to file names, it should be used for representation of all user-visible textual data.

Interacting with the file system from Python

Since Python’s built-in functions such as open and os.listdir accept and correctly handle Unicode file names on Windows, the trick is making sure that they are called with correct arguments. This requires two primitives:

  • to_os_pathname— converts a UTF-8 pathname (file or directory name) to OS-native representation, i.e. Unicode when on Windows. The return value should only be used as argument to built-in open(), or to functions that will eventually call it.

  • from_os_pathname — the exact reverse. Given an OS-native representation of pathname, returns a UTF-8-encoded byte string suitable for use in the GUI.

The implementation of both functions is trivial:

  def to_os_pathname(utf8_pathname):
      """Convert UTF-8 pathname to OS-native representation."""
      if os.path.supports_unicode_filenames:
          return unicode(utf8_pathname, 'utf-8')
      else:
          return pathname

  def from_os_pathname(os_pathname):
      """Convert OS-native pathname to UTF-8 representation."""
      if os.path.supports_unicode_filenames:
          return os_pathname.encode('utf-8')
      else:
          return os_pathname

With these in place, the next step is wrapping file name access with calls to to_os_pathname. Likewise, file names obtained from the system, as with a call to os.listdir must be converted back to UTF-8.

def x_open(utf8_pathname, *args, **kwds):
    return open(to_os_pathname(utf8_pathname), *args, **kwds)

def x_stat(utf8_pathname):
    return os.stat(to_os_pathname(utf8_pathname))
...

# The above pattern can be used to wrap other useful functions from
# the os and os.path modules, e.g. os.stat, os.remove, os.mkdir,
# os.makedirs, os.isfile, os.isdir, os.exists, and os.getcwd.

def x_listdir(utf8_pathname):
    return map(from_os_pathname, os.listdir(to_os_pathname(utf8_pathname)))

The function standing out is x_listdir, which is like os.listdir, except it converts file names in both directions: in addition to calling to_os_pathname on the pathname received from the caller, it also calls from_os_pathname on the pathnames provided by the operating system. Taking the example from the previous chapter, x_listdir would correctly return ['\xe2\x98\x83'] (a UTF-8 encoding of the snowman character), which x_open('\xe2\x98\x83') would correctly open.

Any function in the program that accepts a file name must accept — and expect to receive — a UTF-8-encoded file name. Functions that open the file using Python’s open, or those that call third-party functions that do so, have the responsibility to use to_os_pathname to convert the file name to OS-native form.

Legacy path names

to_os_pathname is useful when calling built-in open() or into code that will eventually call built-in open(). However, sometimes C extensions beyond our control will insist on accepting the file name to open the file using the ordinary C fopen() call. Passing an OS-native Unicode file name on Windows serves no purpose here because it will fail on a string check implemented by the Python bindings for the library. And even if it somehow passed the check, the library is still going to call fopen() rather than _wfopen().

A workaround when dealing with such legacy code is possible by retrieving the Windows “short” 8+3 pathnames, which are always all-ASCII. Using the short paths, it is possible to write a to_legacy_pathname function that accepts a UTF-8 pathname and returns a byte string pathname with both Python open() and the C family of functions such as fopen(). Since short pathnames are a legacy feature of the Win32 API and can be disabled on a per-volume basis, to_legacy_pathname should only be used as a last resort, when it is impossible to open the file with other means.

if not os.path.supports_unicode_filenames:
    def to_legacy_pathname(utf8_pathname):
        """Convert UTF-8 pathname to legacy byte-string pathname."""
        return utf8_pathname
else:
    import ctypes, re
    GetShortPathNameW = ctypes.windll.kernel32.GetShortPathNameW
    has_non_ascii = re.compile(r'[^\0-\x7f]').search
    def to_legacy_pathname(utf8_pathname):
        """Convert UTF-8 pathname to legacy byte-string pathname."""
        if not has_non_ascii(utf8_pathname):
            return utf8_pathname
        unicode_pathname = unicode(utf8_pathname, 'utf-8')
        short_length = GetShortPathNameW(unicode_pathname, None, 0)
        if short_length == 0:
            raise ctypes.WinError()
        short_buf = ctypes.create_unicode_buffer(short_length)
        GetShortPathNameW(unicode_pathname, short_buf, short_length)
        short_pathname_unicode = short_buf.value
        return short_pathname_unicode.encode('ascii')

Summary

If this seems like a lot of thought for something as basic as file names with international characters, you are completely right. Doing this shouldn’t be so hard, and this can be considered an argument for moving to Python 3. However, if you are using C extensions and libraries that accept file names, simply switching to Python 3 will not be enough because the libraries and/or their Python bindings will still need to be modified to correctly handle Unicode file names. A future article will describe approaches taken for porting C and C++ code to become, for lack of a better term, Unicode-file-name-correct. Until then, the to_legacy_pathname() hack can come in quite handy.

Handling large sets of photographs and videos

In 2003 my father bought a digital camera for the family. It was an Olympus C-350 Zoom, 3.2 mpix, 3x optical zoom, a 1.8″ LCD display. At that time, at least here in Croatia, having a digital camera was fairly rare. I’m not saying I had it first in my city, but it wasn’t as commonplace as today. This was such a leap from anything that you owned. You could actually take a picture and upload it to the computer. And the image was usually great if the light conditions were optimal, of course. Indoors, and with low lighting the images were terrible.

Šibenik circa 2003/07
Šibenik circa 2003/07 on a good day
Sorry dude, it's 7:59:34 PM on an August the 18th. There's less sunlight than you think.
Sorry dude, it’s 7:59:34 PM on an August the 18th. There’s less sunlight than you think at this time of the year, so better keep the camera perfectly steady for one fifths a second.

This camera wasn’t cheap. It cost a little less than $500. For Croatian standards of the time it was a fair amount of money. Still is actually, but that is the minimum you have to spend to have a decent camera, it was like that then, it’s still like that now.

I was making pictures of the town, taking it on trips, documenting everything. Since I was always a computer enthusiast I was beginning to worry, what if the hard disk failed? I’d lose all of the photographs I had acquired. There are people that seem to underestimate the importance of photos. You take the photos, they’re nice, but they’re not that valuable right at that moment. Looking back 10 years or more, suddenly the pictures become somehow irreplaceable. They’re a direct window into your past, not the blurry vision of the past that most of us have, but something concrete and immutable. I think this especially applies when you have kids, you’ll want the pictures safe and sound, at least for a little while. Everything gets lost in the end, but why be the guy that loses something that could be classified as a family heirloom?

How not to lose the pictures and how to organize them

Here’s a high-level list of what I’ve found to be good practices, to keep it organized and safe:

  • A clear structure of stored photographs/videos. I’ve found that a single root directory with a simple YYYY-MM does the trick. I dislike categorizing pictures with directory names like summer-vacation-2003, party-at-friends-house-whose-name-I-cant-remember or something to that effect. I think that over time, the good times you had get muddled along the way, and you’ll appreciate a simple year-month format to find something or to remember an occasion. It’s like a time machine, let’s see what I was doing in the spring of 2004, and you can find fun pictures along the way.
  • This goes without saying, backups. Buy an external disk, they go cheap, and you can store a lot of photos there. Your disk can die suddenly and without notice, and all your pictures can simply vanish, never to be seen again. Sure, son, I’d love to show you pictures when I was young, but unfortunately, I couldn’t be bothered to have a backup ready and all the pictures are gone.
  • Disaster recovery – imagine your whole building/house burns to the ground. You get nothing but rubble, and although you were meticulously syncrhonizing to your backup every night to an external HDD, everything is gone. Or more realistically, your house gets broken into and they steal your electronics which contain data that is basically irreplaceable. Create a tarball of all your photographs/videos, encrypt it with a GPG key or passphrase, or with a simple SSL encryption and upload it into the cloud of your choice. Even in the event of a burglary/arson with a regular snapshot of about once per two months, you’ll still be able to recover most of the data when you rebuild your house or buy a new computer in the event of a burglary.
  • Print out a yearly compilation of pictures that you like at your local photo lab. Just pick like 40 of the best, with whatever criteria you deem fit. Who knows if the JPEG standard will be readable in 30 years time, but you can always look at a physical picture you can take with you.
Wow, I just called the cops that my house was burglarized. Now it burned down too? If only I had a disaster recovery plan for my valuable photos.
I just called in a burglary at my house. Now it burned down while getting beers from the store? If only I had a disaster recovery plan for my valuable photos on both desktop computer and portable HDD.

Photos

Most digital cameras, be it video or still frames, have pretty lavish defaults with the image quality. This is a very good thing. I like to get a source file that is close as possible as the device has serialized it to a file. Still, if you take a lot of pictures, you’ll quickly notice that it’s piling up. The first thing to do is delete the technically failed ones. Do not delete the pictures where you think that someone is ugly on it, it may end up great in a certain set of circumstances. You never know.

These days even the shittiest cameras boast with huge pixel numbers, like 10, 15 mega pixels or more with a tiny crappy lens and who knows what kind of sensor. Feel free to downsize it to 5-8 mega pixels, with a JPEG quality of 75-80. Quickly you’ll see that now your images consume a lot less space on the HDD, I’m talking about 30% of the original photo, sometimes even less. I spent a lot of time trying to find exactly how the image is degraded. Some slight aberrations can be seen if you go pixel peeping, but screw that, the photos might have sentimental value on the whole, and you’ve saved a lot of hard drive space that you realistically have available. I recommend using the Imagemagick suite for all your resizing needs. Create a directory where you want the recoded images, like lowres:

$ mogrify -path lowres -auto-orient -quality 80 -resize 8640000@ *.jpg

You can set the number of pixels, in this example it’s 8.64Mpix. Choose a resolution and go with it. I generally use 3600×2400 which is 8640000 in pixels. Mogrify is great for this task, it can encode the images in parallel, so if you have a multi-core computer it really shines since the operations involved are very CPU expensive. You can omit the -path switch, and the files will be processed and placed instead of the file, but be careful as this WILL overwrite the original file(s). Don’t test around on your only copy of the file. You can use the generally more safe convert which takes the same argument with a slight difference, it needs the INFILE and OUTFILE argument:

$ convert -auto-orient -quality 80 -resize 8640000@ mypicture.jpg mypicture-output.jpg

or

$ for JPEGS in *.jpg ; do convert -auto-orient -quality 80 -resize 8640000@ $JPEGS $JPEGS-out; done

The problem with this is that you’ll then have a bunch of IMG_xxxx.jpg-out files. This is the longer way around, but once you’re satisfied with the result, delete the original jpeg files and rename it with a program that mass renames or you can use a perl script called ren, my brother and a buddy of his wrote a long time ago and it still works great for a number of circumstances:

$ ren -c -e 's/\-out//'

This will rename all the files that have the -out to empty string, deleting it from the filename essentially. But this is the long way around, I suggest using mogrify. Mogrify had a very very nasty bug. At one point they decided that it would be cool if you have an Nvidia card and the proprietary drivers installed it would use the GPU for all your encoding needs. That sounds great in theory, but I actually had an Nvidia graphics card with the drivers properly installed. How do I know that? Complex 3D video games worked without issues. And guess what else? It didn’t fucking work. It simply hang there, and didn’t do anything, it would never finish a single image. Did I mention that you can’t fallback on the CPU so easily, I mean at all? I googled around, and multiple bugs were filed. I just tried mogrify now when writing this post, seems they have finally fixed it, and I may go back to using it again, instead of unnecessarily complex python scripts that called concurrent converts which number was based on the number of your physical cores.

Video

A nice feature of modern cameras is its ability to record decent video and audio. The cameras mostly use a very good quality preset for the recordings. On my current SLR camera I get 5-6 megabytes per second for a video. Not only that the files are monstrously huge, they also are sometimes in non-standard containers, have weird video and/or audio encodings. You should really convert it to something decent:

$ ffmpeg -i hugefile.mov -c:v libx264 -preset slow -crf 25 -x264opts keyint=123:min-keyint=20 -c:a libmp3lame -q:a 6 output.mkv

This produces a pretty good quality video. I am strongly against rescaleing the video in any way. Use the original resolution, the displays are advancing at a stable pace, you don’t want to unnecessarily scale down the resolution. You can change the quality with -crf from 18-29 are reasonable options, I discussed it in another post in more detail. Also, it decreases the file size by a factor of 15 or more, virtually without perceptible visual loss. As an added bonus you mux it into an open source container with the h264 family of encoders and the venerable mp3 format for audio. That should work on most computer players by default as well as standalone players hooked up to a TV.

I started this post as more of an in-depth technical overview how to store and encode your multimedia and backing it up. But instead I chose to give a high-level overview of what worked for me over the years. Make backups regularly, have a disaster recovery option present if at all possible, and print out some yearly photos. It’s fun to look over the physical pictures, and can be good fun showing it to visiting friends and family. When deciding how much to shrink the files, always keep in mind that you should compress them as much as possible while keeping the subjective perception of the quality as close as possible to the original. What I mean to say, don’t overdo with the quality settings. What matters is how much space is your archive consuming right now, and how are you able to cope with that amount of data.

Data loss is commonplace. Hard drives fail, do not lose 10+ years of photographs because you didn’t have a decent backup. It’s not so hard. Do it now. Don’t lose a part of your personal history, it’s priceless, and cannot be downloaded from the internet again. Always encrypt your stuff before uploading to the ethereal cloud. Maybe you have sensitive pictures that you wouldn’t want anyone else casually looking over just because they happen to be the sysadmin. You wouldn’t make the same kind of privacy breach in other parts of your life, would you?

Match file timestamp with EXIF data

Over the years I’ve collected a lot of pictures, coming close to 20000. Most of these pictures have the exif metadata embedded in the JPEG files. Alas, I was careless with some of the photographs, and when copying over from filesystem to filesystem, creating backups etc., the timestamps got overwritten. So now I had loads of files that had a timestamp of 22nd January 2010 for example. They were most definitely not taken at that date, but rather they were copied then and no preserve timestamp flag was enabled at the time of the cp issued. I googled for a quick solution to my problems, but I could not find anything that would be simple to use, and not clogged up with bullshit. So, I cracked my knuckles and delved into the world of Python:

#!/usr/bin/python2

# You need the exifread module installed
import exifread, time, datetime, os, sys

def collect_data(file):
    tags = exifread.process_file(open(file), 'rb')
    for tag in tags.keys():
        if tag in ('EXIF DateTimeOriginal'):
            return "%s" % (tags[tag])

for file in sys.argv[1:]:
    try:
        phototaken = int(datetime.datetime.strptime(collect_data(file), '%Y:%m:%d %H:%M:%S').strftime("%s"))
        os.utime(file,(phototaken,phototaken))
    except Exception, e:
        sys.stderr.write(str(e))
        sys.stderr.write('Failed on ' + str(file) + '\n')

Basically it takes each file, reads the exif metadata for photo taken and invokes the os.utime() function to set the timestamp to that date. You’ll need the exifread module for Python, this is the simplest one I could find that can do what I needed it to do. I hope someone will find this script useful. You can start it simply with $ exify *.JPG. You can download it here.

Stuffed bell peppers, the Croatian way

Stuffed bell peppers are a staple of cuisines of several southeast-European countries, including Croatia. This recipe, originally published in Croatian, presents how I make them. The translation will hopefully help this lovely Croatian dish reach a wider audience.

In Croatia we typically use the bell peppers of the “babura” variety, but other kinds of bell peppers will do nicely, as long as they are of reasonable size – at least 2 inches in diameter, and 4 inches or more in height.

STUFFED BELL PEPPERS

6 portions
preparation time: about 2 hours, largely unattended

1 onion, chopped
olive oil
salt, pepper
2-3 cloves garlic
1 tbsp paprika
1 pound ground meat, mix of beef and pork
1/2 cup rice
10 bell peppers of medium size
2-3 cups tomato purée (passata di pomodoro)
1 cup wine
water as needed

  1. Put the olive oil in a saucepan over medium heat. When the oil is warm, add onions and cook until soft, about five minutes. When the onions are nearly done, add the garlic, salt, pepper, paprika, and other spices if you like (e.g. ginger, nutmeg, or a dash of cumin). Do not overdo the spices.

  2. While the onions are cooking, wash the bell peppers, cut off the stems, and shake out the seeds. Put the ground meat in a bowl and add the cooked onions. Season with salt and pepper to taste (feel free to try it, a bit of raw meat won’t harm you), add the rice, and mix well.

  3. Stuff the bell peppers with the meat mixture, trying not to pack the meat too tightly. Arrange the peppers in a cooking pot, if possible so that they stand upright holding each other; leave as little room as possible between them. If the peppers do not fit in one layer, cook them in two smaller pots.

  4. Mix the tomato purée and wine and season with salt. Pour the mixture over the peppers in the pot and add water until the peppers are almost fully submerged. If you are using two pots, equally divide the purée and wine between them and then add water. While the peppers are cooking, do not stir them, just occasionally shake the whole pot. Cook for an hour and a half on low heat.

Let the cooked peppers rest for at least an hour. Serve with mashed potatoes and some crusty bread.

Do not throw away the puree in which the peppers were cooking. If some remains uneaten, freeze it and use it as stock for a future dish.