<?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 Catherine Holloway on Medium]]></title>
        <description><![CDATA[Stories by Catherine Holloway on Medium]]></description>
        <link>https://medium.com/@femion?source=rss-4a068a25ba38------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*XYyUuJHJcu9FETXN.jpg</url>
            <title>Stories by Catherine Holloway on Medium</title>
            <link>https://medium.com/@femion?source=rss-4a068a25ba38------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 16:34:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@femion/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[Cairo Tilings with minimal math]]></title>
            <link>https://medium.com/@femion/cairo-tilings-with-minimal-math-bee322e716e1?source=rss-4a068a25ba38------2</link>
            <guid isPermaLink="false">https://medium.com/p/bee322e716e1</guid>
            <category><![CDATA[svg]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[geometry]]></category>
            <dc:creator><![CDATA[Catherine Holloway]]></dc:creator>
            <pubDate>Sat, 07 Jul 2018 12:37:38 GMT</pubDate>
            <atom:updated>2018-07-07T12:37:38.394Z</atom:updated>
            <content:encoded><![CDATA[<p>I generate cairo tilings because I’m working on generating some custom printed fabric. Cairo tilings are an ideal pattern for clothing prints because they can be made from the same pentagon rotated to four different angles, yet still have a semi-regular repetition, meaning that you can clip the tiling at certain places, and copy that clip up and down to make an infinite pattern.</p><p>This post goes over my method of generating cairo tilings with minimal math using <a href="https://github.com/CatherineH/svgpathtools">my fork of svgpathtools</a>, and <a href="https://svgwrite.readthedocs.io/en/master/">svgwrite</a>. The full code to generate the tilings is available in my <a href="https://github.com/CatherineH/python-sewing/blob/master/pattern_tiling.py">python-sewing</a> repository.</p><h3>Drawing the base pentagon</h3><p>According to wikipedia, a cairo tiling can be made with a pentagon with the interior angles of 120, 90, 120, 120, and 90 radians. So I’ll start off with with an angle of 120 radians, and a length of 300 radians. I’m going to lay out my pentagon like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/0*H1rt-izFl09ttHB7.png" /></figure><p><em>angle01</em> is the angle from horizontal to point 1 from point 0. I start with point 0 at 0,0:</p><pre><strong>def</strong> cexp(x):<br>    <strong>return</strong> pow(exp(1), x)<br>angle01 = 60.0<br>length1 = 300<br><em># start with the top corner at 0, 0</em><br>points = [0, None, None, None, None]</pre><p>Next, points 1 and 4 are at the projection up and down of <em>angle01</em> from point 0:</p><pre>points[1] = points[0] + length1 * cexp(1j * radians(angle01))<br>points[4] = points[0] + length1 * cexp(-1j * radians(angle01))</pre><p>points 1 and 4 have interior angles of 90 degrees. To project up from these points, I subtract <em>angle01</em> from 90:</p><pre>angle12 = -(90 - angle01)<br>points[2] = points[1] + length1 * cexp(1j * radians(angle12))<br>points[3] = points[4] + length1 * cexp(-1j * radians(angle12))</pre><p>I’ve drawn a single pentagon with minimal math — I only had to calculate the second projection angle, and the rest came from looking at the pentagon. I’m going to draw the four-groups of cairo tiling the same way.</p><h3>Drawing the four-pentagon group</h3><p>Next, I generate the 4-group:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/0*gIcyeR8F4bwWPQoD.png" /></figure><p>Like before with projecting from already-calculated points, I let svgpathtools do the work — use it to rotate the pentagons, snap them into place, then use the difference between where the points ended up for a list of transforms that I can use later.</p><pre><strong>def</strong> new_pentagon():<br>	<strong>return</strong> Path(*[Line(start=points[i - 1], end=points[i]) <strong>for</strong> i <strong>in</strong> range(len(points))])</pre><pre>transforms = [[0, 0]]<br>cairo_group = [new_pentagon()]<br><em># point 1 of pentagon 1 needs to be attached to point 1 of pentagon 0</em><br>cairo_group.append(transform_path(rotate_transform(90), new_pentagon()))<br>diff = cairo_group[0][1].end - cairo_group[1][1].end<br>transforms.append([90, diff])<br>cairo_group[1] = cairo_group[1].translated(diff)<br>cairo_group.append(transform_path(rotate_transform(180), new_pentagon()))<br><em># point 3 of pentagon 2 needs to be attached to point 2 of pentagon 0</em><br>diff = cairo_group[0][2].end - cairo_group[2][3].end<br>transforms.append([180, diff])<br>cairo_group[2] = cairo_group[2].translated(diff)<br>cairo_group.append(transform_path(rotate_transform(-90), new_pentagon()))<br><em># point 4 of pentagon 3 needs to be attached to point 1 of pentagon 0</em><br>diff = cairo_group[0][4].end - cairo_group[3][4].end<br>transforms.append([-90, diff])<br>cairo_group[3] = cairo_group[3].translated(diff)</pre><p>Finally, I want to calculate the width of the 4-group so that I know where to repeat the 4-group in the next step:</p><pre>column_offset = cairo_group[0][0].end - cairo_group[1][2].end</pre><h3>Drawing the full pattern</h3><p>The final trick to generating the full tiling is that every other 4-group in each row needs to be moved down by half of the height of the 4-group:</p><pre>dwg = Drawing(&quot;{}/tiling2.svg&quot;.format(output_folder), profile=&quot;tiny&quot;)</pre><pre>current_color = 0<br>rep_spacing = pent_width * 2 + bottom_length</pre><pre><strong>for</strong> y <strong>in</strong> range(num_down):<br>    transform = &quot;translate({}, {})&quot;.format(0, rep_spacing * y)<br>    dgroup = dwg.add(dwg.g(transform=transform))<br>    <strong>for</strong> x <strong>in</strong> range(num_across):<br>        <em># if x is odd, point 0 of pent 0 needs to be attached to point 2 of pent 1</em><br>        <strong>if</strong> x % 2 == 1:<br>            dx = int(x / 2) * rep_spacing + pent_width * 2 + column_offset.real<br>            transform = &quot;translate({}, {})&quot;.format(dx, column_offset.imag)<br>        <strong>else</strong>:<br>            transform = &quot;translate({}, {})&quot;.format(int(x / 2) * rep_spacing, 0)<br>        group = dgroup.add(dwg.g(transform=transform))<br>        <strong>for</strong> pent <strong>in</strong> cairo_group:<br>            group.add(<br>                dwg.path(**{&#39;d&#39;: pent.d(), &#39;fill&#39;: _colors[current_color % len(_colors)],<br>                            &#39;stroke-width&#39;: 4, &#39;stroke&#39;: rgb(0, 0, 0)}))<br>            current_color += 1<br>dwg.save(pretty=True)</pre><p>This generates the pattern:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*UYaaDrdooJISnHPT.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bee322e716e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extracting cut lines from Sewing Patterns with Python]]></title>
            <link>https://medium.com/@femion/extracting-cut-lines-from-sewing-patterns-with-python-656487734c15?source=rss-4a068a25ba38------2</link>
            <guid isPermaLink="false">https://medium.com/p/656487734c15</guid>
            <category><![CDATA[sewing]]></category>
            <category><![CDATA[svg]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Catherine Holloway]]></dc:creator>
            <pubDate>Thu, 10 May 2018 22:04:44 GMT</pubDate>
            <atom:updated>2018-05-11T14:52:12.531Z</atom:updated>
            <content:encoded><![CDATA[<p>The common way to make modifications to sewing patterns is to trace out the cut lines on tracing paper, then cut and tape the pieces of paper together to form a new shape to cut out of fabric. However, as a software developer, every problem is a programming one, so in this post I’m going to show <a href="https://gist.github.com/CatherineH/0eb4770408fa727669294ab29c25e970">my code</a> for extracting the cut lines from sewing patterns as SVGs, so that you can manipulate them in Inkscape.</p><p>The pattern I’m going to use in this demo is the <a href="https://indiesew.com/products/hey-june-cheyenne-tunic">Cheyenne Tunic by Hey June</a> which I recommend purchasing. I use the <a href="https://github.com/pmaupin/pdfrw">pdfrw</a> library for reading in the pattern, and investigating a pdf using this library can really help your understanding of the format.</p><p>Extracting data from PDFs is quite challenging. If you’re unfamiliar with PDFs, I recommend the O’Reilly book <a href="https://www.amazon.com/Developing-PDF-Portable-Document-Format-ebook/dp/B00IV3J23O/ref=sr_1_1?ie=UTF8&amp;qid=1525986567&amp;sr=8-1&amp;keywords=developing+pdf+oreilly">Developing with PDF</a>.</p><h3>Getting the Right Size</h3><p>Most sewing patterns store the cut lines for different sizes in original content groups (known as layers in most PDF readers). This allows you to turn off the sizes you don’t want before printing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/0*KbsTiuzDQYGXJKrb.png" /></figure><p>I set up a command argument parser to define the filename of the PDF and get the size to extract.</p><pre>parser = argparse.ArgumentParser(<br>    description=&#39;Generate new pattern pieces from existing patterns&#39;)<br>parser.add_argument(&#39;--filename&#39;, type=str, help=&#39;The filename of the pdf pattern.&#39;)<br>parser.add_argument(&#39;--size&#39;, type=str, help=&quot;The size of the pattern to analyze.&quot;)</pre><p>The content groups are defined both in the PDF document’s root, and on each page. The group keys for the content groups are defined under <strong>/Resources -&gt; /Properties</strong>.</p><pre>args = parser.parse_args()<br>    x = PdfReader(args.filename, decompress=True)<br>    name = &#39;(&#39; + args.size + &#39;)&#39;<br>    shapes = []<br>    paths = []<br>    <strong>for</strong> page_num, page <strong>in</strong> enumerate(x.pages):<br>        <strong>if</strong> &#39;/Resources&#39; <strong>not</strong> <strong>in</strong> page:<br>            <strong>continue</strong><br>        <strong>if</strong> &#39;/Properties&#39; <strong>not</strong> <strong>in</strong> page[&#39;/Resources&#39;]:<br>            <strong>continue</strong><br>        oc_keyname = [key <strong>for</strong> key <strong>in</strong> page[&#39;/Resources&#39;][&#39;/Properties&#39;]<br>                      <strong>if</strong> page[&#39;/Resources&#39;][&#39;/Properties&#39;][key][&#39;/Name&#39;] == name]</pre><p>If there no original content groups matching the size we want, skip to the next page:</p><pre><strong>if</strong> len(oc_keyname) == 0:<br>            <strong>continue</strong></pre><p>Another thing to extract out of the <strong>/Resources</strong> are the graphics states. If you want a faithful color representation of the graphics when converting PDF to SVG, you need these values. However, since these rules are a bit tricky, and I only care about the shapes, I am not doing anything meaningful with this information at the moment:</p><pre>gstates = {}<br>        <strong>if</strong> &#39;/ExtGState&#39; <strong>in</strong> page[&#39;/Resources&#39;]:<br>            gstates = page[&#39;/Resources&#39;][&#39;/ExtGState&#39;]</pre><p>The paths themselves will be in the page’s content stream. You want to start reading at the group key name, and then end at the end of that block, which is typically indicated by the <strong>EMC</strong> keyword:</p><pre>lines = page.Contents.stream.split(&#39;<strong>\n</strong>&#39;)<br>        start_index = [i <strong>for</strong> i, l <strong>in</strong> enumerate(lines) <strong>if</strong> l.find(oc_keyname) &gt;= 0][0]<br>        end_index = \<br>        [i <strong>for</strong> i, l <strong>in</strong> enumerate(lines) <strong>if</strong> l.find(&#39;EMC&#39;) &gt;= 0 <strong>and</strong> i &gt; start_index][0]<br>        shape = &quot;<strong>\n</strong>&quot;.join(lines[start_index:end_index])</pre><h3>PostScript Graphics to SVG</h3><p>PDF graphics use a format similar to SVG for expressing shapes and paths, but uses a PostScript state machine for updating stylistic elements (like fill and stroke color) and for appending to paths. The instructions are written in reverse Polish notation, where the <strong>q</strong> operation pushes values onto the state machine and <strong>Q</strong> pops off the stack. I wrote a PostScript interpreter that goes over the instructions line by line, and adds shapes to a <a href="https://svgwrite.readthedocs.io/en/master/">svgwrite</a> <strong>Drawing</strong>. It’s by no means complete, but it’s good enough for my purposes. Some operators, like <strong>n</strong>, define clipping paths so that the cut lines render within the page window, and I ignore these.</p><pre><strong>def</strong> parse_shape(shape, i, gstates):<br>    <em># see </em><a href="https://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/PDF32000_2008.pdf"><em>https://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/PDF32000_2008.pdf</em></a><br>    output_filename = &quot;page<strong>%</strong>s.svg&quot; % i<br>    dwg = Drawing(output_filename, profile=&#39;tiny&#39;)<br>    fill = &quot;none&quot;<br>    stroke = rgb(0, 0, 0)<br>    stroke_width = 4<br>    transform = (1, 0, 0, 1, 0, 0)<br>    shapes_stack = []<br>    d = &quot;&quot;<br>    paths = []<br>    <strong>for</strong> line <strong>in</strong> shape.split(&quot;<strong>\n</strong>&quot;):<br>        line = line.strip()<br>        parts = line.split(&quot; &quot;)<br>        nums = []<br>        <strong>for</strong> part <strong>in</strong> parts:<br>            <strong>try</strong>:<br>                nums.append(float(part))<br>            <strong>except</strong> ValueError:<br>                <strong>pass</strong><br>        operation = parts[-1]<br>        <strong>if</strong> operation == &#39;BDC&#39;:<br>            <strong>continue</strong><br>        <strong>elif</strong> operation == &#39;q&#39;:<br>            <em># q - start stack</em><br>            <strong>continue</strong><br>        <strong>elif</strong> operation == &#39;re&#39;:<br>            <em># rectangle</em><br>            vals = {&#39;insert&#39;: (nums[0], nums[1]), &#39;size&#39;: (nums[2], nums[3])}<br>            <strong>if</strong> fill:<br>                vals[&#39;fill&#39;] = fill<br>            <strong>if</strong> stroke:<br>                vals[&#39;stroke&#39;] = stroke<br>            shapes_stack.append(dwg.rect(**vals))<br>        <strong>elif</strong> operation == &#39;n&#39;:<br>            <em># - clipping path</em><br>            <strong>continue</strong><br>        <strong>elif</strong> operation == &#39;RG&#39;:<br>            <em># set stroke color</em><br>            stroke = rgb(*nums[0:3])<br>        <strong>elif</strong> operation == &#39;J&#39;:<br>            <em># not sure how to implement cap styles</em><br>            <strong>continue</strong><br>        <strong>elif</strong> operation == &#39;cm&#39;:<br>            <em># current transformation matrix</em><br>            transform = nums[0:6]<br>        <strong>elif</strong> operation == &#39;F&#39; <strong>or</strong> operation == &#39;f&#39;:<br>            <em># fill</em><br>            fill = rgb(*nums[0:3])<br>        <strong>elif</strong> operation == &#39;m&#39;:<br>            <em># move to</em><br>            d += &quot;M &quot; + format_pointstr(parts[0:2])<br>        <strong>elif</strong> operation == &#39;c&#39;:<br>            <em># curve</em><br>            d += &quot; C &quot; + format_pointstr(parts[0:6])<br>        <strong>elif</strong> operation == &#39;v&#39;:<br>            <em># append to bezier curve</em><br>            d += &quot; S &quot; + format_pointstr(parts[0:4])<br>        <strong>elif</strong> operation == &#39;y&#39;:<br>            d += &quot; C &quot; + format_pointstr(parts[0:4])+&quot; &quot;+format_pointstr(parts[2:4])<br>        <strong>elif</strong> operation == &#39;l&#39;:<br>            <em># line to</em><br>            d += &quot; L &quot; + format_pointstr(parts[0:2])<br>        <strong>elif</strong> operation == &#39;h&#39;:<br>            <em># make sure it&#39;s a closed path</em><br>            <strong>continue</strong><br>        <strong>elif</strong> operation == &#39;S&#39;:<br>            <em># stroke to 4-unit width</em><br>            <strong>continue</strong><br>        <strong>elif</strong> operation == &#39;Q&#39;:<br>            <em># end stack (draw)</em><br>            <em># apply transformation...</em><br>            <strong>for</strong> shape <strong>in</strong> shapes_stack:<br>                dwg.add(shape)<br>            <strong>if</strong> len(d) &gt; 0:<br>                paths.append(d + &quot; Z&quot;)<br>                d = &quot; &quot;.join([transform_str(p, transform) <strong>for</strong> p <strong>in</strong> d.split(&quot; &quot;)])<br>                vals = {&#39;d&#39;: d}<br>                vals[&#39;stroke-width&#39;] = stroke_width<br>                <strong>if</strong> fill:<br>                    vals[&#39;fill&#39;] = fill<br>                <strong>if</strong> stroke:<br>                    vals[&#39;stroke&#39;] = stroke<br><br>                dwg.add(dwg.path(**vals))<br>            d = &#39;&#39;<br>            shapes_stack = []<br>        <strong>elif</strong> operation == &#39;gs&#39;:<br>            key = parts[0]<br>            <strong>if</strong> key <strong>not</strong> <strong>in</strong> gstates:<br>                <strong>print</strong>(&quot;could not find state <strong>%</strong>s in dictionary&quot;)<br>            state = gstates[key]<br>            <em># color blending not yet implemented</em><br>            <strong>pass</strong><br>        <strong>elif</strong> operation == &#39;w&#39;:<br>            stroke_width = nums[0]<br>        <strong>else</strong>:<br>            <strong>print</strong>(&quot;not sure what to do with <strong>%</strong>s <strong>%</strong>s&quot; % (operation, line))<br>    dwg.save()<br>    <strong>return</strong> paths</pre><p>PDF uses the same format as SVG for expressing transformations. Here’s my code for applying these transformations, which is copied from my fork of <a href="https://github.com/CatherineH/svgpathtools">svgpathtools</a></p><pre><strong>def</strong> transform_point(point, matrix=(1, 0, 0, 1, 0, 0), format=&quot;float&quot;, relative=False):<br>    a, b, c, d, e, f = matrix<br>    <strong>if</strong> isinstance(point, list):<br>        x, y = point<br>    <strong>else</strong>:<br>        point_parts = point.split(&#39;,&#39;)<br>        <strong>if</strong> len(point_parts) &gt;= 2:<br>            x, y = [float(x) <strong>for</strong> x <strong>in</strong> point_parts]<br>        <strong>else</strong>:<br>            <em># probably got a letter describing the point, i.e., m or z</em><br>            <strong>return</strong> point<br>    <em># if the transform is relative, don&#39;t apply the translation</em><br>    <strong>if</strong> relative:<br>        x, y = a * x + c * y, b * x + d * y<br>    <strong>else</strong>:<br>        x, y = a * x + c * y + e, b * x + d * y + f<br>    <strong>if</strong> format == &quot;float&quot;:<br>        <strong>return</strong> x, y<br>    <strong>else</strong>:<br>        <strong>return</strong> &quot;<strong>%</strong>s<strong>%</strong>s<strong>%</strong>s&quot; % (x, point_separator, y)</pre><p>Since the same cut lines are spread accross multiple pages, I want to eliminate duplicate cut lines, which I can do using set, since the shapes are all path strings:</p><pre>paths = sorted(list(set(paths)))</pre><p>Here’s all the unique cut lines for the XS shape:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*OHt90WRuSKf7yRBH.png" /></figure><p>Now that I have the cut lines in SVG format, I can programmatically manipulate them and then print them out again, but that’s a post for another day.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=656487734c15" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3 ways to cut SVG shapes]]></title>
            <link>https://medium.com/@femion/3-ways-to-cut-svg-shapes-d24108aba4a3?source=rss-4a068a25ba38------2</link>
            <guid isPermaLink="false">https://medium.com/p/d24108aba4a3</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[svg]]></category>
            <dc:creator><![CDATA[Catherine Holloway]]></dc:creator>
            <pubDate>Tue, 03 Apr 2018 17:06:16 GMT</pubDate>
            <atom:updated>2018-04-03T17:06:16.284Z</atom:updated>
            <content:encoded><![CDATA[<p>SVGs will display the last added shape on top. This means you can very easily create the Canadian flag by layering a white rectangle on top of a red rectangle, but <a href="http://catherineh.github.io/programming/2018/01/21/layering-svgs-in-javascript">that correctly representing merged SVGs is difficult</a>. It also means that, if you’re using SVGs to generate things in meatspace, like with a 3D printer, laser cutter or computerized sewing machine, you’re going to waste material and reduce the quality of the output. Before sending the SVG to the device, you’ll probably want to cut out the later shapes out of the lower shapes. Doing this is kind of tricky, and I’ll go over two methods that work, with trade-offs and one complicated method that I haven’t completed implementing. The code for this post is in my <a href="https://github.com/CatherineH/python-embroidery/">python-embroidery</a> library.</p><h3>Subtract the Paths</h3><p>In SVGs, if you add one path string to another after the first string, SVG will render the second d string as a cut-out of the first d string. This means that you can go through the SVG paths and add the next two together:</p><pre><strong>for</strong> i <strong>in</strong> range(1, len(all_paths)):<br>    remove_path = all_paths[i].d()<br>    current_path = all_paths[i-1].d()<br>    all_paths[i-1] = parse_path(current_path+&quot; &quot;+remove_path)</pre><p>This works well for shapes without the holes, so for example the shape:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/261/0*djWm2icYK3oribxC.png" /></figure><p>will be cut into the shapes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/0*jV2VGdKqZ2JTqFzO.png" /></figure><p>However, for shapes that already have holes, like the shape:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/261/0*-pJBZvEVU4Z87BWh.png" /></figure><p>will be cut into the shapes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/0*g3Qo0Mer9f246h2l.png" /></figure><p>Cutting a path on an existing negative space turns it into a positive space. This makes sense if you have only an on or off setting for each fill area. So this method works well for simple shapes, but not for shapes that already have negative spaces. As soon as you try to stack multiple shapes, you’re going to be double-negating lots of shapes.</p><h3>Use Computational Geometry</h3><p>Computational Geometry is a tricky subject, luckily we can leverage that is used extensively in GIS code to avoid doing our own calculations. The <a href="https://toblerity.org/shapely">Shapely</a> python package has functions to perform all set operations on polygon points, including differencing. It doesn’t support curves, so you must first convert the SVG paths into polygons, do the difference, then convert the polygon into an SVG path:</p><pre><strong>from</strong> <strong>svgpathtools</strong> <strong>import</strong> Line, Path<br><strong>from</strong> <strong>shapely.geometry</strong> <strong>import</strong> Polygon</pre><pre><strong>def</strong> path_difference_shapely(path1, path2):<br>    <em># convert both paths to polygons</em><br>    <strong>def</strong> path_to_poly(inpath):<br>        points = []<br>        <strong>for</strong> path <strong>in</strong> inpath:<br>            <strong>if</strong> isinstance(path, Line):<br>                points.append([path.end.real, path.end.imag])<br>            <strong>else</strong>:<br>                num_segments = ceil(path.length() / minimum_stitch)<br>                <strong>for</strong> seg_i <strong>in</strong> range(int(num_segments + 1)):<br>                    points.append([path.point(seg_i / num_segments).real,<br>                                    path.point(seg_i / num_segments).imag])<br>        <strong>return</strong> Polygon(points)<br>    poly1 = path_to_poly(path1)<br>    poly2 = path_to_poly(path2)<br>    diff_poly = poly1.difference(poly2)<br>    points = diff_poly.exterior.coords<br>    new_path = []<br>    <strong>for</strong> i <strong>in</strong> range(len(points)-1):<br>        new_path.append(Line(start=points[i-1][0]+points[i-1][1]*1j,<br>                             end=points[i][0]+points[i][1]*1j))<br>    new_path.append(Line(start=points[-1][0]+points[-1][1]*1j,<br>                             end=points[0][0]+points[0][1]*1j))<br>    <em># make a new path from these points</em><br>    <strong>return</strong> Path(*new_path)</pre><p>Here I’m sampling along any non-Line segments in the curve at intervals of <strong>minimum_stitch</strong>, which is the smallest stitch I’m going to tell my computerized sewing machine to make.</p><p>This cuts out our negative space the way we’d like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/0*RFcGTGH0DpB9QuoY.png" /></figure><p>Which is what we want. Unfortunately, doing this requires transforming our wonderful continuous Bezier curves into gross discrete polygons. This isn’t a problem if you know the lower resolution of the device that is going to render your SVG, like the minimum stitch of my sewing machine.</p><h3>Use Inkscape</h3><p>So what if you want to preserve your curves? Inkscape is able to do differences between shapes remarkably well, unfortunately <a href="https://gitlab.com/inkscape/inkscape/blob/master/src/livarot/ShapeSweep.cpp#L838">their code</a> for doing this is a thousand lines that is not linted, has no comments, and has methods and variables written in Franglish. Eventually, I’d like to understand what it is doing. Inkscape is a really wonderful tool and I understand that it is difficult to make a professional-level codebase on 0 income. If you want to just use Inkscape’s operations in your python code, you can use the <a href="https://gitlab.com/su-v/inx-pathops">inx-pathops</a> package.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d24108aba4a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Text to SVG Paths]]></title>
            <link>https://medium.com/@femion/text-to-svg-paths-7f676de4c12b?source=rss-4a068a25ba38------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f676de4c12b</guid>
            <category><![CDATA[svg]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Catherine Holloway]]></dc:creator>
            <pubDate>Thu, 01 Feb 2018 20:03:40 GMT</pubDate>
            <atom:updated>2018-02-01T20:03:40.369Z</atom:updated>
            <content:encoded><![CDATA[<p>Most paper cutters, laser engravers, and 3D printers can’t handle fonts, and so ignore 〈text〉 tags in SVGs. Instead, text elements need to first be converted to paths by a program like Inkscape. This post describes how to automate text to path conversion in python using the <a href="https://github.com/rougier/freetype-py">freetype</a>, <a href="https://github.com/mathandy/svgpathtools">svgpathtools</a>, and <a href="https://github.com/mozman/svgwrite">svgwrite</a> libraries.</p><p>I used the freetype <a href="https://github.com/rougier/freetype-py/blob/04c62af91c66b3268051921d609c9552d93560aa/examples/glyph-vector-2.py">rendering in matplotlib example</a> as a guide.</p><p>First, load the svgpathtools paths, and define a tuple_to_imag function to convert between freetype’s tupple point representation to svgpathtools’ imaginary numbers:</p><pre><strong>from</strong> <strong>svgpathtools</strong> <strong>import</strong> wsvg, Line, QuadraticBezier, Path<br><strong>def</strong> tuple_to_imag(t):<br>    <strong>return</strong> t[0] + t[1] * 1j</pre><p>Load your font and initialize a character:</p><pre><strong>from</strong> <strong>freetype</strong> <strong>import</strong> Face<br>face = Face(&#39;./Vera.ttf&#39;)<br>face.set_char_size(48 * 64)<br>face.load_char(&#39;a&#39;)</pre><p>We’ll be converting a string character by character. After converting this character to a path, you use the same method to convert the next character to a path, offset by the kerning:</p><pre>face.get_kerning(&#39;a&#39;, &#39;b&#39;)</pre><p>You’ll need to flip the y values of the points in order to render the characters right-side-up:</p><pre>outline = face.glyph.outline<br>y = [t[1] <strong>for</strong> t <strong>in</strong> outline.points]<br><em># flip the points</em><br>outline_points = [(p[0], max(y) - p[1]) <strong>for</strong> p <strong>in</strong> outline.points]</pre><p>The face has three lists of interest: the points, the tags, and the contours. The points are the x/y coordinates of the start and end points of lines and control points. The tags indicate what type of point it is, where tag values of 0 are control points. Finally, the contours are the end point list index for each shape. Characters like i or ! have two shapes, most others have only one contour. So, for each contour, we want to pick out only the tags and points for that contour.</p><pre>start, end = 0, 0<br>paths = []</pre><pre><strong>for</strong> i <strong>in</strong> range(len(outline.contours)):<br>    end = outline.contours[i]<br>    points = outline_points[start:end + 1]<br>    points.append(points[0])<br>    tags = outline.tags[start:end + 1]<br>    tags.append(tags[0])</pre><p>Next, we want to split the points up into path segments, using the tags. If the tags are 0, add the point to the current segment, else create a new segment, so that control points stay with their path segments:</p><pre>segments = [[points[0], ], ]<br>    <strong>for</strong> j <strong>in</strong> range(1, len(points)):<br>        segments[-1].append(points[j])<br>        <strong>if</strong> tags[j] <strong>and</strong> j &lt; (len(points) - 1):<br>            segments.append([points[j], ])</pre><p>Then convert the segments to lines. For lines with two control points (segment length 4), I could use the CubicBezier, but I find that breaking it into two Quadratic Beziers where the end point for the first and the start point of the second curve is the average of the control points, is more attractive:</p><pre>for segment in segments:<br>   if len(segment) == 2:<br>       paths.append(Line(start=tuple_to_imag(segment[0]),<br>                              end=tuple_to_imag(segment[1])))<br>   elif len(segment) == 3:<br>       paths.append(QuadraticBezier(start=tuple_to_imag(segment[0]),<br>                                 control=tuple_to_imag(segment[1]),<br>                                   end=tuple_to_imag(segment[2])))<br>   elif len(segment) == 4:<br>      C = ((segment[1][0] + segment[2][0]) / 2.0,<br>                 (segment[1][1] + segment[2][1]) / 2.0)</pre><pre>      paths.append(QuadraticBezier(start=tuple_to_imag(segment[0]),<br>                                 control=tuple_to_imag(segment[1]),<br>                                   end=tuple_to_imag(C)))<br>      paths.append(QuadraticBezier(start=tuple_to_imag(C),<br>                                 control=tuple_to_imag(segment[2]),<br>                                     end=tuple_to_imag(segment[3])))</pre><p>Set the start location to the end location and continue. You can use the svgpathtools <em>Path</em> to merge the paths:</p><pre>start = end + 1</pre><pre>path = Path(*paths)<br>wsvg(path, filename=&quot;text.svg&quot;)</pre><p>text.svg looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/226/1*_Ua38EDLPuXwQ5rt0_yOdg.png" /></figure><p>You can see the full code in <a href="https://gist.github.com/CatherineH/499a312a04582a00e7559ac0c8f133fa">this gist</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f676de4c12b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Layering SVGs in JavaScript]]></title>
            <link>https://medium.com/front-end-weekly/layering-svgs-in-javascript-72c8cc7ba98d?source=rss-4a068a25ba38------2</link>
            <guid isPermaLink="false">https://medium.com/p/72c8cc7ba98d</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Catherine Holloway]]></dc:creator>
            <pubDate>Mon, 22 Jan 2018 12:33:29 GMT</pubDate>
            <atom:updated>2018-01-22T12:33:29.959Z</atom:updated>
            <content:encoded><![CDATA[<p>If you want to create or manipulate SVGs, there several great JavaScript libraries, such as <a href="https://d3js.org/">d3</a> or <a href="http://snapsvg.io/">Snap.js</a>. However, right now I just want to stack a set of already-existing SVGs. I’ve created a <a href="https://gist.github.com/CatherineH/5d923ec585acdb89ab2df34c095a681c">gist</a> with my code to stack SVGs, I’m going to go over it in this post.</p><p>This post assumes that the SVGs to stack are the strings of the file contents of the SVGs. You can acquire these strings by either reading in a user-supplied input file, or by making an HTTP request, but that is beyond the scope of this post.</p><h3>Quick and Dirty</h3><p>To extract the svg contents out of a string, you could do some string manipulations to strip everything up to the opening &lt;svg&gt; tag and after the closing &lt;/svg&gt; tag. But since JavaScript was created with the goal of being able to manipulate XML files, this seems unnecessary. Instead, I use the DOMParser object to extract the SVG contents:</p><pre><strong>function</strong> getSVGContents(inputString){<br>    <strong>let</strong> domParser = <strong>new</strong> DOMParser();<br>    <strong>let</strong> svgDOM = domParser.parseFromString(inputString, &#39;text/xml&#39;)<br>        .getElementsByTagName(&#39;svg&#39;)[0];<br>    <strong>return</strong> svgDOM.innerHTML<br>}</pre><p>Then, you can simply concatenate the strings:</p><pre>document.getElementById(&quot;quickSVG&quot;).innerHTML =<br>         getSVGContents(circle)+getSVGContents(star);</pre><p>SVGs have no z-index, like CSS. The elements that appear on the top are just the last elements to be added. So the above code would create the svg:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/0*8_Ehl4bSE8JGP1mg.png" /></figure><p>Whereas if you change the order of ‘circle’ and ‘star’ in the string concatenation:</p><pre>document.getElementById(&quot;quickSVG&quot;).innerHTML =<br>         getSVGContents(star)+getSVGContents(circle);</pre><p>The star will now be under the circle:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/0*m5QebhbIPsCDyT6D.png" /></figure><h3>Less Quick, more OOPy</h3><p>The above method is okay if you want to just layer the SVGs without manipulating them. But since we already have our strings parsed to DOM elements, we can combine the elements directly. We can initialize a SVG element, then use <em>appendChild</em> to move the child nodes from one element to another:</p><pre><strong>function</strong> addSVGs(inputStrings){<br>    <em>// takes a list of strings of SVGs to merge together into one large element</em><br>    <strong>let</strong> svgMain = document.createElement(&quot;svg&quot;);<br>    <strong>for</strong>(<strong>let</strong> stringI=0;stringI&lt;inputStrings.length;stringI++){<br>        <strong>let</strong> domParser = <strong>new</strong> DOMParser();<br>        <strong>let</strong> svgDOM = domParser.parseFromString(inputStrings[stringI], &#39;text/xml&#39;)<br>            .getElementsByTagName(&#39;svg&#39;)[0];<br>        <strong>while</strong>(svgDOM.childNodes.length&gt;0){<br>            svgMain.appendChild(svgDOM.childNodes[0]);<br>        }<br>    }<br>    <strong>return</strong> svgMain</pre><pre>}<br><strong>var</strong> svgMain = addSVGs([circle, star]);<br>document.getElementById(&quot;appendSVG&quot;).innerHTML = svgMain.innerHTML;</pre><p>The things I found confusing about this method were:</p><ul><li>first, unlike other XML parsers, DOMParser does not ignore whitespace. The tabs I put in to make my SVG strings more readable get read in as <strong>#text</strong> nodes. These strings will get rendered as whitespace, which don’t effect the final SVG.</li><li><strong>appendChild</strong> removes the element from the input element’s parent, hence why it’s the first childNodes added to the mainSVG, and why I keep appending until there are no more childNodes in the svgDOM.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72c8cc7ba98d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/front-end-weekly/layering-svgs-in-javascript-72c8cc7ba98d">Layering SVGs in JavaScript</a> was originally published in <a href="https://medium.com/front-end-weekly">Frontend Weekly</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Grabbing Large Datasets out of AppEngine Search Indexes]]></title>
            <link>https://medium.com/@femion/grabbing-large-datasets-out-of-appengine-search-indexes-4889f5ca1570?source=rss-4a068a25ba38------2</link>
            <guid isPermaLink="false">https://medium.com/p/4889f5ca1570</guid>
            <category><![CDATA[app-engine]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Catherine Holloway]]></dc:creator>
            <pubDate>Fri, 19 Jan 2018 22:16:49 GMT</pubDate>
            <atom:updated>2018-01-19T22:16:49.474Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re building a Big Data application on AppEngine, you’ll probably need to grab more than a thousand entries out of a search index. It turns out this is not as straightforward as expected. I’ve built a <a href="https://github.com/CatherineH/appengine-large-offset-example">sample project</a> to demo how to do this.</p><p>In this demo we initialize our index to have 3000 entries of the numbers between 0 and 3000:</p><pre>search_index = search.Index(name=INDEX_NAME, namespace=NAMESPACE)<br><strong>for</strong> i <strong>in</strong> range(3000):<br>    fields = [search.NumberField(name=&#39;number_value&#39;, value=i),<br>              search.NumberField(name=&#39;last_modified&#39;, value=int(time()))]<br>    doc = search.Document(fields=fields)<br>    results = search_index.put(doc)</pre><p>A first attempt at building a handler to query this index would be:</p><pre><strong>class</strong> <strong>Search</strong>(webapp2.RedirectHandler):<br>    <strong>def</strong> get(self):<br>        <strong>try</strong>:<br>            limit = int(self.request.get(&#39;limit&#39;))<br>        <strong>except</strong>:<br>            limit = DOCS_PER_PAGE_LIMIT<br>        <strong>try</strong>:<br>            offset = int(self.request.get(&#39;offset&#39;))<br>        <strong>except</strong>:<br>            offset = 0</pre><pre>        expr_list = [<br>            search.SortExpression(<br>                expression=&#39;number_value&#39;,<br>                default_value=int(0),<br>                direction=search.SortExpression.ASCENDING<br>            )<br>        ]<br>        sort_opts = search.SortOptions(expressions=expr_list)<br>        index = search.Index(name=INDEX_NAME, namespace=NAMESPACE)<br>        search_query = search.Query(<br>            query_string=&#39;&#39;,<br>            options=search.QueryOptions(<br>                limit=limit, sort_options=sort_opts, offset=offset, ids_only=False)<br>        )</pre><p>This works well for values under 1000, but if you try to run the query /search?limit=3000, you’ll get the error:</p><pre>Traceback (most recent call last):<br>  File &quot;/home/catherine/installed/google-cloud-sdk/platform/google_appengine/lib/webapp2-2.5.2/webapp2.py&quot;, line 1535, <strong>in</strong> __call__<br>    rv = self.handle_exception(request, response, e)<br>  File &quot;/home/catherine/installed/google-cloud-sdk/platform/google_appengine/lib/webapp2-2.5.2/webapp2.py&quot;, line 1529, <strong>in</strong> __call__<br>    rv = self.router.dispatch(request, response)<br>  File &quot;/home/catherine/installed/google-cloud-sdk/platform/google_appengine/lib/webapp2-2.5.2/webapp2.py&quot;, line 1278, <strong>in</strong> default_dispatcher<br>    <strong>return</strong> route.handler_adapter(request, response)<br>  File &quot;/home/catherine/installed/google-cloud-sdk/platform/google_appengine/lib/webapp2-2.5.2/webapp2.py&quot;, line 1102, <strong>in</strong> __call__<br>    <strong>return</strong> handler.dispatch()<br>  File &quot;/home/catherine/installed/google-cloud-sdk/platform/google_appengine/lib/webapp2-2.5.2/webapp2.py&quot;, line 572, <strong>in</strong> dispatch<br>    <strong>return</strong> self.handle_exception(e, self.app.debug)<br>  File &quot;/home/catherine/installed/google-cloud-sdk/platform/google_appengine/lib/webapp2-2.5.2/webapp2.py&quot;, line 570, <strong>in</strong> dispatch<br>    <strong>return</strong> method(*args, **kwargs)<br>  File &quot;/home/catherine/python_projects/appengine-large-offset-example/main.py&quot;, line 55, <strong>in</strong> get<br>    limit=limit, sort_options=sort_opts, offset=offset, ids_only=False)<br>  File &quot;/home/catherine/installed/google-cloud-sdk/platform/google_appengine/google/appengine/api/search/search.py&quot;, line 3073, <strong>in</strong> __init__<br>    self._limit = _CheckLimit(limit)<br>  File &quot;/home/catherine/installed/google-cloud-sdk/platform/google_appengine/google/appengine/api/search/search.py&quot;, line 2858, <strong>in</strong> _CheckLimit<br>    upper_bound=MAXIMUM_DOCUMENTS_RETURNED_PER_SEARCH)<br>  File &quot;/home/catherine/installed/google-cloud-sdk/platform/google_appengine/google/appengine/api/search/search.py&quot;, line 496, <strong>in</strong> _CheckInteger<br>    <strong>raise</strong> ValueError(&#39;<strong>%</strong>s, <strong>%</strong>d must be &lt;= <strong>%</strong>d&#39; % (name, value, upper_bound))<br>ValueError: limit, 3000 must be &lt;= 1000</pre><p>We can’t get all 3000 entries in one query, so we’ll have to spread the acquisition over three queries:</p><ul><li>/search?limit=1000</li><li>/search?limit=1000&amp;offset=1000</li><li>/search?limit=1000&amp;offset=2000</li></ul><p>The first two queries work, but if you set offset to 2000, you’ll get the error:</p><pre>Traceback (most recent call last):<br>  File &quot;/home/catherine/installed/google-cloud-sdk/platform/google_appengine/lib/webapp2-2.5.2/webapp2.py&quot;, line 1535, <strong>in</strong> __call__<br>    rv = self.handle_exception(request, response, e)<br>  File &quot;/home/catherine/installed/google-cloud-sdk/platform/google_appengine/lib/webapp2-2.5.2/webapp2.py&quot;, line 1529, <strong>in</strong> __call__<br>    rv = self.router.dispatch(request, response)<br>  File &quot;/home/catherine/installed/google-cloud-sdk/platform/google_appengine/lib/webapp2-2.5.2/webapp2.py&quot;, line 1278, <strong>in</strong> default_dispatcher<br>    <strong>return</strong> route.handler_adapter(request, response)<br>  File &quot;/home/catherine/installed/google-cloud-sdk/platform/google_appengine/lib/webapp2-2.5.2/webapp2.py&quot;, line 1102, <strong>in</strong> __call__<br>    <strong>return</strong> handler.dispatch()<br>  File &quot;/home/catherine/installed/google-cloud-sdk/platform/google_appengine/lib/webapp2-2.5.2/webapp2.py&quot;, line 572, <strong>in</strong> dispatch<br>    <strong>return</strong> self.handle_exception(e, self.app.debug)<br>  File &quot;/home/catherine/installed/google-cloud-sdk/platform/google_appengine/lib/webapp2-2.5.2/webapp2.py&quot;, line 570, <strong>in</strong> dispatch<br>    <strong>return</strong> method(*args, **kwargs)<br>  File &quot;/home/catherine/python_projects/appengine-large-offset-example/main.py&quot;, line 55, <strong>in</strong> get<br>    limit=limit, sort_options=sort_opts, offset=offset, ids_only=False)<br>  File &quot;/home/catherine/installed/google-cloud-sdk/platform/google_appengine/google/appengine/api/search/search.py&quot;, line 3082, <strong>in</strong> __init__<br>    self._offset = _CheckOffset(offset)<br>  File &quot;/home/catherine/installed/google-cloud-sdk/platform/google_appengine/google/appengine/api/search/search.py&quot;, line 2895, <strong>in</strong> _CheckOffset<br>    upper_bound=MAXIMUM_SEARCH_OFFSET)<br>  File &quot;/home/catherine/installed/google-cloud-sdk/platform/google_appengine/google/appengine/api/search/search.py&quot;, line 496, <strong>in</strong> _CheckInteger<br>    <strong>raise</strong> ValueError(&#39;<strong>%</strong>s, <strong>%</strong>d must be &lt;= <strong>%</strong>d&#39; % (name, value, upper_bound))<br>ValueError: offset, 2000 must be &lt;= 1000</pre><p>Darn. Because of these limitations, we’re going to need a concept from Databases usually reserved for operations that span multiple computers: a cursor.</p><p>You can set as a parameter to the query options:</p><pre>search_query = search.Query(<br>    query_string=&#39;&#39;,<br>    options=search.QueryOptions(<br>        limit=self.limit,<br>        sort_options=self.sort_opts,<br>        cursor=search.Cursor(per_result=False),<br>        ids_only=False,<br>    )<br>)</pre><p>you can access the cursor for this search query after getting the results:</p><pre>search_results = self.index.search(search_query)<br>cursor = search_results.cursor</pre><p>The strategy for pulling out the entries is this:</p><ol><li>create a search with no offset and a new cursor</li><li>initialize current_offset to 0</li><li>while current_offset is less than the desired offset, query the search index again with the cursor of the last query, and add the limit to the current_offset</li><li>output the last search results</li></ol><p>It would be nice if we could start our loop at the maximum offset in order to limit the number of repetitions of step 3, but if you do, you’ll get the error:</p><pre>ValueError: cannot set cursor <strong>and</strong> offset together</pre><p>Also, make sure that you set the <strong>per_result</strong> value of <strong>search.Cursor</strong> to <strong>False</strong>, or else the cursor will be None:</p><pre>File &quot;/home/catherine/python_projects/appengine-large-offset-example/main.py&quot;, line 109, <strong>in</strong> query_with_cursors<br>    cursor_cache[current_offset] = search_results.cursor.web_safe_string<br>AttributeError: &#39;NoneType&#39; object has no attribute &#39;web_safe_string&#39;</pre><p>Here’s the implementation:</p><pre>current_offset = self.limit<br>search_query = search.Query(query_string=&#39;&#39;,<br>    options=search.QueryOptions(<br>        limit=self.limit,<br>        sort_options=self.sort_opts,<br>        cursor=search.Cursor(per_result=False),<br>        ids_only=False,<br>    )<br>)</pre><pre>search_results = self.index.search(search_query)<br><strong>if</strong> self.offset &gt;= search_results.number_found:<br>    <strong>return</strong> self.render_search_doc([])<br><strong>while</strong> current_offset &lt; self.offset:<br>    current_offset += self.limit<br>    search_query = search.Query(query_string=&#39;&#39;,<br>        options=search.QueryOptions(<br>            limit=self.limit,<br>            sort_options=self.sort_opts,<br>            cursor=search_results.cursor<br>        )<br>    )<br>    search_results = self.index.search(search_query)<br>self.render_search_doc(search_results)</pre><p>Now, if we’re going to be querying an offset of up to 100000, it will take a while to do 1000 queries. So, it would be better if we could cache these cursors. We can stick the web_safe_string in memcache:</p><pre>cursor_cache = {}<br>current_offset = self.limit<br>search_query = search.Query(query_string=&#39;&#39;,<br>    options=search.QueryOptions(<br>        limit=self.limit,<br>        sort_options=self.sort_opts,<br>        cursor=search.Cursor(per_result=False),<br>        ids_only=False,<br>    )<br>)</pre><pre>search_results = self.index.search(search_query)<br>cursor_cache[current_offset] = search_results.cursor.web_safe_string<br><strong>if</strong> self.offset &gt;= search_results.number_found:<br>    <strong>return</strong> self.render_search_doc([])<br><strong>while</strong> current_offset &lt; self.offset:<br>    current_offset += self.limit<br>    search_query = search.Query(query_string=&#39;&#39;,<br>        options=search.QueryOptions(<br>            limit=self.limit,<br>            sort_options=self.sort_opts,<br>            cursor=search_results.cursor<br>        )<br>    )<br>    search_results = self.index.search(search_query)<br>    cursor_cache[current_offset] = search_results.cursor.web_safe_string<br>memcache.set(cursor_cache_key, json.dumps(cursor_cache))<br>self.render_search_doc(search_results)</pre><p>And then the next time, we can pull out the cursor for that offset:</p><pre>cursor_cache_key = &#39;cursors&#39;<br>cursor_cache = memcache.get(cursor_cache_key)<br><strong>if</strong> cursor_cache:<br>    cursor_cache = json.loads(cursor_cache)<br>    offset_key = str(self.offset)<br>    <strong>if</strong> offset_key <strong>in</strong> cursor_cache:<br>        cursor_cache = cursor_cache[offset_key]<br>    <strong>else</strong>:<br>        logging.info(&quot;<strong>%</strong>s not in <strong>%</strong>s&quot; %(offset_key, cursor_cache))<br>        cursor_cache = None</pre><pre><strong>if</strong> cursor_cache:<br>    logging.info(&quot;found cursor cache string <strong>%</strong>s &quot; % cursor_cache)</pre><pre>    <em># construct the sort options</em><br>    search_query = search.Query(<br>        query_string=&#39;&#39;,<br>        options=search.QueryOptions(<br>            limit=self.limit,<br>            sort_options=self.sort_opts,<br>            cursor=search.Cursor(per_result=False, web_safe_string=cursor_cache),<br>            ids_only=False,<br>        )<br>    )<br>    <strong>return</strong> self.render_search_doc(self.index.search(search_query))</pre><p>A next step would be to find the nearest cursor offset, and start from there. But that would be another blog post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4889f5ca1570" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Christmas Lights from Garbage]]></title>
            <link>https://medium.com/@femion/christmas-lights-from-garbage-761d1300e4d?source=rss-4a068a25ba38------2</link>
            <guid isPermaLink="false">https://medium.com/p/761d1300e4d</guid>
            <category><![CDATA[christmas]]></category>
            <category><![CDATA[electronics]]></category>
            <category><![CDATA[electronics-recycling]]></category>
            <dc:creator><![CDATA[Catherine Holloway]]></dc:creator>
            <pubDate>Thu, 14 Dec 2017 23:22:15 GMT</pubDate>
            <atom:updated>2017-12-14T23:22:15.491Z</atom:updated>
            <content:encoded><![CDATA[<p>I have a dilemma: I don’t want to buy stuff for holidays, but I also don’t want to be the only house on my street without Christmas lights. So I made myself some Christmas lights from:</p><ul><li>the leftover <a href="https://www.amazon.com/econoLED-Flexible-Multi-colors-Non-waterproof-Changing/dp/B006LW2NJM">5050 RGB LEDs</a> from my <a href="https://twitter.com/femion/status/903655137230585856">last PC build</a></li><li>the 12 V DC power supply from my old wifi router</li><li>the leftover canvas from making a bike bag</li><li>a leftover dowel rod from making a bookcase</li></ul><p>I made a model of an individual LED strip in Inkscape and experimented with a few designs. The one I ultimately chose was these snowflakes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/0*FfR-8iE7iqPGkinO.png" /></figure><p>I chose this design because it had relatively few angles, which meant I could free-hand layout the LEDs without needing to project the design onto the fabric:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/0*UFcr8zqrodceup7t.jpg" /></figure><p>I soldered the 12V and Blue Grounds on each snowflake, and then hot-glued some of the longer wires down to the fabric:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*LqyGo7iTB4V8INpp.jpg" /></figure><p>This is the end result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*DuD4OJadWmhwe92n.jpg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=761d1300e4d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is it better to bake cookies in a toaster oven?]]></title>
            <link>https://code.likeagirl.io/is-it-better-to-bake-cookies-in-a-toaster-oven-d01f363a226?source=rss-4a068a25ba38------2</link>
            <guid isPermaLink="false">https://medium.com/p/d01f363a226</guid>
            <category><![CDATA[internet-of-things]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[home-automation]]></category>
            <category><![CDATA[codelikeagirl]]></category>
            <dc:creator><![CDATA[Catherine Holloway]]></dc:creator>
            <pubDate>Sun, 29 Oct 2017 12:40:02 GMT</pubDate>
            <atom:updated>2017-10-29T19:22:44.745Z</atom:updated>
            <content:encoded><![CDATA[<p>My husband and I disagree about whether it’s more energy efficient to use the toaster oven or regular oven for baking. He believes the toaster oven consumes less energy, since the internal volume is much smaller. I believe the oven consumes less because it is better insulated.</p><p>I did some back-of-the-envelope calculations to see if there was an obvious conclusion. I estimate that the total power consumed is the work needed to heat up the volume of air inside the oven to the desired temperature, plus the work lost to heat transfer out of the door. It’s also possible that the heat is lost through the other sides, but I didn’t take that into account. From the ideal gas law, the work to heat up the air inside the oven is:</p><p><em>W</em>=<em>DmVR</em>△<em>T</em>W</p><p>Where <em>Dm</em> is the molar density of air, <em>V</em> is the volume, <em>R</em> is the ideal gas constant, and △<em>T</em> is the temperature change.</p><p>The heat lost through the oven door is:</p><p><em>Q</em>=<em>kA</em>△<em>Tt</em></p><p>Where <em>k</em> is the heat transfer coefficient, <em>A</em> is the area of the door, and <em>t</em>t is the time that the oven is on.</p><p>Since both ovens have the same depth, the ratio of the ovens’ volume, 2.8, is the same for the door area. Some mechanical engineers estimate that the <a href="http://www.esss.com.br/events/ansys2014/colombia/pdf/02_1540.pdf"><em>k</em> of double-paned oven doors is ~3</a>, whereas the toaster oven’s single pane of glass is 5.8. The ratio of these coefficients almost exactly cancels out the difference in volume. Because the heat is constantly being leaked out of the ovens, the work due to lost heat is nearly an order of magnitude larger than work required to heat up the oven, so this contribution can be mostly ignored. Since we don’t exactly know <em>k</em> for both ovens, we’re going to need to get <em>experimental</em>.</p><p>I bought an <a href="https://www.amazon.com/Aeon-Labs-AEDSB09104ZWUS-Aeotec-Monitor/dp/B00DIBSKFU/">Aeotek Smart Energy Meter</a> (currently on Amazon for 32 USD) and an <a href="https://www.amazon.com/Aeotec-Z-Stick-Z-Wave-create-gateway/dp/B00X0AWA6E/">Aeotek Z-stick</a> (currently on Amazon for 45 USD) [1]. The Z-Stick is compatible with <a href="http://www.openzwave.com/">open-zwave</a> which has a <a href="https://github.com/OpenZWave/python-openzwave">python interface</a>.</p><p>My code to grab the power data on linux is:</p><pre><strong>import</strong> <strong>time</strong><br><strong>from</strong> <strong>openzwave.option</strong> <strong>import</strong> ZWaveOption<br><strong>from</strong> <strong>libopenzwave</strong> <strong>import</strong> PyManager<br><strong>import</strong> <strong>csv</strong><br><strong>from</strong> <strong>matplotlib</strong> <strong>import</strong> pyplot</pre><pre>device=&quot;/dev/ttyUSB0&quot;<br>options = ZWaveOption(device, config_path=&quot;/etc/openzwave/&quot;, user_path=&quot;.&quot;, cmd_line=&quot;&quot;)<br>options.set_console_output(False)<br>options.lock()<br></pre><pre><strong>class</strong> <strong>PowerMeter</strong>(PyManager):<br>    <strong>def</strong> __init__(self):<br>        super(PowerMeter, self).__init__()<br>        self.create()<br>        self.addWatcher(self.callback)<br>        time.sleep(1.0)<br>        self.addDriver(device)<br>        self.meter_values = []<br>        self.start_time = None<br>        self.units = None<br>        self.value_id = None</pre><pre>    <strong>def</strong> get_meter_values(self, num_seconds):<br>        self.start_time = time.time()<br>        <strong>while</strong> time.time() - self.start_time &lt; num_seconds:<br>            time.sleep(0.10)<br>            <strong>if</strong> self.value_id:<br>                <strong>assert</strong> self.refreshValue(self.value_id)</pre><pre>    <strong>def</strong> callback(self, zwargs):<br>        <em># get measurement value from the first message tagged with the sensor we want</em><br>        <strong>if</strong> &quot;valueId&quot; <strong>in</strong> zwargs:<br>            <strong>if</strong> zwargs[&quot;valueId&quot;][&quot;commandClass&quot;] == &quot;COMMAND_CLASS_METER&quot;:<br>                <strong>if</strong> zwargs[&quot;valueId&quot;][&quot;label&quot;] == &quot;Power&quot; <strong>and</strong> \<br>                                zwargs[&quot;valueId&quot;][&quot;instance&quot;] == 1 \<br>                        <strong>and</strong> self.start_time <strong>is</strong> <strong>not</strong> None:<br>                    self.value_id = zwargs[&quot;valueId&quot;][&quot;id&quot;]<br>                    self.units = zwargs[&quot;valueId&quot;][&quot;units&quot;]<br>                    self.meter_values.append((time.time() - self.start_time,<br>                                              zwargs[&quot;valueId&quot;][&quot;value&quot;]))<br>                    <strong>print</strong>(&quot;Power&quot;, zwargs[&quot;valueId&quot;][&quot;value&quot;])<br></pre><pre>manager = PowerMeter()<br><em># collect data for an hour</em><br>manager.get_meter_values(60*60)<br><em># add to a csv</em><br><strong>with</strong> open(&#39;meter_values_<strong>%</strong>s.csv&#39; % manager.start_time, &#39;wb&#39;) <strong>as</strong> csvfile:<br>    spamwriter = csv.writer(csvfile, delimiter=&#39;,&#39;, quoting=csv.QUOTE_MINIMAL)<br>    spamwriter.writerow([&#39;time (s)&#39;, &#39;meter (<strong>%</strong>s)&#39; % manager.units])<br>    <strong>for</strong> row <strong>in</strong> manager.meter_values:<br>        spamwriter.writerow(row)</pre><pre>fig, ax = pyplot.subplots()<br>ax.plot([point[0]/60.0 <strong>for</strong> point <strong>in</strong> manager.meter_values],<br>            [point[1] <strong>for</strong> point <strong>in</strong> manager.meter_values])<br>ax.set_xlabel(&quot;Time (minutes)&quot;)<br>ax.set_ylabel(&quot;Meter Value (<strong>%</strong>s)&quot; % manager.units)<br>fig.savefig(&quot;power_meter_<strong>%</strong>s.png&quot; % manager.start_time)</pre><p>I believe that <em>instance 1</em> is the power on the first probe, which is attached to the <em>hot</em> wire of my house’s main power. Since probe 2 is attached to the <em>neutral</em> wire, I believe it’s possible to cancel out most of the noise by subtracting the power on instance 2 from the power on instance 1. I have no idea how these map to European/Australian three phase systems.</p><p>With the script running, I collected three sets of data: one while the toaster cooked a sheet of cookies, one while the oven cooked a sheet of cookies, and one with neither oven running, just the house lights, routers, and refridgerator. The data, from the start of pre-heating to when the cookies came out, looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*rM8VlHNgteT635pk.png" /></figure><p>The toaster took longer to pre-heat, so it had a longer data collection time. It looks like both ovens and the refridgerator (in the base usage) are driven by square forcing functions that turn off when a desired temperature is reached. The oven’s forcing function is a bit more sophisticated than the toaster; it looks like it can heat at two different wattage levels. I think the long period of the oven been off while cooking is proof that the oven does have a lower heat transfer coefficient than the toaster oven.</p><p>I can integrate the data I collected using scipy’s integrate and numpy’s interpolate functions:</p><pre><strong>from</strong> <strong>scipy</strong> <strong>import</strong> integrate<br><strong>from</strong> <strong>numpy</strong> <strong>import</strong> interp</pre><pre>result = integrate.quad(<strong>lambda</strong> x: interp(x, data_array[0], data_array[1]),<br>                        min(data_array[0]), max(data_array[0]))[0]</pre><p>I also subtract off the base usage in each case. After integrating, I estimate that the toaster uses 0.45 kWh to bake a single sheet of cookies, and the oven uses 0.70 kWh.</p><p>The toaster is more efficient at baking a single sheet of cookies, so I’d conclude that the heat transfer coefficient of the toaster is not as bad as expected. However, the oven can handle two sheets at once, and is faster. If you want to shave 8 minutes off of your cook time, it’s only an extra 0.15 kWh, which in Florida costs two cents. However, the oven has an advantage over the toaster in that it can cook more than a single sheet at a time, and then the energy cost per cookie favors the oven.</p><p>So depending on the situation, we’re both right.</p><p>1: It is my personal opinion that Z-Wave compatible devices are 2–3 times more expensive than they should be, given the underlying hardware. I think this is because Z-Wave is not open source, so development takes longer and costs more. I would not invest in a Z-Wave system now. It would be nice to be able to turn off my overhead light from a smartphone app so that I don’t have to get out of bed, but just putting a long piece of twine on the pull chain seems to be an adequate solution.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d01f363a226" width="1" height="1" alt=""><hr><p><a href="https://code.likeagirl.io/is-it-better-to-bake-cookies-in-a-toaster-oven-d01f363a226">Is it better to bake cookies in a toaster oven?</a> was originally published in <a href="https://code.likeagirl.io/">Code Like A Girl</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Emoji data markers in matplotlib]]></title>
            <link>https://medium.com/@femion/emoji-data-markers-in-matplotlib-7020c9910748?source=rss-4a068a25ba38------2</link>
            <guid isPermaLink="false">https://medium.com/p/7020c9910748</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[matplotlib]]></category>
            <dc:creator><![CDATA[Catherine Holloway]]></dc:creator>
            <pubDate>Tue, 24 Oct 2017 21:47:49 GMT</pubDate>
            <atom:updated>2017-10-24T21:47:49.186Z</atom:updated>
            <content:encoded><![CDATA[<p>Using matplotlib’s <strong>axes.transData</strong> and <strong>get_sample_data</strong>, it’s possible to replace data markers with images, such as the poo emoji:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*zc2RZXnRfxVEfdNi.png" /><figcaption>it’s a wave of happy shits</figcaption></figure><p>This is fun and silly, but it’s also important for accessibility for people with colorblindness or with shitty printers, like me.</p><p><strong>axes.transData</strong> can transform x/y coordinates into the plot’s pixel location on the plot output. In order to then convert the pixel location to the figure’s 0.0–1.0 scale, divide by these locations by the size of the figure’s bounding box.</p><pre><strong>from</strong> <strong>os.path</strong> <strong>import</strong> join, dirname, abspath<br><strong>from</strong> <strong>matplotlib</strong> <strong>import</strong> pyplot<br><strong>from</strong> <strong>matplotlib.cbook</strong> <strong>import</strong> get_sample_data<br><strong>from</strong> <strong>numpy</strong> <strong>import</strong> linspace<br><strong>from</strong> <strong>numpy.core.umath</strong> <strong>import</strong> pi<br><strong>from</strong> <strong>numpy.ma</strong> <strong>import</strong> sin</pre><pre><em># poo-mark came from emojipedia:</em><br><em># https://emojipedia-us.s3.amazonaws.com/thumbs/120/apple/96/pile-of-poo_1f4a9.png</em><br>poo_img = pyplot.imread(get_sample_data(join(dirname(abspath(__file__)), &quot;poo-mark.png&quot;)))</pre><pre>x = linspace(0, 2*pi, num=10)<br>y = sin(x)</pre><pre>fig, ax = pyplot.subplots()<br>plot = ax.plot(x, y, linestyle=&quot;-&quot;)</pre><pre>ax_width = ax.get_window_extent().width<br>fig_width = fig.get_window_extent().width<br>fig_height = fig.get_window_extent().height<br>poo_size = ax_width/(fig_width*len(x))<br>poo_axs = [None <strong>for</strong> i <strong>in</strong> range(len(x))]<br><strong>for</strong> i <strong>in</strong> range(len(x)):<br>    loc = ax.transData.transform((x[i], y[i]))<br>    poo_axs[i] = fig.add_axes([loc[0]/fig_width-poo_size/2, loc[1]/fig_height-poo_size/2,<br>                               poo_size, poo_size], anchor=&#39;C&#39;)<br>    poo_axs[i].imshow(poo_img)<br>    poo_axs[i].axis(&quot;off&quot;)<br>fig.savefig(&quot;poo_plot.png&quot;)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7020c9910748" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mr Farwell, by highlighting the scoffaws you make cycling more dangerous for law-abiding bike…]]></title>
            <link>https://medium.com/@femion/mr-farrell-by-highlighting-the-scoffaws-you-make-cycling-more-dangerous-for-law-abiding-bike-8fc01808bce0?source=rss-4a068a25ba38------2</link>
            <guid isPermaLink="false">https://medium.com/p/8fc01808bce0</guid>
            <category><![CDATA[cycling]]></category>
            <dc:creator><![CDATA[Catherine Holloway]]></dc:creator>
            <pubDate>Fri, 25 Aug 2017 13:46:46 GMT</pubDate>
            <atom:updated>2017-08-25T13:49:05.383Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mr Farwell, by highlighting the scoffaws you make cycling more dangerous for law-abiding bike riders</h3><p>I know I’m late to the party, but I’d like to make a counter-intuitive argument.</p><p>I commuted to work by bike for the 6 years I was in Kitchener between several different apartments and jobs. My commutes often took me on roads with no biking infrastructure. So I studied vehicular cycling and the collision stats and did everything in my power to reduce my risk of an accident, which in most cases means following the law.</p><p>However, every couple of months I would have an incident where I was endangered through no fault of my own. This would happen when a driver did not want to share the road with me, or was otherwise frustrated by a cyclist in their lane, and wanted to “teach me a lesson” with their car. This meant tailgating me, calling me the c-word or the b-word, passing halfway in my lane, or passing me lawfully and abruptly braking in front of me.</p><p>Though I can’t know for sure where they got this impression that they knew the rules of the road better than me, or that they were more deserving of the road than me, but I can’t help feel that the image of all cyclists being poor, drunkard, incapable human beings is helped every time they hear an opinion columnist talk about their negative encounters with cyclists.</p><p>Since leaving KW, I’ve also biked to work in Southern California (where the car is king) and Florida (home of the infamous petty-criminal Florida Man), and these places are much safer, despite having far worse cycling scoffaw behaviors. The difference is that the cyclists are usually committing these bad behaviors while wearing full lycra kit and riding a several-thousand dollar bike.</p><p>Funny how the same behavior is assumed to be competent based on the wealth of the rider…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8fc01808bce0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>