Archive

Tag Archives: Python

PyCon 2016 just ended! I had a far more relaxing time this year, since I didn’t have to give a talk.

Highlights:

Ned gave an amazing machete-mode debugging talk this year.

machete

I’ve seen a couple of his talks over the past years, and this one is my favorite.

pyladies

I bought a super cute PyLadies Seattle tshirt, featuring plaid hair!

motorcycle

Lars gave an incredible keynote! It was also great to see him again. ūüėÄ

excited

I’m not sure if it was the talks or the general atmosphere, but I felt excited/inspired about software development in a way that I hadn’t been for a while.

I also got to see a lot of friends I don’t usually get to see, which was great.

Until next year, PyCon!

So I use Vagrant/virtual machines in my daily development and with that comes annoyances that my host-machine-only friends don’t experience.

I have my Flask app set up to detect changes and reload whenever static files change.

However, Werkzeug updated and my Flask’s auto reload stopped working.

Turns out it was using inotify and since I’m on a virtual machine, (using the /vagrant/ directory), inotify can’t detect changes on a mounted filesystem.

The solution was to use stat.

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

if __name__ == "__main__":
    app.run(extra_files=my_static_files, reloader_type='stat')

Of course, there’s some disadvantages to stat, it might technically be a watchdog issue, and Werkzeug technically updated a long time ago.

Anyhoo, here’s my quick and dirty solution. I’m posting it ’cause it was hard to search for.

I want to re-compile static assets (SASS to CSS and Coffeescript to JS) whenever there’s change in my Flask app.

I also want to optionally set a flag to toggle whether that compilation happens or not.

I’m using Flask-Assets, and it only seems to trigger the compilation whenever the jinja template with the corresponding assets extension is loaded.

For example, js_all.js will only be created whenever the jinja template with the following is loaded.

{% assets "js_all" %}
    <script type="text/javascript" src="{{ ASSET_URL }}"></script>
{% endassets %}

Bizarrely, triggering the build manually was rather hard to search for.

Here’s my solution.

****Update****
You can use bundle.build() instead of asserts[‘js_all’].urls()

if reload_flag:
  assets = Environment(app)

  # Don't cache otherwise it won't build every time
  assets.cache = False
  assets.manifest = False

  js = Bundle('jquery.js', 'base.js', 'widgets.js',
              filters='jsmin', output='gen/packed.js')
  assets.register('js_all', js)

  js.build()

****

You can build bundles manually with .urls().

if reload_flag:
  assets = Environment(app)

  js = Bundle('jquery.js', 'base.js', 'widgets.js',
              filters='jsmin', output='gen/packed.js')
  assets.register('js_all', js)

  assets['js_all'].urls()

In the template:

<script type="text/javascript" src="/static/gen/js_all.js"></script>

It’s a lot less robust than using assets to automatically inject the resource url, but for me, I don’t want compilation to happen on production (I don’t even want the compilation tools on the production machines).

Hope this helps folks.
Let me know if there’s a better answer.

I recently switched from working in Python to working in Ruby. The behavior of Ruby’s keyword arguments gave me a shock. You have to explicitly decide between positional and keyword arguments for methods in Ruby. With a method with keyword arguments, Ruby won’t interpret your parameters as positional if you don’t supply the parameter name. It will instead throw an argument error.

For example, in Python (examples from Stackoverflow):

def fn(a, b, c = 1):
    return a * b + c

print fn(1, 2)                # returns 3, positional and default.
print fn(1, 2, 3)             # returns 5, positional.
print fn(c = 5, b = 2, a = 2) # returns 9, named.
print fn(b = 2, a = 2)        # returns 5, named and default.
print fn(5, c = 2, b = 1)     # returns 7, positional and named.
print fn(8, b = 0)            # returns 1, positional, named and default.

In Ruby, for method with positional arguments:

def fn(a, b, c = 1)
    a * b + c
end

puts fn(1, 2)                # returns 3
puts fn(1, 2, 3)             # returns 5
puts fn(c: 5, b: 2, a: 2)    # ArgumentError, Wrong Number of Arguments
puts fn(b: 2, a: 2)          # ArgumentError, Wrong Number of Arguments
puts fn(5, c: 2, b: 1)       # ArgumentError, Wrong Number of Arguments
puts fn(8, b: 0)             # ArgumentError, Wrong Number of Arguments

For methods with keyword arguments:

def fn(a:, b:, c: 1)
    a * b + c
end

puts fn(1, 2)                # ArgumentError, Missing keywords
puts fn(1, 2, 3)             # ArgumentError, Missing keywords
puts fn(c: 5, b: 2, a: 2)    # returns 9
puts fn(b: 2, a: 2)          # returns 5
puts fn(5, c: 2, b: 1)       # ArgumentError, Missing keywords
puts fn(8, b: 0)             # ArgumentError, Missing keywords

Here’s a neat article on Ruby 2 arguments from thoughtbot.

Here’s a short FAQ on parameters vs arguments from Python 3.

I just got back from Nashville and I gotta say, PyTennesee was AWESOME!

Lars

My first day started with Lars giving amazing electric bassoon performances accompanying his talk ‘The Well Tempered API’.

Ed

The day ended with Ed Finkler giving a really poignant talk on mental health. He mentioned taking a Mental Health First Aid course to help the people around you, which I’m definitely gonna take.

Chris

Day two started with Chris Fonnesbeck giving a talk on the importance of statistics. It made me feel like I didn’t take enough math in school and ought to catch up. Time to crack open some books!

I also gave my talk ‘3D Print Anything with the Blender API’ and hopefully inspired people to give Blender a try. As I’ve mentioned, all the code from my talk (like creating glasses and lampshades) are on my GitHub.

‚̧ BlenderOverall, I had a great time at the conference. Also, I felt like I got the Nashville experience, from all the country music at the airport to the famous hot chicken at Emma’s after party.Special thanks to Carrol, May, and Bono for shuttling me everywhere, and to all the organizers of the conferences.

Recently I read an inspirational post on how to create stereographic lampshades. I noticed the author created the model in MATLAB and then rendered the lampshades in Blender. I feel like Blender on its own provides all the features necessary to create stereographic lampshades, so I set out to write a script to do just that.

rendered lampshade

My script is [here] on Github.

Check it out!

I created a SVG pattern modified from a public domain snowflake on Pixabay.

snow pattern

Let it snow!

Then I imported the SVG into Blender and ran my script. My script converted the SVG into a mesh and transformed each vertex according to the post’s instructions.

I admit I cheated a little. In the original post, the input to the lampshade creation was a raster image. I instead jumped straight into vector images with SVGs. Since Blender can manipulate SVGs¬†easily and there’re good tools¬†on converting raster images to SVGs, I felt no need to reinvent the wheel.

There are two things that¬†were non-obvious to me initially for computing¬†the new vertices’ coordinates. First, all angles were supposed to be in radians. Luckily the default math functions like sin() and cos() ¬†operate in radians, so that wasn’t a big trip-up. Second was that the default arctangent function atan() only returned a compressed¬†range which resulted in a super collapsed/deformed hemispherical blob. I needed to use atan2() to get the full range. A fuller¬†explanation can be found on¬†Wikipedia.

After transforming each vertex the resulting mesh is a non-manifold¬†surface. It’s basically a sheet with infinite thinness, which isn’t 3D printable.

My first instinct was to use Blender’s solidify modifier to turn the surface into a solid, but it didn’t behave like I expected. I ended up choosing extrude and scaling the extruded faces. Since I scaled proportionally to the thickness of the extrusion, I hope that the image projected by my lampshade won’t be distorted.

Since I don’t own a 3D printer, I sent my model to a service for printing. I’ll update with my results (hopefully it comes before holiday time!)

To print your own, you need an SVG (you can convert raster images to SVGs using Inkscape). I’ve provided the snowflake pattern as well as the final STL I used in the Github repository.

imported SVG

After you import the SVG into Blender, open up my script in the the Blender Text Editor.

hit Run Script!

Select the SVG and hit Run Script.

final object

You might need to rescale to the desired print size.

Have fun! Feedback welcome!

Click for Update

Success!