Skip to content

Instantly share code, notes, and snippets.

Common string operations

Checks

List in-place operations

Common sequence operations with examples

len

:::python
len('abc')  # -> 3

len([1, 5, 2, 3])  # -> 4
@Nagasaki45
Nagasaki45 / nuclear.py
Created May 3, 2014 18:58
Nuclear GUI for the Simcity project
'''
This program controls the state of the waterpump and
LED's of the nuclear power station.
If the pump stops working a countdown of 10 seconds starts
ticking and then does 2 things:
1) turning on red lights instead of blue lights in the
reactor's core.
2) cutting the power: writing outpin HIGH (on the arduino
of the power system this will set the power out.
import Tkinter as tk
import serial
ANGLE_MIN = 0
ANGLE_MAX = 180
SERVO_MIN = 1
SERVO_MAX = 4
# Assign Arduino's serial port address
# Windows example
@Nagasaki45
Nagasaki45 / block_navigation.js
Created May 13, 2014 11:20
blocking navigation from page script
var block_navigation = function(state) {
if (state) {
window.onbeforeunload = function(e) {
// If we haven't been passed the event get the window.event
e = e || window.event;
var message = 'Any text will block the navigation and display a prompt';
// For IE6-8 and Firefox prior to version 4
if (e) { e.returnValue = message; }
// For Chrome, Safari, IE8+ and Opera 12+
return message;
@Nagasaki45
Nagasaki45 / drop_from_history.js
Created May 13, 2014 11:22
Remove current page from browsing history
$(document).ready(function() {
$("#submit_button").on("click", function() {
window.history.replaceState({}, 'foo page', '/foo');
});
});
import java.util.Map;
import processing.video.Movie;
String MOVIE_FILE = "videofile";
String OUTPUT_DIR = "pos/";
int SEEK_INTERVAL = 4;
String OBJ_NAME = "object_name";
DisposeHandler dh;
@Nagasaki45
Nagasaki45 / validate_attr.py
Last active August 29, 2015 14:05
A function to validate attribute (or attributes) of an instance (or a list of instances) against white or black list of values.
def validate_attr(instance, attr, valid, errors=None, positive=True):
'''Returns a list of errors (strings) for mom objects attribute
validation.
Parameters:
instance: instance or list of instances to validate.
attr: attribute name or list of attributes names as strings.
valid: valid value or list of valid values (invalid values if
positive=False).
errors: an optional list to aggregate the errors into.
@Nagasaki45
Nagasaki45 / forms.py
Created October 31, 2014 22:15
TDD with Python book. p. 221: Better implementation for field validation.
def clean_text(self):
data = self.cleaned_data['text']
if data in [item.text for item in self.instance.list.item_set.all()]:
raise forms.ValidationError(DUPLICATE_ITEM_ERROR)
return data