Skip to main content

Posts

Showing posts with the label python

Open Source Paillier Libraries

The Confidential Computing team at Data61 has been looking at novel methods of using privacy preserving computation - with the lofty long term goal of increasing users' privacy while still allowing modern analytical insights. One of the principals we've been relying on is partially homomorphic encryption - the ability to carry out some basic mathematical operations on encrypted data, usually this property is either addition or multiplication. Take a quick look at my previous post on  Homomorphic Encryption . My team has looked at multiple homomorphic systems and settled on using the Paillier Crypto system for some of our confidential computing projects. The homomorphic properties of the Paillier Crypto system are: An encrypted number can be multiplied by a non encrypted scalar. Encrypted numbers can be added together. Encrypted numbers can be added to non encrypted scalars. Everything else (such as multiplying encrypted numbers together) is either extremely difficul...

Single Server Web App Deployment

Deploying small web applications can take up more time than creating the application itself, for this reason I've put together this small guide to document how I go about deploying applications. I've used this method for things like small business sites, demo sites and application prototypes. Although we will go through a Python Flask application the same method would apply to other micro web apps. The final running application will have a few moving parts, here is how it will handle two incoming requests: Our final implementation will comprise three Docker containers: - Our frontend reverse proxy server - nginx - Our WSGI server Gunicorn and application server Flask - An example ancillary service - a redis cache To follow along grab the code from https://github.com/hardbyte/python-app-deploy In this post we’ll create a small standalone flask application that uses redis for a cache. The same deployment method works for applications that require services like mem...

Why learn programming

Why would you set off to study the art of computer programming? Programming certainly seems like the most complex way to interface with today’s increasingly complex machines. Programming, much like knitting , isn't for everybody; you have to have a curious mind and not be afraid of getting into the nitty gritty. Learning to program is also not something to rush into, it will take a significant investment of time . But here are my top few reasons when asked: Programming is fun! As with all creative outlets you experience the sheer joy of making things. You start with nothing but an idea and only your imagination limits what you can create. Programming is a useful tool! To better be able to analyse raw data, automate boring repetitive tasks, or create interactive websites. Programming teaches a new way of thinking . The process of creating programs is quite different from most things we humans do. Gaining a skill that changes how you think about other things. Gain a deeper ...

Learning in an online world

Since I started at Dynamic Controls about two years ago, engineers have done free online courses in machine learning, artificial intelligence, cryptography and digital electronics. These services are just starting to build momentum, have a go at many computer science topics at coursera.org or udacity.com , for something completely different learn a language while transcribing the web at duolingo.com . The business also promotes internal classes, from topics related to each department like Finance 101 to classes run by enthusiasts in a particular domain like the Chinese language or Programming in Python. I'm about to embark on teaching the "Introduction to Programming" course for the third time. It is so rewarding to see many of my previous students use Python to automate some repetitive part of their job. Everyone has been happy using Python 3 as their first programming language. We live in a wonderful world with a rich culture of free learning and education.

Codebreaking

The first challenge question for my cryptography course with  udacity.com  was to decrypt two intercepted messages encoded using a  One Time Pad . The messages were encrypted using the same key, which is a big operator error for sending secure messages with a one time pad. Despite having considerable computer resources available it took me a full afternoon before I obtained the full key. I ended up using a very tedious manual process which pretty much involved assuming common words would present. I ended up trying a few hundred words before finding an invalid assumption I'd made. Back on the right track I tried words surrounded by spaces starting at all possible locations. By assuming a word appears in a message you get a section of bits that could potentially be the key aligned with that word. Using this key on the other message usually gives garbage - except for the few cases where it output something resembling English, meaning you "might"...

Porting labjack's Python 2 library to Python 3

I'm teaching an introduction to programming with Python 3 at work, 12 weeks with a 2 hour seminar once a week and homework. Internally one of the biggest uses of Python is in hardware interaction - especially when it comes to automated testing. We communicate with embedded devices running elua , labjacks , programmable power supplies, oscilloscopes, Kvaisers and more with Python - primarily using the serial interface and abstracting the hardware with Python. Since most of our existing code uses python2, I figured I should spend an hour looking at porting an existing Python module to python3. The python library we currently use to communicate with Labjack is an in house ctypes wrapper, but Labjack have their own Python library code so I decided to port that to Python3. I only did the bare minimum to get the basic tutorial running but you can see forked code on github . For the most part 2to3 did everything. The modifications I had to make were all because the Labjack opera...

Wikipedia Mining

So I was studying nearest neighbor for my machine learning exam tomorrow and I stumbled across "breadth-first search" and it got me thinking... Okay I've come across it before but never thought of a breadth-first search of wikipedia as a means of finding the nearest neighbour... I thought about all the internal links that wikipedia keeps and how easy it would be to use each page as a graph node then do a bit of a breadth-first search by visiting all those child nodes. Then I thought maybe the links from the child nodes would be interesting so I created a link counter to keep track of how often a link shows up across all children of a page. The way I implemented it wasn't using the wikipedia api or anything - just scraping the data off the web. This means it kinda downloads a few thousand wikipedia pages for a single query... but still it was interesting! If I query " Machine learning " the closest match is not " Artificial intelligence " as you...

Python and Gmail with IMAP

Today I had to automatically access my Gmail inbox from Python. I needed the ability to get an unread email count, the subjects of those unread emails and then download them. I found a Gmail.py library on sourceforge, but it actually opened the normal gmail webpage and site scraped the info. I wanted something much faster, luckily gmail can now be accessed with both pop and imap. After a tiny amount of research I decided imap was the better albiet slightly more difficult protocol. Enabling imap in gmail is straight forward, it was under labs. The address for gmail's imap server is: imap.gmail.com:993 Python has a library module called imaplib , we will make heavy use of that to access our emails. I'm going to assume that we have already defined two globals - username and password. To connect and login to the gmail server and select the inbox we can do: import imaplib imap_server = imaplib . IMAP4_SSL ( "imap.gmail.com" , 993 ) imap_server . login ( use...

Publicly query facebook using Python

In my cosc lab today a few students were asking about doing something "real" and "cool" with Python, something that isn't easy in excel. After a bit of a think I came to the conclusion that getting data from the internet is a "real" enough problem. As for "cool", since most people seem to have facebook open in the background during labs I thought getting some real live data off facebook could be interesting. First a disclaimer or two. Don't just run random code without reading it and satisfying yourself that its not trying to delete your operating system or do anything sinister! I don't make the test or the assignment. This is not at all related, except for the fact it is using Python (okay it uses a for loop to iterate over a list, if nothing else in this post is of interest to you, learn how to do that!) So if anyone is still reading, let me introduce the problem, then look into how we can solve it. We will take a quick look at f...

SciPy-Simulator

For the last few weeks I have been working on a Simulink / Labview / Ptolemy II like program for modelling... all sorts of stuff!! I am interested in modeling with different systems of computation, and of course some engineering problems, mechanical and electrical control etc. Ptolemey II is an open source java based system which a whole lot of people from Berkley have been working on for a number of years - I am not trying to match what they have - or get anywhere near the breadth that the commercial products Simulink and Labview have. But I do think something useful is very achievable - and of course leveraging what I can from Ptolemy II and basing mine on Python - heavily using SciPy , NumPy and MatPlotLib . So far I have been working on the semantics - in essence creating a new language for defining models by using blocks (or Actors) that carry out a very specific function. An example actor might be a Ramp Source or a Sin Function . Each of these actors run in their own thre...

Animations with matplotlib

For some reason this wasn't overly clear in the documentation, but a simple way to make an animation using the default backend in matplotlib is something like this: from numpy import random , array , arange import matplotlib.pyplot as plt plt . ion () print "starting" x = arange ( 100 ) y = 2 * random . rand ( 100 ) line , = plt . plot ( x , y , 'd-' ) for i in arange ( 1 , 200 ): y = y + random . rand ( 100 ) - 0.500000 line . set_data ( x , y ) ax = line . get_axes () ax . relim () ax . autoscale_view () plt . draw () # redraw the canvas plt . show ()

Kiwi Pycon 2009 - Basic Computer Vision in Python

Well I have given my first ever conference talk! Wasn't any where near as scary as I'd feared and all my live python demos using the webcam worked fine. My slides have been uploaded on slideshare here . Heaps of random snippets from the weekend made it onto twitter . The conference had two main tracks, with delegates enjoying presentations on project management, science and maths, games and animation, and web development. There were also more interactive sessions with conference attendees participating in short presentations or open discussions on a specific theme. All in all I had a great weekend at the conference, learnt heaps and made some new contacts in the Python community. The maths exam the following day wasn't to bad either. Now the next challenge - concurrent systems modelling for scipy.

Greenscreen

Something used heaps in the film industry is the " Greenscree n" I thought I would take a quick look at how to make a greenscreen that works fast enough to run on a live webcam stream. And infact one that works with any coloured background. It has many many limitations, but was a fun experiment! To run this example you will need OpenCV with the SWIG Python bindings installed. You can get this code from my SVN repository here . Firstly the background I started with: Adding an object to the scene, and carrying out back ground subtraction: So anyhow the code: #!/usr/bin/env python from VideoCapturePlayer import VideoCapturePlayer as VCP from opencv import cv def threshold_image ( image , n = []): """Record the first 5 images to get a background, then diff current frame with the last saved frame. """ if len ( n ) < 5 : # n[4] will be our background # First capture a few images ...

Decoration to the rescue!

import numpy as np from scipy import signal from opencv import adaptors class scipyFromOpenCV ( object ): """This decorator can be used to wrap a function that takes and returns a numpy array into one that takes and retuns an opencv CvMat. """ def __init__ ( self , f ): self . f = f def __call__ ( self , image ): # Convert CvMat to ndarray np_image = adaptors . Ipl2NumPy ( image ) # Call the original function np_image_filtered = self . f ( np_image ) # Convert back to CvMat return adaptors . NumPy2Ipl ( np_image_filtered ) @scipyFromOpenCV def slowGaussianBlur ( matrix ): """Manual gaussian blur - Very very very slow!""" filterSize = 3 filt = gauss_kern ( filterSize ) r = signal . convolve ( matrix [:,:, 0 ], filt , 'same' ) g = signal . convolve ( matrix [:,:, 1 ], filt ...

Instant Messaging, Threading and Sockets

So we were given an assignment for software today. It's going to be used to teach us promala and spin and good multi-threaded software practices. The overall goal is to make a simple GUI based multi-user instant messager system in C++. I haven't used allot of concurrency before so I thought I would investigate by trying some stuff out in python. Also I haven't used sockets directly before - so wanted to have a look at them. Firstly taking a read of the Socket Programming HOWTO guide - there is plenty of information there. And also handy is the Socket documentation for python. For now I just want a echoing server that can service multiple clients at once. So the server will be the difficult part - might as well dive in there! Firstly creating a socket and echoing any data it recieves is pretty easy with this loop: while True:            data = self.conn.recv(1024)            i...