<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Christopher Lott on Medium]]></title>
        <description><![CDATA[Stories by Christopher Lott on Medium]]></description>
        <link>https://medium.com/@chrisinmtown?source=rss-27e344e7e090------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Christopher Lott on Medium</title>
            <link>https://medium.com/@chrisinmtown?source=rss-27e344e7e090------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 06:22:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chrisinmtown/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[New Jersey Red Sauce]]></title>
            <link>https://chrisinmtown.medium.com/new-jersey-red-sauce-e86947d3e09c?source=rss-27e344e7e090------2</link>
            <guid isPermaLink="false">https://medium.com/p/e86947d3e09c</guid>
            <category><![CDATA[recipe]]></category>
            <category><![CDATA[tomato-sauce]]></category>
            <category><![CDATA[new-jersey]]></category>
            <dc:creator><![CDATA[Christopher Lott]]></dc:creator>
            <pubDate>Mon, 25 May 2020 17:36:58 GMT</pubDate>
            <atom:updated>2020-05-25T17:36:58.539Z</atom:updated>
            <content:encoded><![CDATA[<h4>27 August 2016</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*jo3XTkqRQ8tRYMcv.jpg" /></figure><p>This is the holy grail that appears in my local New Jersey farmers’ markets in good years about late August: a huge basket of ripe tomatoes for a very small price. That’s the time to make red sauce!</p><p>My recipe has a quirk or two that I thought might be worth sharing: I roast the tomatoes and use the skins. A roasted tomato skin blends down to a thick paste with all kinds of flavor, no waste! Altho running the oven on a sweaty August day when the A/C is running hard just kills me, the result is great. I’ve tried parboiling the tomatoes to remove the skins, but that yields a watery sauce.</p><p>This yields 8–10 cups of finished sauce, plenty for several meals.</p><p><strong>Ingredients</strong></p><ul><li>About 24 large tomatoes or 40 plum tomatoes</li><li>1 red onion</li><li>3 cloves garlic (or more)</li><li>2 sprigs of fresh basil (or more — depends on your family :)</li><li>1 sprig fresh oregano</li><li>Extra virgin olive oil</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*WMuzFxzwr77YAVps.jpg" /></figure><p><strong>Directions</strong></p><ul><li>Lightly spread olive oil on 2 13x18 sheet trays. Don’t need much, just want to prevent them sticking.</li><li>Wash tomatoes, slice in half and remove the stem/core bit.</li><li>Arrange the halves on baking sheets, leaving a bit of space. Don’t overfill, they throw off a lot of juice as they roast.</li><li>Bake or broil tomatoes at 400 deg F about 20–30 minutes until skins wrinkle, loosen and char. The picture here shows them just barely ready. Extra char means extra flavor! This also evaporates some water.</li><li>While the tomatoes are roasting, dice the onion and crush the garlic, put in pot with generous olive oil, sweat over modest heat until soft and slightly caramelized.</li><li>Pluck skins off tomatoes — tongs work well! Try to resist eating the skins. They’re a little sweet.</li><li>Blend the skins with a bit of tomato juice from the sheet trays until they are paste, add to pot.</li><li>Coarsely chop the tomatoes and add to pot.</li><li>If the juice left on the trays is super thin and watery, put it in a separate pot and boil to reduce it; if it looks ok, add it to the pot also.</li><li>Simmer 15 minutes, I prefer uncovered to let some water escape and reduce it. If you had to reduce the tray juice separately, add it to the main pot.</li><li>Finely chop and add the herbs, simmer another minute or two</li><li>Use an immersion blender in the pot to produce a smooth sauce.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e86947d3e09c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Visit to the Rudas Thermal Bath in Budapest]]></title>
            <link>https://chrisinmtown.medium.com/a-visit-to-the-rudas-thermal-bath-in-budapest-9b3a88b5f302?source=rss-27e344e7e090------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b3a88b5f302</guid>
            <category><![CDATA[budapest]]></category>
            <category><![CDATA[thermal-bath]]></category>
            <category><![CDATA[tourism]]></category>
            <dc:creator><![CDATA[Christopher Lott]]></dc:creator>
            <pubDate>Sun, 24 May 2020 11:47:11 GMT</pubDate>
            <atom:updated>2020-05-24T11:47:11.257Z</atom:updated>
            <content:encoded><![CDATA[<h4>17 September 2017</h4><p>I’m a novice at spa culture, but when in Rome .. so I visited the Rudas Thermal Bath while in Budapest. I hope this blog post will help the next novice :) In Sep 2017 the exchange rate was about 250 HUF for 1 USD. The first picture is the baths from outside. The thermal baths are in the low building on the right, that dome lets in light.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fZAtJVkpJmvTC9t_.jpg" /></figure><p>In a Turkish bath you relax in warm-water pools, steam rooms and hot-air saunas at your own pace. The Rudas complex has a thermal (Turkish) bath, a swimming pool and a “wellness” spa. Swimming pools and spas are everywhere but ancient thermal baths are rare, so I’ll focus only on that.</p><p>First pick your day: men only MWThF, women only Tue, mixed on weekends. Expect to stay an hour or two.</p><p>What to bring: money (HUF 3300 weekdays, 3700 weekends), maybe a bottle of water, possibly your shampoo. Flip-flops? I saw nobody wearing them. Friends? The signs say silence but there was much talking. A bathing suit? Only on the weekends.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/0*QtBajudj--LJYOT5.jpg" /></figure><p>A covering is required, full nudity not allowed. The standard garment for men on their days is a white cloth apron about 14 inches square with a tie string. You wear it in front walking around, turn it around to sit in the sauna — never want bare skin on wood etc. A long swimsuit is so uncomfortable in the sauna that I highly recommend wearing the apron, anyhow it’s included in the entry fee. Some people wore two: one front for modesty and one back for convenience, I wasn’t that savvy on my first visit :). Will you look ridiculous? You will look exactly like everyone else.</p><p>What about securing your stuff while you’re inside? The standard entry fee to the thermal baths includes a private cabin that your wristband locks and unlocks. It’s not exactly high security, so I left my valuables back at my place. The baths have a real safe where you can leave your phone etc. for an additional fee of HUF 500.</p><p>Questions? The price list at the entry was in English. The staff was not fluent in English, but very friendly and spoke enough to get me through.</p><p>OK you’re finally inside! Shower off the street dirt (look for a shower with a soap dispenser) then enter the main chamber. You’ll see five pools: small side pools at 28, 30, 33 and 42°C, and a large center pool at 36°C. Move among them as you like! Side chambers have steam rooms — don’t know the temperature as I could not even see the floor in front of me — and hot air rooms at 50–55°C. Steam first? Steam last? Entirely up to you. After leaving a hot room look for the shower stall with a rope and a bucket of cold water, feels good when dumped over you. (Unlike some spas, there is no open-to-the-outside room where you can cool off in fresh air after some sauna time.) When your skin and heart can’t take anymore and you are on your way out there is a cold water pool at 18°C to, uh, tighten everything up again lol.</p><p>Somewhat confusingly there are no towels here, no terrycloth plush anything. After you leap shrieking from the cold water pool you grab a large sheet off a shelf, take it to a chaise lounge in the relaxation room, wrap yourself up and rest.</p><p>You may wish to return to the showers and use your own fave shampoo before dressing. I was not savvy enough to realize this either on my first vist.</p><p>For what it’s worth, the bathroom doors have no locks and many signs that say one person at a time.</p><p>If you want to splurge, many many services like massages, pedicures etc. are available, see the list below. The cheapest massage is HUF 3400 for 20 minutes. (They tell you the start time for your service so you have to keep an eye on the clock, which frankly disturbed my attempt at relaxation, but what can you do.) Yes it more than doubles the price, I thought the basic massage was great.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/0*YcdT-AilQsugC6Om.jpg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b3a88b5f302" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Polishing a Modern Cast-Iron Pan]]></title>
            <link>https://chrisinmtown.medium.com/polishing-a-modern-cast-iron-pan-98fee198cd99?source=rss-27e344e7e090------2</link>
            <guid isPermaLink="false">https://medium.com/p/98fee198cd99</guid>
            <category><![CDATA[cast-iron-frying-pan]]></category>
            <category><![CDATA[cast-iron-cookware]]></category>
            <category><![CDATA[do-it-yourself]]></category>
            <dc:creator><![CDATA[Christopher Lott]]></dc:creator>
            <pubDate>Sun, 24 May 2020 11:42:23 GMT</pubDate>
            <atom:updated>2020-05-24T11:42:23.740Z</atom:updated>
            <content:encoded><![CDATA[<h4>16 December 2017</h4><p>Can I improve a modern cast-iron pan? I’m a recent convert to using cast-iron pans. They’re cheap at about $25, they work great on an induction stovetop, and they make a mean steak, you should try it: <a href="https://cooking.nytimes.com/recipes/1016334-cast-iron-steak">https://cooking.nytimes.com/recipes/1016334-cast-iron-steak</a></p><p>Why polish my pan? Modern cast-iron pans like those from Lodge are very rough on the inner surface, probably the texture of the sand from the casting, and I suppose they save plenty by not machining them at all after casting. This means unless you fry your egg in a puddle of oil, flipping it for easy-over is tough. And some searching yielded lots of material — hey there’s a surprise lol. For example <a href="http://www.instructables.com/id/Iron-Skillet-Seasoning-Modification/">http://www.instructables.com/id/Iron-Skillet-Seasoning-Modification/</a></p><p>Fanning the flames, a friend gave me a vintage pan that his wife banned from the kitchen (!). The picture below shows the inner surface after I sanded off a few years of rust. Look at the circular machining marks! The cast surface was smoothed down by spinning this against some tool. The result is far smoother than modern pans.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/0*_IA7wxZYlkGp6eCo.jpg" /></figure><p>That vintage pan got me thinking. Could I improve my modern pan that came straight from wally world? Here’s the “before” picture. This is a Lodge skillet that we’ve used to make some great steaks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/0*aa5DCPGtCZ1w5luc.jpg" /></figure><p>Well I don’t own a grinder but I have a sander and plenty of 80 grit discs, so I got to it. This next picture shows my progress after about 20 minutes of sanding. Yes I used a dust collector, no need to breathe more iron filings than necessary. <strong>I SHOULD HAVE STOPPED HERE.</strong> More on that later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/0*eSh2WjQzngXdrK5s.jpg" /></figure><p>After about 45 minutes the base was VERY smooth so I stopped.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/0*yGLIYJWeY5dtXn-x.jpg" /></figure><p>Then the seasoning. This means “varnishing.” I know that sounds gross but in the end you really are trying to create a thin layer of solid dried oil on the surface, just like that layer of stuff on your sheet trays after many years. Here’s a picture of doing it the WRONG way. A coleman stove is insanely hot in small areas, it burns off the oil instead of curing it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Gd5rhQ5MOzjgko8N.jpg" /></figure><p>To season effectively ya gotta use the right oil. Initially I used all the wrong oils. I tried bacon fat, crisco, canola oil. Nothing really worked. Finally I found this blog that convinced me to pony up the $1+/oz for flaxseed oil at my local health-food store: <a href="http://sherylcanter.com/wordpress/2010/01/a-science-based-technique-for-seasoning-cast-iron/">http://sherylcanter.com/wordpress/2010/01/a-science-based-technique-for-seasoning-cast-iron/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*UOZd7dQOQdgcHsHS.jpg" /></figure><p>We followed the directions, put on a thin coat and baked it in a 450 degree oven upside down for an hour. That did NOT fill the house with smoke but it didn’t smell so great either. It’s tough to get the even finish you want all over, but we came close. With time I think the entire surface will darken to an even black.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/0*1NCn3Kmgv-w0Ur8s.jpg" /></figure><p>Looking closely, I found that a thin layer of oil coalesces into tiny drops all over the surface, then those tiny drops turn into little plastic-like dots, very very tough to remove. With the next coat, more dots accumulate until eventually you get a reasonably even coating. So I’m cooking on plastic? Well, uh, it sorta seems like it. But it sure cooks a MEAN egg!</p><p><strong>Update 6 months later:</strong> The baked-on oil came off while trying to clean clean some cooked-on carbonized sauce, something with sugar in it. The finish was more fragile than I expected, I can only guess that I polished off too many imperfections and now the oil cannot grab well. If anyone reads this far, don’t polish your pan down to a mirror, just knock off the high spots and call it a day.</p><p>Also see Stephanie Y.’s discussion of cast-iron cookware: <a href="https://campingcooks.com/cast-iron-cookware-user-guide/">https://campingcooks.com/cast-iron-cookware-user-guide/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98fee198cd99" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Batch Optical Character Recognition on PDFs in Practice]]></title>
            <link>https://chrisinmtown.medium.com/batch-ocr-in-practice-20b6091e4272?source=rss-27e344e7e090------2</link>
            <guid isPermaLink="false">https://medium.com/p/20b6091e4272</guid>
            <category><![CDATA[ocr-software]]></category>
            <category><![CDATA[optical-character-recogn]]></category>
            <category><![CDATA[pdf-converter]]></category>
            <category><![CDATA[ocr]]></category>
            <dc:creator><![CDATA[Christopher Lott]]></dc:creator>
            <pubDate>Fri, 22 May 2020 18:54:10 GMT</pubDate>
            <atom:updated>2020-05-24T11:38:56.427Z</atom:updated>
            <content:encoded><![CDATA[<h4>5 August 2015</h4><p>This blog post shares some lessons learned about batch optical character recognition on PDF documents. There were 3 challenges: deciding whether OCR is necessary for a document, choosing an OCR package, and assessing OCR results.</p><h4>Background</h4><p>In 2014 I drew the assignment of extracting text from over 20,000,000 pages in about 200,000 PDF documents. Some were scans, so choosing an OCR package was a concern, but other issues were just as important. I only needed the words; didn’t have to pick out structured data like tables. (If tables are your thing, check out the Scraperwiki and Tabula projects.) So the first step was to produce a version of every document that would allow text extraction.</p><p>I have to rant a little about PDF. Now that we are in an era of big data, you really have to dial down your expectations when dealing with the portable document format. PDF is a legacy presentation format that’s a thin layer on top of postscript, largely opaque to software tools, and an extremely effective means of locking away text from machine processing. Every PDF text document basically is a bunch of statements that say “paint the following characters at this X,Y pixel position on the page.” Repeat that a bunch of times, then you and I can come along and read “Hello, world!” on our favorite devices, or maybe a table of soccer match scores. You don’t have to paint spaces in PDF, just choose the right pixel positions and hey presto, space between words, or perfect column alignment. PDF supports some intensional mark-up, so tables could in theory be nicely decorated with row and column indicators, but as far as I can tell nobody (i.e., no word processor vendor) uses that PDF feature.</p><p>Before I jump in, I’ll define three document types for clarity. For me a searchable document is one that was produced using a modern text-processing program that prints directly to PDF; i.e., it has characters and words painted on the page, not images. An image document consists solely of pictures, like the output from a scanner. And a mixed document is one with both searchable pages and image pages.</p><p>But in practice, documents often straddle the boundary of those three types. PDF allows multiple layers in a document. Every OCR package that I tried can create an output document with a layer of searchable text on top of the original image (sometimes called “PDF Searchable Image”). The new layer aligns word characters as closely as possible on the word images so that when you double-click on the document, the viewer allows you to select and copy the word under your cursor. Sometimes that selection aligns perfectly with the underlying text, sometimes not so much.</p><p>One last issue is protected documents. PDF supports a couple of digital-rights management features. One encrypts the document (the owner password, I never had to deal with that), and the other feature allows authors to use a password to block viewer actions such as printing, copying or editing. It’s up to the viewer to honor this limited-permissions feature. In my experience every document allowed printing, and I found that printing to PDF format is a crude way of lifting this protection. Also the text-extraction software that I used ignored the protection, which was incredibly convenient for me.</p><h4>Do I need to run OCR on this document?</h4><p>Based on a per-page execution time of several seconds, multiplied by millions of pages, I was highly motivated to minimize the number of pages to process thru OCR. So answering this question, is OCR required, was worth some investment. I tried categorizing files into two buckets: purely searchable content (OCR not necessary); or image content (definitely OCR needed).</p><p>I had no software tools that could evaluate the content of a raw PDF document, i.e., no machine-vision magic, so my recourse was to extract the available text. I used the Poppler package’s command-line “pdftotext” tool. Then I used scripts to evaluate crude heuristics on the extracted text, with the goal of deciding whether a document was searchable. First I checked the quantity of text that was extracted, then checked the text quality. See the end of this post for a Python method that counts character classes.</p><h4>Quantity of available text</h4><p>This heuristic counts characters on each page in the original document as a first step towards deciding if the document is searchable.</p><ol><li>Is every page completely empty? An empty page in pdftotext output probably means the original document has an image there. So if no page has text, you have fairly high confidence that the document has only images, and no further classification is required.</li><li>Are some pages completely empty? This probably means the document has mixed content; i.e., both searchable and image pages. But what’s the acceptable threshold, 5%? If your documents were produced by members of the legal profession then it’s likely the least amount of text on any page will be “This page intentionally left blank” and you will have very, very few truly empty pages. Alternately (and I’ve seen this), if someone scanned a one-sided document using two-sided mode, you could have 50% empty pages in a perfectly searchable document!</li><li>Does every page have characters? This may mean that the document is searchable. However, some image pages yield a few (sometimes many) gibberish control characters, so passing this test isn’t any guarantee of text content.</li></ol><p>A caveat: counting characters per page requires detection of page boundaries, and that is unfortunately not straightforward. The Poppler tool writes a form-feed character at the end of every page, as the first character on a line. But sometimes it writes form-feed characters in gibberish pages, and every once in a while a form-feed character amidst the gibberish appears as the first character on a line. So the results of this heuristic are not nearly as solid as I would have liked.</p><p>Note to self: enhance pdftotext to allow use of a null or other seriously unusual character as the page-termination indicator.</p><h4>Quality of available text</h4><p>A document that yields text from every page just might be searchable. But maybe not, and here’s the first pitfall: I found quite a few PDF documents with a layer of impossibly garbled, low-quality text on every page, presumably from a previous OCR pass. On the screen your viewer will just show you the original image. You have to extract the text layer to be sure. In other words, the document appeared to be searchable, but I sure didn’t want the text that it had.</p><p>So I had to develop some quality checks to apply to extracted text.</p><ol><li>Count letters, numbers, spaces, and ordinary punctuation; separately count other characters. Then calculate the percentage of the total number of characters that fall in that “other” bucket. Even rather ordinary text documents have a handful of special characters such as fancy double quotes, long dashes, bullets and others, so a modest number in that bucket is perfectly acceptable. But if it’s more than a few percent, that very likely means pdftotext was not able to extract a satisfactory text from every page — and OCR will be required.</li><li>Count recognized and unrecognized words using a spell checker. A spell checker is readily available on linux systems and offers a fast quality check of words. (I used the Linux utility hunspell.) Mine had an English-language dictionary that included many common first names (“Mary”) and well-known place names (“Wyoming”), but not too many last names nor names of small municipalities in the U.S. So at least a 1% rate of unrecognized words was to be expected. If the document exhibits 10% or more unrecognized words, then very likely the existing text is not satisfactory, possibly it has a layer of poor OCR results, and again OCR will be required.</li></ol><p>I did not calculate other characters nor unrecognized words on a per-page basis. This would be be a useful refinement, because that would allow detecting one page among hundreds that has thousands of unusual characters; an average over the document would look fine.</p><h3>Which OCR package should I use?</h3><p>Ok you’ve classified your documents into buckets and are ready to start OCR. Which one? Here’s the conclusion right up front: I recommend you start with Nuance products, Omnipage Professional and/or PowerPDF Advanced.</p><p>I was looking for a package to do hands-off, batch conversion. All the packages I found are desktop software for Windows. If you’re willing to spend a few hundred dollars you have many options; trial versions can get you thru if you only need to convert a few hundred pages. You can also spend tens of thousands if you choose.</p><p>Many software packages want to load all the input files, do OCR, query the user for corrections, and coalesce the mess into a single output. This may work for some people but I was looking for true batch: one output file for each input file, unattended operation, don’t stop for anything, give me a detailed report at the end. Spoiler alert: I didn’t find that.</p><p>When I’m doing OCR, should I rasterize? This basically means, should every page be treated as an image, or is it acceptable to use available text? This goes back to the quality assessment from before. Obviously it’s a lot faster to process a mixed-content document if the available text can simply be reused (instead of re-recognized). But if you sent a document off to OCR because of low quality in the available text, then you must tell the OCR to rasterize and recognize. Not all packages offer this feature!</p><h4>OCR Packages</h4><p>Packages in alphabetic order follow. Prices shown below are list but discounts abound. Take my comments about accuracy with a grain of salt; your inputs will not be the same as my inputs so your mileage will certainly vary.</p><p>ABBYY Finereader 12 Corporate: $400</p><p>Batch feature is called the “Task Manager” and it’s on the Tools menu. It will process files from a folder, including subfolders; it will happily create a separate output file for each input file. It does not seem capable of preserving the input folder hierarchy; all output files went to the same output folder. The accuracy was high in my tests, yet still the lowest of the packages I’ve listed here.</p><p>Adobe Acrobat XI: $300</p><p>Batch feature is called “Text Recognition/In Multiple Files” which can be found by clicking on Tools (third toolbar, top right side of the main screen). Processes subfolders, one output for each input. Stops and puts up a prompt if it finds a password-protected file. Does not preserve input directory tree by default; can do so by writing output to same folder as input. Accuracy was quite good in my tests.</p><p>Nuance OmniPage Ultimate (aka v19): $500</p><p>Batch feature is called “DocuDirect” and it’s a separate program that comes with the package. It will process folders and subfolders; if you select the features just right, it will preserve the input directory tree in the output area. One output for each input. Stops and demands a password for a protected file. Seems to take excellent advantage of multi-core processors to run tasks in parallel. The accuracy was excellent. But stability of the batch processor is poor; a fuzzy document will stop it in its tracks, never to recover, derailing a batch with ease.</p><p>Nuance PowerPDF Advanced v1.1: $150</p><p>Batch feature is called “Batch Converter” and it’s reachable from the main program under the Advanced Processing tab. It will process folders and subfolders, preserving the input structure in the output. One output for each input. Will use multiple cores, but not aggressively; what that means is I could not get it to saturate a multi-core host. Accuracy is excllent, as good or better than OmniPage. Bad or fuzzy files did not cause it to hang. The batch processor writes (shock) a plain-text log file to the output directory. Not a replacement for Omnipage Professional; has fewer features and is intended for simpler use cases, not to mention at a lower price point.</p><p>PDF Compressor: $$$$</p><p>This super high-end package is licensed on a per-page basis, with a base price in the thousands of dollars plus a fee per page. Altho the main feature is reducing the size of PDF documents, it also has an extremely capable OCR feature. This package includes a proper batch feature and offers incredibly low-level control over the text-recognition features. It also writes a detailed log file. The speed of the processing was as fast as any other package, and the quality of the output was every bit as good as the Nuance products. But the price point is 10 to 100 times the others.</p><p>ReadIris Corporate 14: $600</p><p>Batch feature is invoked by the “Batch OCR” item which is revealed by clicking on the “From Files” button on the main screen. It will process folders and subfolders, one output for each input, and by default the output directory structure matches the input directory structure. Stops and demands user input on an invalid file; processes without further complaint all protected documents apparently by OCR-ing the image. The accuracy was very good, on par with Acrobat.</p><h4>Results and Gotchas</h4><p>On my desktop machine (only dual core), with my chosen inputs, every package required at least 3 seconds to process a page; some took more. Might be able to drive this down on a machine with more cores. Some packages took good advantage of multiple cores, especially the Nuance packages. Others resolutely stuck to just 1 core (Adobe).</p><p>Gotchas abound, be sure to plan for them: invalid PDFs (some packages halt), password-protected PDFs (some packages halt, others convert anyhow!), and rotated pages (landscape instead of portrait). If you want the batch to run thru to completion, you have to prep the input area for these packages Very, Very Carefully.</p><p>Running large batches can lead to memory-exhaustion and hanging problems, even tho it should not (argh — probably memory leaks). If you’re doing any kind of automation at all, a big problem is discovering after the fact what really happened — which documents could not be processed, which failed during processing, etc. It’s like the desktop software people never heard of something called a “log file”.</p><p>Finally getting support, even as a paying customer, is pretty difficult for these mass-market packages. For example I complained to one esteemed customer support rep about a package (which shall remain nameless) hanging for some large inputs. I watched it stay hung 36 hours before giving up :). They sweetly suggested limiting the batch size to 300 documents. That was just completely unacceptable to me, but hey it got that support ticket closed dang quick, right? And that’s all that matters, right? Sigh.</p><h3>What’s the quality of the OCR result?</h3><p>You’ve successfully pushed documents thru OCR and now you need to evaluate the result. Basically I reused all the heuristics discussed above for assessing the available text in the pre-OCR document.</p><ol><li>Start with the basics: how many pages are in the result? Maybe it’s obvious but you have to check that there’s an output page for every input page. Some packages silently dropped pages on me, that was fatal. Also make sure the result doesn’t have more pages than the input!</li><li>Are all the pages empty? This is a basic sanity test, should never happen, but worth checking.</li><li>Count characters and normalize by pages. A basic minimum (100 chars per page) and maximum (5,000 chars per page) will reveal serious problems.</li><li>What’s the percentage of unrecognized words in the output? The spell-checker again is tremendously useful here. A truly fuzzy document will defeat even the best algorithm. Even a rather modest character non-recognition rate will lead to a significant word-miss rate, which means many mis-spelled words. Setting the threshold for an acceptable misspelling rate is very much dependent on the project and its goals.</li></ol><h3>Summary</h3><p>The lessons in this blog entry stemmed from my encounters with an enormous variety of PDF documents in a large corpus. Many of these issues were total surprises to me, especially the documents with garbage OCR results! Like my father used to say: too soon old, too late smart.</p><h3>Links</h3><ul><li>Nuance: <a href="http://www.nuance.com/">http://www.nuance.com</a></li><li>Poppler: <a href="http://poppler.freedesktop.org/">http://poppler.freedesktop.org</a></li><li>Scraper Wiki: <a href="https://scraperwiki.com/">https://scraperwiki.com</a></li><li>Tabula Project: <a href="https://github.com/tabulapdf/tabula">https://github.com/tabulapdf/tabula</a></li><li>Discussion at Superuser.com: <a href="http://superuser.com/questions/424459/batch-ocr-many-pdfs">http://superuser.com/questions/424459/batch-ocr-many-pdfs</a></li></ul><h3>Code</h3><p>This Python 2 method profiles pdftotext output, yielding some measures for assessing quality of OCR output.</p><pre>def analyze_doc_content(content):<br>    &#39;&#39;&#39;<br>    Analyzes document content and returns the following counts in a tuple:<br>    1. number of form-feed characters at the start of a line (approximates page count)<br>    2. number of empty pages (no chars at all)<br>    3. number of whitespace characters<br>    4. number of lower alpha characters<br>    5. number of upper alpha characters<br>    6. number of digits <br>    7. number of punctuation characters<br>    8. number of other characters<br>    <br>    Form-feed characters can occur anywhere (and do).<br>    A succession of FFs on a line indicate empty pages;<br>    a FF occurring randomly on a page doesn&#39;t mean a damn thing.<br>    This uses a trivial state machine to track the start of lines.<br>    HOWEVER, files exhibit the magic newline-formfeed sequence<br>    at places that are not page breaks, so the count is not a<br>    truly reliable indicator of pages.  Unfortunately.<br>    <br>    `content`: A string that is the output of &quot;pdftotext&quot; with<br>            form-feed characters at the end of each page.<br>    &#39;&#39;&#39;<br>    # initial state<br>    ff_state_begin_line = True<br>    is_page_empty = True<br>    nr_page = nr_empty = nr_ws = nr_lower = nr_upper = nr_digit = nr_punc = nr_other = 0<br>    for c in content:<br>        <br>        # run the form-feed state machine<br>        if c == u&#39;\f&#39;:<br>            if ff_state_begin_line:<br>                # FF occurs at start of line<br>                nr_page += 1<br>                # were any chars found on the page?<br>                if is_page_empty:<br>                    nr_empty += 1<br>                # reset empty check; stay in begin_line state<br>                is_page_empty = True<br>            #else:<br>                # FF occurs mid line.<br>                # don&#39;t change state<br>            # if<br>            # count the FF as WS and skip the tests below<br>            nr_ws += 1<br>            continue<br>        elif c == u&#39;\n&#39;:<br>            ff_state_begin_line = True<br>            is_page_empty = False<br>            # count the LF as WS and skip the tests below<br>            nr_ws += 1<br>            continue<br>        else:<br>            ff_state_begin_line = False<br>            is_page_empty = False<br>        # state machine<br>            <br>        # count character classes<br>        if c in u&quot;abcedfghijklmnopqrstuvwxyz&quot;:<br>            nr_lower += 1<br>        elif c in u&quot;\u0009\u000B\u000C\u000D\u0020\u0085\u00A0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u200B\u2028\u2029\u202F\u205F\u2060\u3000\uFEFF&quot;: <br>            # never get here on \f or \n<br>            nr_ws += 1<br>        elif c in u&quot;~!@#$%^&amp;*()[]{}&lt;&gt;-_+=:;\&quot;&#39;`,.?/\\|&quot;:<br>            nr_punc += 1<br>        # fancy quotes and dashes<br>        elif c in u&quot;\u0060\u00B4\u02B9\u02BB\u02BC\u02BD\u2018\u2019\u201B\u2032\u2035\u275B\u275C\u02BA\u2033\u3003\u201C\u201D\u00AD\u2010\u2011\u2012\u2013\u2014\u2015\uFE58\uFE63\uFF0D&quot;: <br>            nr_punc += 1<br>        elif c in u&quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ&quot;:<br>            nr_upper += 1<br>        elif c in u&quot;0123456789&quot;:<br>            nr_digit += 1<br>        else:<br>            # print(&quot;Other char: %s (%x)&quot; % (c, ord(c)))<br>            nr_other += 1<br>            <br>    # for c</pre><pre>return (nr_page, nr_empty, nr_ws, nr_lower, nr_upper, nr_digit, nr_punc, nr_other)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20b6091e4272" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basic Big Data Profiling in Python]]></title>
            <link>https://chrisinmtown.medium.com/data-profiling-in-python-8e94239e3dae?source=rss-27e344e7e090------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e94239e3dae</guid>
            <category><![CDATA[data-profiling]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Christopher Lott]]></dc:creator>
            <pubDate>Fri, 22 May 2020 18:48:03 GMT</pubDate>
            <atom:updated>2020-05-24T11:39:27.796Z</atom:updated>
            <content:encoded><![CDATA[<h4>12 Dec 2014</h4><p>This blog entry offers some simple Python 2 scripts for profiling raw data.</p><p>I was working with a customer to help them understand just exactly what data they are receiving, what it means and how they might best take advantage of it. Some is big data (hundreds of millions of rows in daily deliveries of comma-separated value files), and some is little data (thousands of rows in monthly deliveries of excel workbooks). So I needed some basic tools to gain preliminary insights into the files. I was also learning python so I chose that to build the scripts.</p><p>Data profiling? Ok this is a four-dollar word that just means figuring out the longest and shortest string values, the greatest and least number values, the number of unique values and their frequencies, and so on. Getting this little collection of descriptive statistics on a CSV or spreadsheet file can be remarkably insightful. This is especially useful to do a quick check of fields (columns) that are supposed to have a restricted set of values, or never be empty.</p><p>Of course this bit of data profiling could easily be done with a very small handful of SQL queries. But lately I’ve been hit repeatedly with data long before it goes thru any extract-transform-load (ETL) tools, so I get to analyze raw files.</p><p>See below for these scripts:</p><ol><li>profile_csv.py, a script that uses standard Python library to iterate over a comma-separated value file.</li><li>profile_excel.py, a script that uses the (immensely useful) xlrd library to iterate over an Excel workbook, either old or new format. You can get xlrd from <a href="https://pypi.python.org/pypi/xlrd">https://pypi.python.org/pypi/xlrd</a></li><li>tablestat.py, a couple of Python classes that support gathering descriptive statistics from rows of tabular data.</li></ol><p>I know I should be using Python 3, but my customer is still stuck on version 2. And admittedly these scripts are way, way wrong for data that’s hundreds of millions of rows, they’re just way too slow. Still these have been a useful tool in my bag. If these help you please drop me a line.</p><h4>profile_csv.py</h4><pre># Imports from the standard Python 2.7 library<br>from __future__ import print_function<br>import csv<br>import datetime<br>import getopt<br>import sys<br><br># Local import - tablestat.py defines class TableStat etc.<br>import tablestat <br><br>&#39;&#39;&#39;<br>Script to profile the values in a table read from a CSV file.<br>Keeps relatively little data so should be able to handle very large inputs.<br>&#39;&#39;&#39;<br> <br>def profile_csv(header_skip, table, unique_max, file_obj):<br>    &#39;&#39;&#39;<br>    Reads a CSV file using csv.reader<br>    &#39;&#39;&#39;<br>    ts = None<br>    rownum = 0<br>    column_names = []<br>    reader = csv.reader(file_obj)<br>    for row in reader:<br>        # skip header rows as directed, possibly zero<br>        if rownum &lt; header_skip:                 <br>            # First ensure list is the right length<br>            while len(column_names) &lt; len(row):<br>                column_names.append(&quot;&quot;)<br>            # catenate values to form column names<br>            column_names = [ column_names[i] + str(row[i]) for i in xrange(len(row)) ]<br>            # detect the last header row           <br>            if rownum + 1 == header_skip:<br>                # instantiate the object<br>                ts = tablestat.TableStat(unique_max, column_names)<br>        else:<br>            # instantiate the stat collector bocs there were no header rows<br>            if ts is None and header_skip == 0:<br>                ts = tablestat.TableStat(unique_max, [])<br>            # analyze this data row (it&#39;s not a header)<br>            # SAMPLE 1%<br>            #if rownum % 100 == 0:<br>            ts.analyze_row(row)<br>        # finally increment the row number<br>        rownum += 1<br>        # be verbose during very large jobs<br>        if rownum % 1000000 == 0:<br>            print(&quot;%s row %d&quot; % (datetime.datetime.now(), rownum), file=sys.stderr)<br>            sys.stderr.flush()<br>    # for all rows<br>    if rownum == 0:<br>        print(&quot;No rows read&quot;)<br>    elif table: <br>        ts.print_report_thead(&quot;&quot;)<br>        ts.print_report_tbody(&quot;&quot;)<br>    else: <br>        ts.print_report()<br> <br>def usage():<br>    &#39;&#39;&#39;<br>    Prints a usage message and exits.<br>    &#39;&#39;&#39;<br>    print(&#39;profile_csv.py [options] [file.csv]&#39;)<br>    print(&#39;Reads from stdin if no file is given.&#39;)<br>    print(&#39;Options:&#39;)<br>    print(&#39;   -h header row skip count (default 1)&#39;)<br>    print(&#39;   -t tabular format report (default no)&#39;)<br>    print(&#39;   -u unique-limit (default 20)&#39;)<br>    sys.exit()<br><br>def main(args):<br>    &#39;&#39;&#39;<br>    Parses command-line arguments and profiles the named file.<br>    &#39;&#39;&#39;<br>    try:<br>        opts, args = getopt.getopt(args, &quot;h:tu:&quot;)<br>    except getopt.GetoptError:<br>        usage()<br>    # default values<br>    hskip = 1<br>    table = False<br>    umax = 20<br>    for opt, optarg in opts:<br>        if opt in (&quot;-h&quot;):<br>            hskip = int(optarg)<br>        elif opt in (&quot;-t&quot;):<br>            table = True  <br>        elif opt in (&quot;-u&quot;):<br>            umax = int(optarg)<br>        else:<br>            usage()<br>    if len(args) == 1:<br>        print(&quot;Reading from file &quot; + args[0],file=sys.stderr)<br>        with open(args[0]) as file_obj:<br>            profile_csv(hskip, table, umax, file_obj)<br>    else:<br>        print(&quot;Reading from stdin&quot;, file=sys.stderr)<br>        profile_csv(hskip, table, umax, sys.stdin)<br><br># Pass all params after program name to our main<br>if __name__ == &quot;__main__&quot;:<br>    main(sys.argv[1:])</pre><h4>profile_excel.py</h4><pre># Imports from the standard Python 2.7 library<br>import getopt<br>import sys</pre><pre># xlrd, see <a href="http://www.python-excel.org/">http://www.python-excel.org</a> and <a href="https://pypi.python.org/pypi/xlrd">https://pypi.python.org/pypi/xlrd</a><br># developed with version 0.9.3<br>from xlrd import open_workbook</pre><pre># Local import - tablestat.py defines class TableStat etc.<br>import tablestat</pre><pre>&#39;&#39;&#39;<br>Script to profile the values in sheets within an Excel file (xls or xlsx).<br>&#39;&#39;&#39;<br> <br>def profile_excel(header_skip, table, unique_max, file_name, sheet_index):<br>    &#39;&#39;&#39;<br>    Reads a XLS file using xlrd<br>    Uses on-demand features to reduce memory requirements.<br>    TODO: Send date-time values as type datetime.datetime (not float)<br>    &#39;&#39;&#39;<br>    ts = None<br>    # detect failure to do anything<br>    found_sheet = False<br>    with open_workbook(file_name, on_demand=True) as wb_obj:<br>        sheet_names = [ n for n in wb_obj.sheet_names() ]<br>        # print(&quot;Sheet names: &quot; + &quot;,&quot;.join(sheet_names))<br>        for idx in xrange(len(sheet_names)):<br>            if sheet_index is not None and sheet_index != idx:<br>                continue<br>            s = wb_obj.sheet_by_name(sheet_names[idx])<br>            column_names = []<br>            for rownum in range(s.nrows):<br>                # get the row&#39;s values as a regular list<br>                row = [ s.cell(rownum,col).value for col in range(s.ncols) ]<br>                # skip header rows as directed, possibly zero<br>                if rownum &lt; header_skip:<br>                    # gather header contents to use as cell names<br>                    # First ensure list is the right length<br>                    while len(column_names) &lt; len(row):<br>                        column_names.append(&quot;&quot;)<br>                    column_names = [ column_names[i] + str(row[i]) for i in xrange(len(row)) ]<br>                    # detect the last header row           <br>                    if rownum + 1 == header_skip:<br>                        # instantiate the stat collector<br>                        ts = tablestat.TableStat(unique_max, column_names)<br>                else:<br>                    # special case for header-free inputs<br>                    if ts is None and header_skip == 0:<br>                        ts = tablestat.TableStat(unique_max, [])<br>                    # this is a data row (not a header), analyze it<br>                    ts.analyze_row(row)<br>            # for all rows<br>            # Free some memory<br>            s = None<br>            wb_obj.unload_sheet(sheet_names[idx])<br>            # print report for this sheet<br>            if table: <br>                # emit header when the first sheet is found (a bit of a hack)<br>                if not found_sheet: ts.print_report_thead(&quot;Sheet name,Sheet index,&quot;)<br>                ts.print_report_tbody(&quot;%s,%d,&quot; % (sheet_names[idx], idx))<br>            else: <br>                print (&quot;---Begin sheet: &#39;%s&#39; (index %d)---&quot; % (sheet_names[idx], idx))<br>                ts.print_report()<br>                print (&quot;---End sheet: &#39;%s&#39; (index %d)---&quot; % (sheet_names[idx], idx))<br>            # If we got here, we found a sheet.<br>            found_sheet = True<br>        # for all sheets<br>    # with<br>    # warn on bad arguments<br>    if not found_sheet:<br>        print(&quot;Failed to find sheet at index %d&quot; % sheet_index)<br>        <br>def usage():<br>    &#39;&#39;&#39;<br>    Prints a usage message and exits.<br>    &#39;&#39;&#39;<br>    print(&#39;profile_excel.py [options] file.xls | file.xlsx&#39;)<br>    print(&#39;Options:&#39;)<br>    print(&#39;   -h header row skip count (default 1)&#39;)<br>    print(&#39;   -s sheet-index (default all)&#39;)<br>    print(&#39;   -t tabular format report (default no)&#39;)<br>    print(&#39;   -u unique-limit (default 20)&#39;)<br>    sys.exit()</pre><pre>def main(args):<br>    &#39;&#39;&#39;<br>    Parses command-line arguments and profiles the named file.<br>    &#39;&#39;&#39;<br>    try:<br>        opts, args = getopt.getopt(args, &quot;h:s:tu:&quot;)<br>    except getopt.GetoptError:<br>        usage()<br>    # default values<br>    hskip = 1<br>    table = False<br>    sheetidx = None<br>    umax = 20<br>    for opt, optarg in opts:<br>        if opt in (&quot;-h&quot;):<br>            hskip = int(optarg)<br>        elif opt in (&quot;-s&quot;):<br>            sheetidx = int(optarg)<br>        elif opt in (&quot;-t&quot;):<br>            table = True  <br>        elif opt in (&quot;-u&quot;):<br>            umax = int(optarg)<br>        else:<br>            usage()<br>    if len(args) != 1:<br>        usage()<br>    profile_excel(hskip, table, umax, args[0], sheetidx)</pre><pre># Pass all params after program name to our main<br>if __name__ == &quot;__main__&quot;:<br>    main(sys.argv[1:])</pre><h4>tablestat.py</h4><pre># future must be first<br>from __future__ import print_function<br>import datetime</pre><pre># Simple enum<br># <a href="http://stackoverflow.com/questions/36932/how-can-i-represent-an-enum-in-python">http://stackoverflow.com/questions/36932/how-can-i-represent-an-enum-in-python</a><br>#class Enum(set):<br>#    def __getattr__(self, name):<br>#        if name in self:<br>#            return name<br>#        raise AttributeError<br># This avoids repeating string constants<br>#Datatype = Enum([&quot;charstring&quot;, &quot;digitstring&quot;, &quot;number&quot;, &quot;date&quot;, &quot;mixed&quot;, &quot;unknown&quot;])<br># Constant values for speedy comparisons.<br># A pseudo enum is clearer but runs lots of code.<br>datatype_unknown = -1<br>datatype_charstring = 0<br>datatype_digitstring = 1<br>datatype_number = 2<br>datatype_date = 3<br>datatype_mixed = 4</pre><pre>def get_datatype_name(d):<br>    &#39;&#39;&#39;<br>    Translates integers to strings for reporting.<br>    &#39;&#39;&#39;<br>    if d == datatype_charstring:     return &quot;Charstring&quot;<br>    elif d == datatype_digitstring:  return &quot;Digitstring&quot;<br>    elif d == datatype_number:       return &quot;Number&quot;<br>    elif d == datatype_date:         return &quot;Date&quot;<br>    elif d == datatype_mixed:        return &quot;Mixed&quot;<br>    else:                            return &quot;Unknown&quot;<br>    <br># Inherits only from object<br>class TableStat(object):<br>    &#39;&#39;&#39;<br>    Provides methods to gather and report descriptive statistics on a <br>    table of strings; for example, useful to profile a CSV file.<br>    Also handles integer, float and None values.<br>    <br>    Designed to be instantiated with a list of column names, but can<br>    also be created with an empty list; it will then self-assign names.<br>    <br>    Combines count of &quot;None&quot; values with count of empty string values.<br>    <br>    This code has been tuned for performance to handle large inputs.<br>    On a 3.1GHz win7 PC this requires about 1 min / 1 million rows,<br>    depending on the number of columns of course.</pre><pre>Useful attributes: <br>        unique_max (integer)<br>        row_count (integer)<br>        stats (list of ColumnStat objects)<br>        <br>    Profiled with &quot;-m cProfile&quot; arguments to python<br>    &#39;&#39;&#39;<br>    <br>    def __init__(self, unique_max_count, column_list):<br>        &#39;&#39;&#39;<br>        Constructor accepts an ORDERED list of column names.<br>        If the list is empty, assigns names as it does.<br>        &#39;&#39;&#39;<br>        # validate the input arguments<br>        if not isinstance(unique_max_count, int):<br>            raise Exception(&quot;Expected int but received %s&quot; % type(unique_max_count))<br>        if not isinstance(column_list, list):<br>            raise Exception(&quot;Expected list but received %s&quot; % type(column_list))<br>        # Keep the limit on unique values<br>        self.unique_max = unique_max_count<br>        # Number of rows seen<br>        self.row_count = 0<br>        # List of stat-collection objects, one per column<br>        self.stats = [ ColumnStat(i, column_list[i], self.unique_max) for i in xrange(len(column_list)) ]<br>            <br>    def analyze_row(self, data_list):<br>        &#39;&#39;&#39;<br>        Gathers statistics from the ORDERED list of data, which must match<br>        match the order and count of columns given to constructor.<br>        &#39;&#39;&#39;<br>        self.row_count += 1<br>        # compute length once, not repeatedly<br>        datalen = len(data_list)<br>        # Extend for wider-than-expected rows; nothing to do for narrow rows.<br>        if len(self.stats) &lt; datalen:<br>            # Don&#39;t warn if column names began as an empty list<br>            if  len(self.stats) &gt; 0:<br>                print(&quot;Warning: input row %d has %d columns but expected %d&quot; % (self.row_count, datalen, len(self.stats)))<br>            while len(self.stats) &lt; datalen:<br>                # Grow the list of column stat objects to allow<br>                # extra columns, or starting with no columns defined<br>                self.stats.append(ColumnStat(len(self.stats), None, self.unique_max))<br>        # Analyze each field in this row<br>        for i in xrange(datalen):<br>            self.stats[i].analyze_value(data_list[i])</pre><pre>def print_report(self):<br>        &#39;&#39;&#39;<br>        Prints report on all columns to stdout, one result per line.<br>        This is convenient for humans.<br>        &#39;&#39;&#39;<br>        print(&quot;Row count = %d&quot; % self.row_count)<br>        print(&quot;Note: unique value limit = %d&quot; % self.unique_max)<br>        for i in xrange(len(self.stats)):<br>            self.stats[i].print_report()<br>    <br>    def print_report_thead(self, prefix):<br>        &#39;&#39;&#39;<br>        Prints header for column-oriented report.<br>        Prefix is used for additional column heads.<br>        &#39;&#39;&#39;<br>        self.stats[0].print_report_head(prefix)<br>        <br>    def print_report_tbody(self, prefix):<br>        &#39;&#39;&#39;<br>        Prints body of column-oriented report.<br>        Prefix is used for additional data columns.<br>        &#39;&#39;&#39;<br>        for i in xrange(len(self.stats)):<br>            self.stats[i].print_report_row(prefix)</pre><pre># Inherits only from object<br>class ColumnStat(object):<br>    &#39;&#39;&#39;<br>    Gathers and reports descriptive statistics on a <br>    collection of values, such as a single column in a table.<br>    Constructor takes index, name, unique_max limit.<br>    <br>    Useful attributes:<br>        name (string)<br>        datatype (inferred)<br>        empty (count of empty values)<br>        nonempty (count of non-empty values)<br>        values (set of unique values, up to limit)<br>  freqs (dict of unique values and their frequencies)<br>        minval, maxval (minimum and maximum numeric values)<br>        minlen, maxlen (minimum and maximum string lengths)<br>    &#39;&#39;&#39;</pre><pre>def __init__(self, col_index, col_name, unique_max):<br>        # Keep the index &amp; name<br>        self.index = col_index<br>        self.name = col_name<br>        # Limit set size to this maximum<br>        self.unique_max = unique_max<br>        # Datatype is inferred for strings<br>        self.datatype = datatype_unknown<br>        # Number of None, empty string or all-whitespace entries<br>        self.empty = 0 <br>        # Number of non-empty entries<br>        self.nonempty = 0<br>        # constants used as sentinels<br>        self.minsentinel = 999999999<br>        self.maxsentinel = -1<br>        # min and max lengths for strings<br>        self.minlen = self.minsentinel<br>        self.maxlen = self.maxsentinel<br>        # min and max values for numbers<br>        self.minval = self.minsentinel<br>        self.maxval = self.maxsentinel        <br>        # min and max values for dates<br>        self.mindate = None<br>        self.maxdate = None        <br>        # Unique value frequencies (size is limited)<br>        self.freqs = {}<br>        # set when freqs grows too long<br>        self.freqsfull = False<br>    <br>    def analyze_value(self, value):<br>        &#39;&#39;&#39;<br>        Analyzes a new value (i.e., new row) for the column.<br>        <br>        This is the critical method for performance tuning.<br>        &#39;&#39;&#39;<br>        # Track unique values/frequencies, limited by unique_max.<br>        if not self.freqsfull:<br>            if len(self.freqs) &lt; self.unique_max: <br>                # use get method&#39;s default value feature<br>                self.freqs[value] = self.freqs.get(value, 0) + 1<br>            else:<br>                # set flag in hope that boolean test is very fast<br>                self.freqsfull = True<br>            <br>        # Test for type<br>        if value is None:<br>            # This is not really expected, but don&#39;t blow up.<br>            self.empty += 1<br>        # this is a python 2.x solution; doesn&#39;t work in 3<br>        elif isinstance(value, basestring):<br>            # It has some kind of string.            <br>            if value == &quot;&quot; or value.isspace():<br>                self.empty += 1<br>                # Don&#39;t infer type based on a zero-length string.<br>                # TODO: possibly turn off digitstring on non-zero whitespace?<br>            else: <br>                self.nonempty += 1<br>                # infer type of data within the string<br>                if value.isdigit():<br>                    # this value is only numbers<br>                    if self.datatype == datatype_digitstring:<br>                        # this is the most common case, no need to look further<br>                        pass<br>                    elif self.datatype == datatype_unknown:<br>                        # first sighting<br>                        self.datatype = datatype_digitstring<br>                    elif self.datatype != datatype_charstring and self.datatype != datatype_digitstring:<br>                        # previously had non-string value, so mark as mixed<br>                        self.datatype = datatype_mixed<br>                else:<br>                    # not digits<br>                    if self.datatype == datatype_charstring:<br>                        # this is the most common case, no need to look further<br>                        pass<br>                    elif self.datatype == datatype_unknown or self.datatype == datatype_digitstring:<br>                        # first sighting, or first presence of chars<br>                        self.datatype = datatype_charstring<br>                    elif self.datatype != datatype_charstring:<br>                        # previously had non-string type<br>                        self.datatype = datatype_mixed<br>                # done with type<br>            # track min/max length of the string<br>            # calculate length once, not 2+ times<br>            strlen = len(value)<br>            if strlen &lt; self.minlen: self.minlen = strlen<br>            if strlen &gt; self.maxlen: self.maxlen = strlen<br>        <br>        elif isinstance(value, int) or isinstance(value, long) or isinstance(value, float):<br>            # It&#39;s a proper number.<br>            self.nonempty += 1<br>            # Note type<br>            if self.datatype == datatype_unknown: self.datatype = datatype_number<br>            elif self.datatype != datatype_number: self.datatype = datatype_mixed<br>            # Store min/max numeric values<br>            if value &lt; self.minval: self.minval = value<br>            if value &gt; self.maxval: self.maxval = value<br>            <br>        elif isinstance(value, datetime.datetime):<br>            # It&#39;s a date-time value; first seen from XLSX via openpyxl<br>            self.nonempty += 1<br>            # Note type<br>            if self.datatype == datatype_unknown: self.datatype = datatype_date<br>            elif self.datatype != datatype_date: self.datatype = datatype_mixed<br>            # Store min/max date values<br>            if self.mindate is None or value &lt; self.mindate: self.mindate = value<br>            if self.maxdate is None or value &gt; self.maxdate: self.maxdate = value<br>            <br>        else:<br>            # Tabular data should not have non-scalar values like list, etc.<br>            raise Exception(&quot;Cannot profile type &quot; + str(type(value)))<br>            <br>            # not a string<br>        <br>    def print_report(self):<br>        &#39;&#39;&#39;<br>        Prints field report to stdout, one result per line.<br>        &#39;&#39;&#39;<br>        print(&quot;Column &#39;%s&#39; (index %d)&quot; % (self.name, self.index))<br>        print(&quot;\tData type      = %s&quot; % get_datatype_name(self.datatype))<br>        print(&quot;\tEmpty count    = %d&quot; % self.empty)<br>        print(&quot;\tNonempty count = %d&quot; % self.nonempty)<br>        print(&quot;\tDensity        = %f&quot; % self.get_density())<br>        if self.datatype == datatype_charstring or self.datatype == datatype_digitstring:<br>            print(&quot;\tMax length str = %s&quot; % self.maxlen)<br>            print(&quot;\tMin length str = %s&quot; % self.minlen)<br>        if self.datatype == datatype_number:<br>            print(&quot;\tMax number     = %s&quot; % self.maxval)<br>            print(&quot;\tMin number     = %s&quot; % self.minval)<br>        if self.datatype == datatype_date:<br>            print(&quot;\tMax date       = %s&quot; % self.maxdate)<br>            print(&quot;\tMin date       = %s&quot; % self.mindate)<br>        # Don&#39;t just echo the max value count when it&#39;s exceeded<br>        if len(self.freqs) &lt; self.unique_max:<br>            print(&quot;\tUnique count   = %d&quot; % len(self.freqs))<br>            # emit dictionary contents sorted by key<br>            print(&quot;\tUnique values  = %s&quot; % &quot;{&quot; + &quot;, &quot;.join(&quot;%r: %r&quot; % (key, self.freqs[key]) for key in sorted(self.freqs)) + &quot;}&quot;)<br>        else:<br>            print(&quot;\tUnique count   &gt; %d&quot; % self.unique_max);<br>    <br>    def get_density(self):<br>        return (self.nonempty / float(self.empty + self.nonempty))<br>    <br>    def print_report_head(self, prefix):<br>        &#39;&#39;&#39;<br>        Prints the column heads for a tabular report to stdout.<br>        Use in conjunction with print_report_row.<br>        Optionally adds a prefix, which supports sheet name and index.<br>        &#39;&#39;&#39;            <br>        print(prefix + &quot;Column name,Column index,Data type,Empty count,Nonempty count,Density,&quot;<br>              + &quot;Max length str,Min length str,Max number,Min number,Max date,Min date,&quot;<br>              + &quot;Unique count,Unique values&quot;)  <br>        <br>    def print_report_row(self, prefix):<br>        &#39;&#39;&#39;<br>        Prints field report to stdout, one result per column.<br>        Optionally adds a prefix, which supports sheet name and index.<br>        &#39;&#39;&#39;<br>        # Avoid a hopelessly wide line.<br>        if len(self.freqs) &lt; self.unique_max:<br>            myuniques = str(len(self.freqs))<br>            # emit dictionary contents sorted by key<br>            myfreqs = &quot;{&quot; + &quot;, &quot;.join(&quot;%r: %r&quot; % (key, self.freqs[key]) for key in sorted(self.freqs)) + &quot;}&quot;<br>        else:<br>            myuniques = &quot;&gt; &quot; + str(self.unique_max)<br>            myfreqs = &quot;Unknown&quot;<br>        print(prefix<br>              + &quot;%s,&quot; % self.name<br>              + &quot;%d,&quot; % self.index<br>              + &quot;%s,&quot; % get_datatype_name(self.datatype) <br>              + &quot;%d,&quot; % self.empty<br>              + &quot;%d,&quot; % self.nonempty<br>              + &quot;%f,&quot; % self.get_density()<br>              + &quot;%s,&quot; % (self.maxlen if self.maxlen != self.maxsentinel else None) # emit as string to allow None<br>              + &quot;%s,&quot; % (self.minlen if self.minlen != self.minsentinel else None)<br>              + &quot;%s,&quot; % (self.maxval if self.maxval != self.maxsentinel else None)<br>              + &quot;%s,&quot; % (self.minval if self.minval != self.minsentinel else None)<br>              + &quot;%s,&quot; % self.maxdate<br>              + &quot;%s,&quot; % self.mindate<br>              + &quot;%s,&quot; % myuniques<br>              + &#39;&quot;%s&quot;&#39; % myfreqs     # surround with quotes<br>            )</pre><pre># Basic tests<br># TODO: How to generate a date-time value?<br>if __name__ == &quot;__main__&quot;:<br>    cols = [ &quot;Empties&quot;, &quot;Numbers&quot;, &quot;Strings&quot;, &quot;Digitstring&quot; ]<br>    ts = TableStat(unique_max_count = 5, column_list = cols)<br>    ts.analyze_row([None , None, None   , None  ])<br>    ts.analyze_row([&quot;   &quot;, 1   , &quot;hi&quot;           ])<br>    ts.analyze_row([&quot;\t&quot; , 2   , &quot;world&quot;, &quot;456&quot;, &quot;bonus&quot; ])<br>    ts.analyze_row([None , 3.0 , &quot;bar&quot;  , &quot;789&quot; ])<br>    ts.analyze_row([None , 4.0 , &quot;bar&quot;  , &quot;012&quot; ])<br>    print(&quot;Generating tall report:&quot;)<br>    ts.print_report()<br>    print(&quot;Generating wide report:&quot;)<br>    ts.print_report_thead(&quot;&quot;)<br>    ts.print_report_tbody(&quot;&quot;)<br>    # This tests constructor input validation<br>    # bogus = TableStat(&quot;hi&quot;)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e94239e3dae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Refreshing the A/T Fluid in a Honda CR-V]]></title>
            <link>https://chrisinmtown.medium.com/refreshing-the-a-t-fluid-in-a-honda-cr-v-dc529b109637?source=rss-27e344e7e090------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc529b109637</guid>
            <category><![CDATA[honda-crv]]></category>
            <category><![CDATA[auto-maintenance]]></category>
            <category><![CDATA[do-it-yourself]]></category>
            <category><![CDATA[transmission-fluid]]></category>
            <dc:creator><![CDATA[Christopher Lott]]></dc:creator>
            <pubDate>Wed, 20 May 2020 14:56:43 GMT</pubDate>
            <atom:updated>2020-05-20T14:56:43.718Z</atom:updated>
            <content:encoded><![CDATA[<h4>23 July 2012</h4><p>This blog post offers some pictures and details of my experience with draining and refilling the automatic transmission fluid on a 2009 Honda 4WD CR-V as part of a 60,000 mile service. I hope it helps someone out there!</p><p>I started down this road when I got a kick in the backside from the car’s maintenance minder (display indicator about what service to do next), which showed codes “1” and “3” next to the “A” at the 60K oil change. Cryptic, right? The book says A is oil change, 1 is air filter and 3 is A/T fluid. The air filter was easy. But I had not done an A/T fluid service before.</p><p>Google lead me to the <a href="http://www.crvownersclub.com/">CRVOwnersClub.com</a>. In the (very helpful!) “Maintenance and Service” forum I read the posts that explain an A/T can’t easily be drained completely without disassembling it, it retains fluid in the torque converter and many other places. So the service is more properly called a fluid refresh rather than a fluid change.</p><p>The people in the forum categorically stated to use Honda fluid, and also explained to drain from the bottom, replace the crush washer on the drain bolt, and refill thru the dipstick tube with a long-neck funnel. There was some disagreement about the filter, with some people saying to change it, and others saying to ignore it, hmm. And the forums had much discussion of the official flush-and-fill procedure, which seems to entail draining, refilling and driving *4* times in rapid succession to get the percentage of new oil up somewhere near 80%. Seriously? I admit I tend towards over maintenance, but that seemed excessive.</p><p>Just for kicks and giggles I asked my local dealer about their price for the A/T service at 60K miles, and the service dude claimed $90 plus parts. I asked specifically about the 4X flush method from the CRV forums, and the service dude asked if the A/T is shifting OK. Yes I said, so he asked, why would I do the 4X flush and fill? From what I heard from him, I gather the Honda service department’s $90 price for a regular A/T service at 60K is just to drain and refill ONCE. And I later got confirmation of this from people in the CR-V forums. So a single drain-and-refill was looking reasonable.</p><p>The first step was laying in supplies. At my local friendly NAPA I found a long-necked plastic funnel for $2.50, made by Blitz in the U.S. of A.!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*LBOvXWIdci-nVwL-.jpg" /></figure><p>Just in case I decided to go for the 4X procedure I bought a case of A/T fluid at my local Honda dealer. Honda charged me $6.50/quart plus tax, which was less than I expected to pay based on comments found on the CR-V owners forums. Honda sold me ATF DW-1 fluid (not the previous generation Z1 fluid), the Honda parts guy said no more ATF Z1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*vvuX2Qi8QWgX3v_N.jpg" /></figure><p>After driving the car around the block a few times it was plenty warm. I found the drain plug quickly enough, roughly in the center and just inches behind the front of the car. It’s accessible without putting the car on ramps. Gotta give the Honda engineers credit for making the access very easy, not burying this one behind something awful! Here’s the front of the car just to show how to find the plug.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*j3TFMna4EvoTLTjE.jpg" /></figure><p>In this next picture I’m a bit closer, the transmission housing is lit up by my trouble light, and you can see the bottom edge of the plug already.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*jVkzQiJKsDhK_F-1.jpg" /></figure><p>I’ve moved closer still and you can see the A/T drain plug. The bolt is round on the outside and has a 3/8&quot; square hole on the inside, conveniently the exact right size for a 3/8&quot; socket wrench :).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*d6HXYSIAh0zpUmRw.jpg" /></figure><p>I put a long-handled 3/8 inch drive socket wrench into the bolt and started tugging. Gently at first, then a lot harder. The transmission moved a bit as I pulled on it. I can only estimate without a torque wrench set for loosening, but I think I put at least 75 ft-lb of pressure on it. I guess all those hot-cold cycles make the bolt stick. Then when it finally turned it went suddenly, and I whacked the wrench into a metal member. Luckily no fingers were in the way for once! The bolt and washer came out easily and the fluid poured out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*zK6ZDBQZnFocvlXs.jpg" /></figure><p>Here’s the drain plug, still with the old crush washer and some goopy stuff on it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*VbWiwjCKlkABmBEg.jpg" /></figure><p>Here’s the drain plug all cleaned off, lying next to the new aluminum crush washer that Honda sold me for $3.12, ouch. After the fluid had slowed to a trickle I put the plug back in. Used the torque wrench set to 35 ft-lb which was the number I got from the CRV owner’s club forums. Altho Honda is delightfully clear about publishing the required torque for the oil-pan drain plug (29 ft-lb), my owner’s manual is silent about A/T fluid service, it basically says “take the car in for service.” So the recommendation of 35 ft-lb seemed reasonable considering the crush washer is made of aluminum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*HN8wmA9YpToXmeS2.jpg" /></figure><p>Time to refill what I took out. Here I’ve aimed the trouble light down into the engine compartment to show the A/T fluid dipstick, the pull ring is yellow, located low and to the left of the battery.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*m40AS5lExMCEcmBG.jpg" /></figure><p>In this picture I’ve pulled the dipstick and inserted the long-neck funnel. Turns out that it was just exactly long enough, the space is narrow and the top of the funnel was wedged just as the bottom part went into the fill tube.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*ATYBd2YP0Knxvl61.jpg" /></figure><p>Leaving the quart container upside down was the easy way to fill. At first I thought I might have to fill very slowly, but the fluid never backed up or overflowed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*RZeXa52jPeOW40bC.jpg" /></figure><p>This shot shows the color of the old stuff. It didn’t smell burned to me but it was certainly a dark color.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*K3dd6aKIzezvmYKJ.jpg" /></figure><p>Here’s the new stuff for easy comparison. Looks like cough syrup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*VmFF3MEY-rE6ShiW.jpg" /></figure><p>To figure out how much to put in, I refilled each empty bottle with dirty fluid, and added the next only when it was clear it was needed. That showed me that only 3 quarts came out. This was a notable variance from the advice I found in the CR-V forums, where people claimed that 3.7 quarts came out. Hmm, low on fluid?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*iPBGTcyFax5VSvOd.jpg" /></figure><p>The last picture shows the business end of the dipstick. The word HOT is printed between the two holes, can’t quite see it here. I guess the fluid level should be right between the two holes when the car is hot. After replacing the 3 quarts that I drained out, the fluid was just below the bottom hole on the dipstick. I had to add another half a quart before the fluid came to the middle of the word HOT. Guess I should have checked the level BEFORE I started draining, but totally forgot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*U4OnwQD6he0VabS5.jpg" /></figure><p>In the end this bit of maintenance was not nearly as bad as I thought it would be when the code first popped up on the MM, in fact it was about as easy as a regular oil change. If this post helps you please drop me a line.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc529b109637" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Validating Files for Unicode/UTF-8 Character Set in Java]]></title>
            <link>https://chrisinmtown.medium.com/validating-files-for-unicode-utf-8-character-set-in-java-fa305b7e7617?source=rss-27e344e7e090------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa305b7e7617</guid>
            <category><![CDATA[character-set]]></category>
            <category><![CDATA[unicode]]></category>
            <category><![CDATA[utf-8]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Christopher Lott]]></dc:creator>
            <pubDate>Wed, 20 May 2020 14:41:51 GMT</pubDate>
            <atom:updated>2020-05-20T14:41:51.718Z</atom:updated>
            <content:encoded><![CDATA[<h3>Validating Files for Unicode/UTF-8 Character Sets with Java</h3><blockquote>18 July 2011</blockquote><p>I was using <a href="http://tika.apache.org/">Apache Tika</a> to extract text from files containing all sorts of content, and write that text to files using UTF-8 encoding. After botching it a few times I finally forced myself to learn a bit about encoding systems and Java’s representation of Unicode code points. I also learned that using the word “character” all too often leads to confusion!</p><p>My colleague D. B. tells me that Java’s support for international character sets was written about the time the Unicode committee finalized a standard that allowed a character to be represented in 16 bits. Then after Sun’s people cast that 16-bit assumption into concrete deep within java.lang.Character and other classes, the Unicode committee had a change of heart.. and now it takes 32 bits to represent a character properly. This information is all well documented at the Sun (oops I mean Oracle) Java API web site but it took several reads before it started sink in for me.</p><p>What I learned, and what really bothers me still, is that a Java String may contain parts (avoiding the “C” word here) that cannot be represented using a single Java Character type! In other words, using the String.charAt(int) method gives back something that must be handled with extreme care. So iterating over the little parts that make up a String is not as simple as I once thought. And I have not yet accustomed myself to using the String.codePointAt(int) method.</p><p>The task I had to accomplish was to check whether files contain valid UTF-8 byte sequences. Some tools were giving garbage results and I needed to figure out why. The basic java.io.InputStreamReader will happily translate byte streams to character streams, but it does not report encoding/decoding errors (also see <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4646959">http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4646959</a>). I found that the java.nio.charset package offers some help that does not require loops to iterate over the parts in a String so I went with that.</p><p>Below you will find the source code for an example Java class that checks whether file content can be decoded using the UTF-8 character set. It also supports creation of a file with a character that is valid in the ISO-8859–1 encoding system but not in the UTF-8 system so you can test the class and see the exception that is thrown.</p><pre>import java.io.File;<br>import java.io.FileInputStream;<br>import java.io.FileOutputStream;<br>import java.io.IOException;<br>import java.io.InputStreamReader;<br>import java.nio.charset.CharacterCodingException;<br>import java.nio.charset.Charset;<br>import java.nio.charset.CharsetDecoder;<br>import java.nio.charset.CodingErrorAction;<br><br>/**<br> * Reads bytes from file using a decoder that throws an exception if the bytes<br> * cannot be decoded as UTF-8. Can be used to validate a single file or a<br> * directory of files with full recursion. Includes a feature to create a file<br> * with a non-UTF-8 byte sequence for testing.<br> * <br> * @author Chris Lott<br> * <br> */<br>public class ValidateEncodingApp {<br><br>	private final String charsetName;<br>	private final CharsetDecoder decoder;<br>	private int filesPassed = 0, filesFailed = 0;<br><br>	/**<br>	 * Obtains a decoder and configures it to blow up on problems.<br>	 * <br>	 * @param charsetName<br>	 *            Name of character set to use; e.g., UTF-8<br>	 */<br>	public ValidateEncodingApp(String charsetName) {<br>		this.charsetName = charsetName;<br>		Charset charset = Charset.forName(charsetName);<br>		decoder = charset.newDecoder();<br>		decoder.onMalformedInput(CodingErrorAction.REPORT);<br>		decoder.onUnmappableCharacter(CodingErrorAction.REPORT);<br>	}<br><br>	/**<br>	 * @return The character set name supplied to the constructor<br>	 */<br>	public String getCharsetName() {<br>		return charsetName;<br>	}<br><br>	/**<br>	 * @return The number of files that could not be validated for whatever<br>	 *         reason.<br>	 */<br>	public int getFilesFailed() {<br>		return filesFailed;<br>	}<br><br>	/**<br>	 * @return The number of files successfully validated.<br>	 */<br>	public int getFilesPassed() {<br>		return filesPassed;<br>	}<br><br>	/**<br>	 * Reads and decodes bytes from the specified file, which will find byte<br>	 * sequences that cannot be decoded using the current system. Traps all<br>	 * exceptions and reports to System.err.<br>	 * <br>	 * @param file<br>	 * @return True on success, false on IOException or decoding error<br>	 */<br>	private boolean validateFile(File file) {<br>		boolean result = true;<br>		long total = 0;<br>		InputStreamReader isr = null;<br>		char[] buf = new char[65536];<br>		int chars;<br>		try {<br>			isr = new InputStreamReader(new FileInputStream(file), decoder);<br>			while ((chars = isr.read(buf)) &gt;= 0)<br>				total += chars;<br>			++filesPassed;<br>		} catch (CharacterCodingException ex) {<br>			++filesFailed;<br>			System.err.println(&quot;Decoding failed near byte &quot; + total<br>					+ &quot; in file &quot; + file.getPath() + &quot;: &quot; + ex.toString());<br>			result = false;<br>		} catch (IOException ex) {<br>			++filesFailed;<br>			System.err.println(&quot;Failed to read file &quot; + file.getPath() + &quot;: &quot;<br>					+ ex.toString());<br>			result = false;<br>		} finally {<br>			if (isr != null)<br>				try {<br>					isr.close();<br>				} catch (IOException ex) {<br>					System.err.println(&quot;Failed to close file: &quot; + ex.toString());<br>				}<br>		}<br>		return result;<br>	}<br><br>	/**<br>	 * Validates all files in the specified directory. Optionally recurses into<br>	 * subdirectories. Prints message to stdout when it starts and again when it<br>	 * finishes traversing a directory.<br>	 * <br>	 * @param dir<br>	 *            Directory to traverse.<br>	 * @param isRecurse<br>	 *            If true, will call itself to process subdirectories.<br>	 * @throws Exception<br>	 */<br>	private void validateDirectory(File dir, boolean isRecurse) throws Exception {<br>		if (!dir.exists() || !dir.isDirectory())<br>			throw new IllegalArgumentException(&quot;Not found or not a directory: &quot;<br>					+ dir.getPath());<br>		System.out.println(&quot;Entering directory &quot; + dir.getPath());<br>		File[] contents = dir.listFiles();<br>		for (File f : contents) {<br>			if (f.isFile())<br>				validateFile(f);<br>			else if (f.isDirectory() &amp;&amp; isRecurse)<br>				validateDirectory(f, isRecurse);<br>		}<br>		System.out.println(&quot;Leaving directory &quot; + dir.getPath());<br>	}<br><br>	/**<br>	 * Prints message(s) and exits<br>	 * <br>	 * @param msg<br>	 */<br>	private static void usage(String msg) {<br>		if (msg != null)<br>			System.err.println(msg);<br>		System.err.println(&quot;Usage: ValidateEncodingApp -validate (file|dir)&quot;);<br>		System.err.println(&quot;	   ValidateEncodingApp -create filename&quot;);<br>		System.exit(0);<br>	}<br><br>	public static void main(String[] args) {<br><br>		// TODO: extend to accept encoding system name<br>		// and recurse option as arguments.<br>		String charsetName = &quot;UTF-8&quot;;<br>		boolean recurse = true;<br><br>		if (args.length != 2)<br>			usage(&quot;Unexpected number of arguments&quot;);<br><br>		String cmd = args[0];<br>		File file = new File(args[1]);<br><br>		if (&quot;-create&quot;.equals(cmd)) {<br>			if (file.exists())<br>				usage(&quot;Will not overwrite existing file: &quot; + file.getPath());<br><br>			System.out.println(&quot;Creating file with ISO-8859-1 content: &quot;<br>					+ file.getPath());<br>			try {<br>				// The word &quot;dolt&quot; has an o with a diagonal slash thru it.<br>				// The slash-o is valid in ISO-8859-1 but not in UTF-8.<br>				final byte[] invalid = &quot;d\u00f8lt&quot;.getBytes(&quot;iso-8859-1&quot;);<br>				FileOutputStream fis = new FileOutputStream(file);<br>				fis.write(invalid);<br>				fis.close();<br>			} catch (IOException ex) {<br>				System.err.println(&quot;Failed to write file: &quot; + ex.toString());<br>			}<br>		} else if (&quot;-validate&quot;.equals(cmd)) {<br>			if (!file.exists())<br>				usage(&quot;Not found: &quot; + file.getPath());<br><br>			try {<br>				ValidateEncodingApp validator = new ValidateEncodingApp(<br>						charsetName);<br>				if (file.isFile()) {<br>					System.out.println(&quot;Validating decoding of bytes as &quot;<br>							+ charsetName + &quot; for file &quot; + file.getPath());<br>					validator.validateFile(file);<br>				} else {<br>					System.out.println(&quot;Validating decoding of bytes as &quot;<br>							+ charsetName + &quot; for files in/below directory &quot;<br>							+ file.getPath());<br>					validator.validateDirectory(file, recurse);<br>				}<br>				System.out.println(&quot;Validation success count is &quot;<br>						+ validator.getFilesPassed());<br>				System.out.println(&quot;Validation failure count is &quot;<br>						+ validator.getFilesFailed());<br><br>			} catch (Exception ex) {<br>				ex.printStackTrace();<br>			}<br>		} else {<br>			usage(&quot;Unexpected command: &quot; + cmd);<br>		}<br><br>	}<br><br>}</pre><p>If this helps you please drop me a line.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa305b7e7617" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Server and Client Certificates in HTTPS for Apache Client in Java]]></title>
            <link>https://chrisinmtown.medium.com/server-and-client-certificates-in-https-for-apache-client-in-java-aeceae62a023?source=rss-27e344e7e090------2</link>
            <guid isPermaLink="false">https://medium.com/p/aeceae62a023</guid>
            <category><![CDATA[ssl]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Christopher Lott]]></dc:creator>
            <pubDate>Wed, 20 May 2020 14:41:36 GMT</pubDate>
            <atom:updated>2020-05-20T14:41:36.685Z</atom:updated>
            <content:encoded><![CDATA[<h4>7 Jan 2012</h4><p>I was working on a client to access a RESTful (representation state transfer AKA http) web service. Maybe that’s just the buzzword of choice these days, but the system seems to conform to Wikipedia’s list of <a href="http://en.wikipedia.org/wiki/Representational_state_transfer">REST architecture constraints</a>. I’m reusing version 4.1.2 libraries provided by the <a href="http://hc.apache.org/">Apache HttpComponents</a> project. All straightforward so far, right?</p><p>Two complicating factors made this a bit interesting. First, the server requires access via HTTPS, and for that it uses a self-signed server certificate. This requirement can be met in a couple of ways: either the HttpClient can be told to trust all servers no matter what, or the server certificate can be cached locally for comparison. Apache offers <a href="http://hc.apache.org/httpcomponents-client-ga/httpclient/examples/org/apache/http/examples/client/ClientCustomSSL.java">example code</a> to demonstrate caching a self-signed certificate so that was no significant problem.</p><p>The second requirement, presenting a user certificate to the server, was a bit tricker. I found example code at the Apache site, but it was for version 3 and no longer works in v4. Stackoverflow offered <a href="http://stackoverflow.com/questions/3375121/mutual-authentication-with-x509-certificates-using-httpclient-4-0-1">pieces of code</a> but not the full solution. A<a href="http://drumcoder.co.uk/blog/2011/oct/18/httpclient-client-side-certificates/"> blog post by Tim Sawyer</a> was extremely helpful in pointing out that this scenario requires both a *keystore* and a *truststore*, but I still struggled to get the keystore and truststore files set up appropriately. I find the Java keytool fairly inscrutable but that’s prolly because I’m not a crypto person. And just to make it fun, the javadoc for the critical constructor in the <a href="http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/conn/ssl/SSLSocketFactory.html">SSLSocketFactory class</a> is utterly free of any description, and the parameter names are barely helpful.</p><p>I had to save the server’s certificate in a Java keystore file. Because this file holds the server info, the proper term is a *truststore*, which is the term used in the Apache HttpClient javadoc. The keystore must show that it has a “trustedCertEntry.” This is the incantation I used to build a server truststore file in Java Keystore (“JKS”) format using the keytool command that comes with Java; after keytool shows the details you have to tell it to trust the certificate:</p><pre>keytool -importcert -alias &quot;server&quot; -file server.crt -keystore server.keystore -deststorepass password1</pre><p>I had to save the client’s private key in a Java keystore file, and it must appear in that keystore as a “PrivateKeyEntry” (not a certificate entry). The client key was available in a PKCS12 (“.p12”) format and that was critical. I learned from googling that keytool can read a PKCS12 file and import its contents appropriately. This is the incantation I used to build a client keystore file in JKS format using the keytool command; again you have to approve import of the data:</p><pre>keytool -v -importkeystore -srckeystore user.p12 -srcstoretype PKCS12 -srcstorepass changeit -destkeystore user.keystore -deststoretype JKS -deststorepass password2</pre><p>Along the way I hit various stumbling blocks of course.</p><ol><li>Initially I supplied the wrong server certificate, and I hit this exception:</li></ol><pre> javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated`</pre><p>At least once I gave the wrong password for a keystore and this exception is what happens:</p><pre>java.io.IOException: Keystore was tampered with, or password was incorrect</pre><p>While I knew that the private key is protected by a password, I didn’t quite grasp that this protection is preserved when it’s imported into the destination keystore, which of course is protected by a different password. So I supplied the correct password to load the keystore, but not the right password to decrypt the private key within the keystore. That yielded the following exception.</p><pre>java.security.UnrecoverableKeyException: Cannot recover key</pre><p>When I botched the user private key certificate by supplying a keystore file with the wrong content, I hit this exception:</p><pre>org.apache.http.impl.client.DefaultRequestDirector handleResponse WARNING: Authentication error: Unable to respond to any of these challenges: {}</pre><p>I used Java version 1.6.0_20, and apparently this VM has an SSL implementation that blocks SSL renegotation, which presented itself as this exception:</p><pre>javax.net.ssl.SSLException: HelloRequest followed by an unexpected handshake message</pre><p>I frankly don’t understand all the ramifications of this, but again googling yielded the answer. Supposedly other versions don’t have this problem but I have not yet tested them. Launching the program with this additional VM argument turns this off. But note that his only appears *if some other problem is also present*; it’s not necessary when all the keystores and passwords are correct.</p><pre>-Dsun.security.ssl.allowUnsafeRenegotiation=true</pre><p>Putting all the pieces together yields the following demonstration code. It traps all the exceptions that I hit and tries to give helpful messages :). Forgive me for assuming UTF-8 encoding for the server response! Please drop me a line if it helps you.</p><pre>import java.io.File;<br>import java.io.FileInputStream;<br>import java.net.URI;<br>import java.security.KeyStore;<br>import java.security.UnrecoverableKeyException;<br><br>import javax.net.ssl.SSLException;<br>import javax.net.ssl.SSLPeerUnverifiedException;<br><br>import org.apache.http.HttpEntity;<br>import org.apache.http.HttpResponse;<br>import org.apache.http.client.methods.HttpGet;<br>import org.apache.http.conn.scheme.Scheme;<br>import org.apache.http.conn.ssl.SSLSocketFactory;<br>import org.apache.http.impl.client.DefaultHttpClient;<br>import org.apache.http.util.EntityUtils;<br><br>/**<br> * Demonstrates use of the Apache HTTP Client version 4 to access a web site via<br> * HTTPS, with special conditions:<br> * &lt;OL&gt;<br> * &lt;LI&gt;The server presents a self-signed certificate (not signed by a trusted<br> * certificate authority). The certificate is available in a .crt file (x509<br> * format?). To allow this, the caller must supply a truststore file containing<br> * the expected server certificate.<br> * &lt;LI&gt;The user must supply a private key to the server for authentication. The<br> * key is available in PCKS12 format. To enable this, the caller must supply a<br> * keystore file containing the expected user certificate.<br> * &lt;/OL&gt;<br> * Built and tested using Apache HTTP Components version 4.1.2.<br> * <br> * Used Java&#39;s keytool to create the server truststore from a .crt file:<br> * <br> * &lt;PRE&gt;<br> *   keytool -importcert -alias &quot;server&quot; -file server.crt -keystore server.keystore -deststorepass password1<br> * &lt;/PRE&gt;<br> * <br> * Used Java&#39;s keytool to creaet the client keystore from a .p12 file:<br> * <br> * &lt;PRE&gt;<br> *    keytool -v -importkeystore -srckeystore user.p12 -srcstoretype PKCS12 -srcstorepass changeit -destkeystore user.keystore -deststoretype JKS -deststorepass password2<br> * &lt;/PRE&gt;<br> * <br> * Note that JDK versions 1.6.0_19 thru JDK 1.6.0_23 prohibit SSL renegotiation.<br> * Reopen this possible security hole by supplying this JVM argument:<br> * -Dsun.security.ssl.allowUnsafeRenegotiation=true<br> * <br> * This is a revised version of ClientCustomSSL, an example program contributed<br> * to the Apache Http Client project, and available here:<br><br> * http://hc.apache.org/httpcomponents-client-ga/httpclient/examples/org/apache/<br> * http/examples/client/ClientCustomSSL.java<br> *<br> * @author Chris Lott<br> */<br>public class ServerClientCustomSSL {<br><br>    public final static void main(String[] args) throws Exception {<br>	if (args.length != 6) {<br>	    System.err<br>		.println(&quot;Usage: server-truststore-file-name server-truststore-password client-keystore-file-name client-keystore-password client-key-password target-URI&quot;);<br>	    return;<br>	}<br><br>	File truststoreFile = new File(args[0]);<br>	if (!truststoreFile.exists() || !truststoreFile.isFile()) {<br>	    System.err.println(&quot;Not found or not a file: &quot;<br>			       + truststoreFile.getPath());<br>	    return;<br>	}<br>	System.out.println(&quot;Truststore file with server cert is &quot;<br>			   + truststoreFile.getPath());<br><br>	String truststorePassword = args[1];<br>	if (truststorePassword.length() == 0) {<br>	    System.err.println(&quot;Empty truststore password, giving up&quot;);<br>	    return;<br>	}<br>	System.out.println(&quot;Truststore password is &quot; + truststorePassword);<br><br>	File keystoreFile = new File(args[2]);<br>	if (!keystoreFile.exists() || !keystoreFile.isFile()) {<br>	    System.err.println(&quot;Not found or not a file: &quot;<br>			       + keystoreFile.getPath());<br>	    return;<br>	}<br>	System.out.println(&quot;Keystore file with client private key is &quot;<br>			   + keystoreFile.getPath());<br><br>	String keystorePassword = args[3];<br>	if (keystorePassword.length() == 0) {<br>	    System.err.println(&quot;Empty keystore password, giving up&quot;);<br>	    return;<br>	}<br>	System.out.println(&quot;Keystore password is &quot; + truststorePassword);<br><br>	String privateKeyPassword = args[4];<br>	if (privateKeyPassword.length() == 0) {<br>	    System.err.println(&quot;Empty private key password, giving up&quot;);<br>	    return;<br>	}<br>	System.out.println(&quot;Private key password is &quot; + privateKeyPassword);<br><br>	URI targetURI = new URI(args[5]);<br>	String protocol = targetURI.getScheme();<br>	if (!&quot;https&quot;.equals(protocol)) {<br>	    System.err<br>		.println(&quot;URI does not begin with expected protocol name&quot;);<br>	    return;<br>	}<br>	System.out.println(&quot;URI to fetch is &quot; + targetURI.toString());<br><br>	DefaultHttpClient httpclient = new DefaultHttpClient();<br>	try {<br>	    // The expected server certificate must be in a *trust* store.<br>	    // keytool must report &quot;trustedCertEntry&quot; when listing the contents.<br>	    KeyStore trustStore = KeyStore.getInstance(KeyStore<br>						       .getDefaultType());<br>	    FileInputStream trustStream = new FileInputStream(truststoreFile);<br>	    try {<br>		System.out.println(&quot;Loading server truststore from file &quot;<br>				   + truststoreFile.getPath());<br>		trustStore.load(trustStream, truststorePassword.toCharArray());<br>		System.out.println(&quot;Truststore certificate count: &quot;<br>				   + trustStore.size());<br>	    } catch (Exception ex) {<br>		System.err.println(&quot;Failed to load truststore: &quot;<br>				   + ex.toString());<br>		return;<br>	    } finally {<br>		try {<br>		    trustStream.close();<br>		} catch (Exception ignore) {<br>		}<br>	    }<br><br>	    // The required user key must be in a *key* store.<br>	    // keytool must report &quot;PrivateKeyEntry&quot; when listing the contents.<br>	    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());<br>	    FileInputStream keyStream = new FileInputStream(keystoreFile);<br>	    try {<br>		System.out.println(&quot;Loading client keystore from file &quot;<br>				   + keystoreFile.getPath());<br>		keyStore.load(keyStream, keystorePassword.toCharArray());<br>		System.out.println(&quot;Keystore certificate count: &quot;<br>				   + keyStore.size());<br>	    } catch (Exception ex) {<br>		System.err.println(&quot;Failed to load keystore: &quot; + ex.toString());<br>		return;<br>	    } finally {<br>		try {<br>		    keyStream.close();<br>		} catch (Exception ignore) {<br>		}<br>	    }<br><br>	    // Create and register a socket factory for all HTTPS connections<br>	    SSLSocketFactory socketFactory = null;<br>	    try {<br>		// http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/index.html<br>		// This constructor has zero words of documentation in the<br>		// version 4.1.2 javadoc; I only figured it out by googling.<br>		socketFactory = new SSLSocketFactory(keyStore,<br>						     privateKeyPassword, trustStore);<br>	    } catch (UnrecoverableKeyException ke) {<br>		System.err<br>		    .println(&quot;Failed to create SSLSocketFactory, possible wrong password on client private key&quot;);<br>		return;<br>	    }<br>	    // This is the default port number only; others are allowed<br>	    Scheme sch = new Scheme(&quot;https&quot;, 443, socketFactory);<br>	    httpclient.getConnectionManager().getSchemeRegistry().register(sch);<br><br>	    HttpGet httpget = new HttpGet(targetURI);<br>	    System.out.println(&quot;Executing request &quot; + httpget.getRequestLine());<br><br>	    HttpResponse response = null;<br>	    try {<br>		response = httpclient.execute(httpget);<br>	    } catch (SSLPeerUnverifiedException ex) {<br>		// Message &quot;peer not authenticated&quot; means the server presented<br>		// a certificate that was not found in the local truststore.<br>		System.err<br>		    .println(&quot;Get failed, possible missing or invalid certificate: &quot;<br>			     + ex.toString());<br>		return;<br>	    } catch (SSLException sx) {<br>		// Renegotiation must be allowed in certain JDK versions via the<br>		// JVM argument -Dsun.security.ssl.allowUnsafeRenegotiation=true<br>		System.err<br>		    .println(&quot;Get failed, possible missing JVM argument: &quot;<br>			     + sx.toString());<br>		return;<br>	    } catch (Exception x) {<br>		// Something I have not seen (yet)<br>		System.err.println(&quot;Get failed unexpectedly: &quot; + x.toString());<br>		return;<br>	    }<br>								  <br>	    HttpEntity entity = response.getEntity();<br>	    System.out.println(&quot;----------------------------------------&quot;);<br>	    System.out.println(&quot;Response status: &quot; + response.getStatusLine());<br>	    if (entity != null) {<br>		System.out.println(&quot;Response content length: &quot;<br>				   + entity.getContentLength());<br>		if (entity.getContentLength() &gt; 0) {<br>		    byte[] first100 = new byte[100];<br>		    int howMany = entity.getContent().read(first100);<br>		    // Hope that the encoding is sane<br>		    String hundred = new String(first100, 0, howMany, &quot;UTF-8&quot;);<br>		    System.out.println(&quot;First &quot; + howMany<br>				       + &quot; characters of the response:&quot;);<br>		    System.out.println(hundred);<br>		}<br>	    }<br>	    // read the rest and close the stream<br>	    EntityUtils.consume(entity);<br><br>	} finally {<br>	    // When HttpClient instance is no longer needed,<br>	    // shut down the connection manager to ensure<br>	    // immediate deallocation of all system resources<br>	    httpclient.getConnectionManager().shutdown();<br>	}<br>    }</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aeceae62a023" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making Fire-Roasted Salsa]]></title>
            <link>https://chrisinmtown.medium.com/making-fire-roasted-salsa-f14c9aab7537?source=rss-27e344e7e090------2</link>
            <guid isPermaLink="false">https://medium.com/p/f14c9aab7537</guid>
            <category><![CDATA[salsa]]></category>
            <category><![CDATA[mexican-food]]></category>
            <category><![CDATA[recipe]]></category>
            <dc:creator><![CDATA[Christopher Lott]]></dc:creator>
            <pubDate>Tue, 19 May 2020 15:08:55 GMT</pubDate>
            <atom:updated>2020-05-19T15:11:38.121Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>7 Oct 2010</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/0*iUCFFgDKR9QJgbtL.jpg" /></figure><p>I have long loved eating Mexican food in general and salsa in particular. In grad school my buddy Bill and I decided to conduct some experiments with salsa. Well it wasn’t a bad excuse to drink beer, right? So we gathered different onions, different peppers, etc. and made salsa. Lots of salsa. Some was so hot we could barely stand it, we called it drano. Some was basically salad — we were making pico de gallo before I knew what that was. After much goofing around we wrote up the recipe for <a href="http://maultech.com/chrislott/misc/salsa-eng.html">Damn Good Salsa</a> and posted it on our respective web pages. (Anyone remember Agent Cooper in Twin Peaks? Damn fine cherry pie? That was the inspiration for the name. But I digress.) I know now that we had barely scratched the surface.</p><p>Occasionally I’d find a really great salsa in a restaurant, and my favorite had bits of charred tomato in it and a hint of a smoky taste. This is my attempt at recreating that flavor. Here’s the list of ingredients and directions for my latest favorite version. After that there’s some pictures and fairly useless commentary from my latest batch.</p><p><strong>Ingredients</strong></p><ul><li>10 ripe plum tomatoes</li><li>1/2 red onion</li><li>1–2 cloves garlic</li><li>2+ jalapeno peppers (ideally chipotles)</li><li>1 lime</li><li>half a bunch of fresh cilantro</li><li>2 T red wine vinegar</li><li>1 t cumin</li><li>1/2 t ground black pepper</li></ul><p><strong>Directions</strong></p><ul><li>Wash tomatoes, slice in half, arrange on baking sheet</li><li>Broil tomatoes about 30 minutes until skins are black</li><li>Pluck skins off tomatoes</li><li>Process tomatoes thru a food processor cheese grater wheel, or dice by hand</li><li>Dice red onion</li><li>Combine tomatoes and onions in a large pot</li><li>Extract juice from lime, add to pot</li><li>Clean garlic, peppers, and cilantro, then put in food processor with the chopping blade</li><li>Add vinegar, cumin, pepper to the processor</li><li>Run processor to mince everything up, add to pot</li><li>Bring to gentle boil</li><li>Let cool, serve with chips!</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/0*VdoAIDg6-tjwQ--B.jpg" /></figure><p>Plum tomatoes were abundant in the farmer’s markets around here a few weeks ago. I bought a big box, easily 25 pounds, for just $20. The picture below shows just a few.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/0*d3JfuLkwVzHd9AwB.jpg" /></figure><p>These plum tomato halves have been under the broiler for about 30 minutes. Below you can see enough for a double batch of the recipe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/0*xjyikDThX2TYSveQ.jpg" /></figure><p>In this picture you can see how they look after I’ve plucked off all the skins. The blackened skins are usually easy to remove, but sometimes are a hassle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/214/0*4UCk2RUGK3SWk-5O.jpg" /></figure><p>This is the cheese-grater wheel on our ancient cuisinart. Hey, it still works. This wheel produces a nice coarse texture. I don’t want to turn the tomatoes into juice with the chopping blade! Yeah, I know I took a photo of the container on backwards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/214/0*2tCYjN7vQ8bVUPdz.jpg" /></figure><p>The tomatoes have been through the mill. This is dead quick and easy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/0*WXVpTANYMG7W6BMB.jpg" /></figure><p>Here’s all the good stuff that makes it salsa. This bunch of cilantro is about half what I usually find in the market, don’t know why it was so small. So I used the whole thing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/0*r-ZezGtSOv_tdByi.jpg" /></figure><p>I’m using a whole onion because I’m making a double batch. You just gotta chop the onions by hand. I’ve never been able to get a satisfactory texture out of the food processor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/0*bom_hPyil7nt_vd3.jpg" /></figure><p>This is the part I like the least. Cilantro leaves turn to disgusting black mush really really quickly and I don’t want any of it in my salsa. Here I’m separating leaves from stems and washing it a few times. The extra onion is hanging around, sneaking into pix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/0*T6rG8eg8gOjm9rUI.jpg" /></figure><p>Cilantro is key to the salsa tho, and that’s why I put up with the hassle. Here’s the cleaned result, ready for the processor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/0*k2LeHKW8vRtZ9XjY.jpg" /></figure><p>I had high hopes for these beautiful ripe jalapenos but they had NO HEAT at all, a disappointment. Unfortunately I was all out of chipotle peppers. A chipotle is a smoked jalapeno, often sold dry but also sold “en Adobo” which means canned in a rich tomato sauce. I highly recommend you try a chipotle in this recipe. The heat increases slightly after the salsa is mixed and cooked, I guess the capsaicin takes a while to escape from the seeds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/0*_6Ivq55DtAaio7LB.jpg" /></figure><p>Lime is the other key ingredient. I resisted making a margarita. But only because I had no tequila in the house. Dangit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/214/0*l00ndu3bfA67QhK0.jpg" /></figure><p>Peppers, cilantro, lime juice and spices in the processor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/214/0*OHg41GyESsJ3VgHn.jpg" /></figure><p>After chopping down into green liquid. Doesn’t look like much but it’s pure flavor!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/0*-wt0ChjO9Axr2ZIs.jpg" /></figure><p>Everything’s in the pot. Red and green — Christmas!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/0*tLmlSi-YaOce1_GW.jpg" /></figure><p>I stop cooking when the some tomato foam appears on the surface, that’s enough.</p><p>What’s missing from this picture? Right, beer! Enjoy. Please send me a pepper, ahem, I mean an email if you like this recipe, thanks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f14c9aab7537" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Baking Jim Lahey’s No-Knead Bread]]></title>
            <link>https://chrisinmtown.medium.com/baking-jim-laheys-no-knead-bread-fffee17f11de?source=rss-27e344e7e090------2</link>
            <guid isPermaLink="false">https://medium.com/p/fffee17f11de</guid>
            <category><![CDATA[baking-tips]]></category>
            <category><![CDATA[no-knead-bread]]></category>
            <category><![CDATA[bread-recipes]]></category>
            <category><![CDATA[baking]]></category>
            <category><![CDATA[bread]]></category>
            <dc:creator><![CDATA[Christopher Lott]]></dc:creator>
            <pubDate>Tue, 19 May 2020 14:56:35 GMT</pubDate>
            <atom:updated>2020-05-19T14:56:35.178Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>3 Oct 2010</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*XxwFt0qksSY1uXq8K3LJzQ.jpeg" /></figure><p>First I’ll bore you with the back story. When we were in gradual school at UMCP and had more time than we do now, my buddies Bill, Scott and I made valiant attempts at baking decent bread at home. This was before good bakeries popped up everywhere, and long before grocery stores received par-baked loaves to finish daily. Occasionally we’d get something almost edible but never good enough to motivate us to make it again soon. Then I spent a few years in Germany where good bread was everywhere, and never baked. When we moved to New Jersey over a decade ago there was some good bread around and even tho I finally had a kitchen to mess up, I still didn’t attempt any bread.</p><p>Then late in 2008 I stumbled across Mark Bittman’s article in the NY Times on baking no-knead bread (links are below). I printed it out and it lay on my desk for a solid year. Maybe it was longer, I don’t know. Finally in some fit of desk cleaning I unearthed the sheet and forced myself to make it.</p><p>Before I go any further, here are links to the recipe, at The New York Times and at the Sullivan Street Bakery.</p><ul><li><a href="http://www.nytimes.com/2006/11/08/dining/081mrex.html">http://www.nytimes.com/2006/11/08/dining/081mrex.html</a></li><li><a href="http://www.sullivanstreetbakery.com/recipes">http://www.sullivanstreetbakery.com/recipes</a></li></ul><p>Making the dough is almost no work. Back in grad school we were too impatient to knead the dough enough, and this recipe solves that problem. To bake this bread you need a medium-size oven-proof container with an oven-proof lid, ideally ceramic. Well, I used a makeshift system of a mixing bowl and an inverted frying pan. (Once I almost melted the bakelite knob on a frying-pan lid, but don’t tell my wife.)</p><p>So my very first loaf emerged from this ridiculous bowl and frying pan contraption .. just amazing. It looked like, well, like a real loaf of bread. It tasted GREAT. The kids and I ate it in, uh, probably about an hour. I made another loaf immediately, baked it the next day. The second loaf, despite my best attempts to mess it up, was great too. Hmm. Suddenly baking bread got a lot more attractive!</p><p>Eventually I experimented a bit. I have found that this recipe works just fine with whole-wheat flour or rye flour, but not more than about 1/3 of the total flour. One more picture, this is a loaf with about 1/3 rye flour and maybe a quarter cup of some goofy flax seed that I found in the pantry. It doesn’t rise as much as an all-white-flour loaf but the taste is a lot more interesting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*ekemQiCoL_B47iMW.jpg" /></figure><p>This has become my standard thing to take to other people’s houses. Their kids usually devour it, even the rye version. I also found a smallish ceramic pot with a ceramic lid that has become my standard bread baker, just got lucky at the local home-goods store that sells remnants etc.</p><p>I’ll wrap this up with a big thank-you to Jim Lahey for sharing the fruits of his research, and also many thanks to Mark Bittman for writing it up!</p><p><strong>Update 18 Feb 2012</strong>: After seeing a friend use a shaker to distribute flour evenly when making gravy, I finally got one for making bread. It works great!! This is probably something totally obvious to real bakers but it took me a long time to stumble upon it. That’s today’s loaf rising in the background, sitting on top of a silicone baking sheet liner that is nicely covered with flour from the shaker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*1Mg4coTgDNTsUUAC.jpg" /></figure><p>Here’s the plain-text recipe, just in case those links above ever stop working. I sure hope they don’t mind me repeating the recipe here.</p><pre>baking the perfect<br>loaf of bread at home</pre><pre>Formula and process created by<br>Jim Lahey, owner of Sullivan St Bakery.</pre><pre>formula</pre><pre>3 cups (430g) flour<br>1 1/2 cups (345g or 12oz) water<br>1/2 teaspoon (1g) yeast<br>1 1/4 teaspoon (8g) salt<br>olive oil (for coating)<br>extra flour, wheat bran, or cornmeal (for dusting)</pre><pre>equipment</pre><pre>Two medium mixing bowls<br>6 to 8 quart pot with lid<br>  (Pyrex glass, Le Creuset cast iron, or ceramic)<br>Wooden Spoon or spatula (optional)<br>Plastic wrap<br>Two or three cotton dish towels (not terrycloth)</pre><pre>process</pre><pre>Mix all of the dry ingredients in a medium bowl. <br>Add water and incorporate by hand or with a wooden <br>spoon or spatula for 30 seconds to 1 minute. Lightly <br>coat the inside of a second medium bowl with olive oil <br>and place the dough in the bowl. Cover the bowl with <br>plastic wrap and let the dough rest 12 hours at room <br>temperature (approx. 65-72 degrees F).</pre><pre>Remove the dough from the bowl and fold once or twice. <br>Let the dough rest 15 minutes in the bowl or on the work <br>surface. next, shape the dough into ball. Generously <br>coat a cotton towel with flour, wheat bran, or cornmeal; <br>place the dough seam side down on the towel and dust with <br>flour. Cover the dough with a cotton towel and let rise <br>1-2 hours at room temperature, until more than doubled in <br>size.</pre><pre>Preheat oven to 450-5000F. Place the pot in the oven at <br>least 30 minutes prior to baking to preheat. Once the dough <br>has more than doubled in volume, remove the pot from the <br>oven and place the dough in the pot seam side up. Cover <br>with the lid and bake 30 minutes Then remove the lid and <br>bake 15-30 minutes uncovered, until the loaf is nicely browned.</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fffee17f11de" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>