code:
from tkinter import *

class zoomer(Tk):

    def __init__(self):
        x=100
        y=100
        Tk.__init__(self)
        self.border = 10
        self.size_x = x
        self.size_y = y

        #SIZE
        self.app_sizex = 200
        self.app_sizey = 200
        fontSize=int(x/20)

        self.title("Graphic")
        self.geometry(str(self.app_sizex+10) + "x" + str(self.app_sizey+40))

        #CANVAS + BORDER
        self.canvas = Canvas(self, width = self.app_sizex, height = self.app_sizey, scrollregion=(0,0,x,y))
        self.canvas.grid(row=0, column=0, sticky="nsew")
        self.canvas.create_line(self.border, self.border, self.border, y-self.border)
        self.canvas.create_line(x-self.border, self.border, x-self.border, y-self.border)
        self.canvas.create_line(self.border,   self.border, x-self.border, self.border)
        self.canvas.create_line(self.border, y-self.border, x-self.border, y-self.border)
        self.canvas.create_line(self.border,   self.border, x-self.border, y-self.border)
        text1=self.canvas.create_text(50, 50, fill="white",font=("Purisa", fontSize))
        self.canvas.itemconfig(text1, text="Graphic Text")

        #SCROLLING BARS
        self.vbar=Scrollbar(self,orient=VERTICAL)
        self.vbar.grid(row=0, column=1, sticky="ns")
        self.vbar.config(command=self.canvas.yview)
        self.hbar=Scrollbar(self,orient=HORIZONTAL)
        self.hbar.grid(row=2, column=0, sticky="ew")
        self.hbar.config(command=self.canvas.xview)
        self.canvas.config(xscrollcommand=self.hbar.set, yscrollcommand=self.vbar.set)

        #zoom button
        save_button = Button(self, text = "Zoom")
        save_button["command"] = lambda: self.zoom_in()
        save_button.grid(row=3, column = 0, pady = 5)

    def zoom_in(self):
        #Clean canvas
        self.canvas.delete("all")
        self.size_x = int(self.size_x * 1.1)
        self.size_y = int(self.size_y * 1.1)
        x=self.size_x
        y=self.size_y
        fontSize=int(x/20)
        self.canvas.create_line(self.border, self.border, self.border, y-self.border)
        self.canvas.create_line(x-self.border, self.border, x-self.border, y-self.border)
        self.canvas.create_line(self.border, self.border, x-self.border, self.border)
        self.canvas.create_line(self.border, y-self.border, x-self.border, y-self.border)
        self.canvas.create_line(self.border,   self.border, x-self.border, y-self.border)
        text1=self.canvas.create_text(self.size_x/2, self.size_y/2, fill="white",font=("Purisa", fontSize) )
        self.canvas.itemconfig(text1, text="Graphic Text")
        self.canvas.configure(scrollregion=self.canvas.bbox("all"))

        #SCROLLING BARS
        self.vbar.config(command=self.canvas.yview)
        self.hbar.config(command=self.canvas.xview)
        self.canvas.config(xscrollcommand=self.hbar.set, yscrollcommand=self.vbar.set)

if __name__ == '__main__':
    my_gui=zoomer()
    my_gui.mainloop()

rawDescription: tkinter fixed canvas size

description: Tkinter fixed canvas size


code:
import xlwt

x=1
y=2
z=3

list1=[2.34,4.346,4.234]

book = xlwt.Workbook(encoding="utf-8")

sheet1 = book.add_sheet("Sheet 1")

sheet1.write(0, 0, "Display")
sheet1.write(1, 0, "Dominance")
sheet1.write(2, 0, "Test")

sheet1.write(0, 1, x)
sheet1.write(1, 1, y)
sheet1.write(2, 1, z)

sheet1.write(4, 0, "Stimulus Time")
sheet1.write(4, 1, "Reaction Time")

i=4

for n in list1:
    i = i+1
    sheet1.write(i, 0, n)

book.save("trial.xls")

rawDescription: Opening multiple excel files using Python


code:
with open(fname1) as f1, open(fname2) as f2:
    for line1, line2 in izip(f1, f2):
        ...

rawDescription: using python's 'with' while reading two files simultaneously with izip

description: Using python's 'with' while reading two files simultaneously with izip


code:
import tkinter as tk

root = tk.Tk()

screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()

rawDescription: How to get the screen size in Tkinter?

description: Get the screen size in Tkinter


rawDescription: How to change a tuple into array in Python?

description: Change a tuple into array in Python


code:
def getobj(astr):
    """
    getobj('scipy.stats.stats') returns the associated module
    getobj('scipy.stats.stats.chisquare') returns the associated function
    """
    try:
        return globals()[astr]
    except KeyError:
        try:
            return __import__(astr, fromlist=[''])
        except ImportError:
            modname, _, basename = astr.rpartition('.')
            if modname:
                mod = getobj(modname)
                return getattr(mod, basename)
            else:
                raise

needed_utils = ["firstutil", "secondutil", "fifthutil"]
for util_name in needed_utils:
    globals()[util_name] = getobj('mainapp.utils.{m}'.format(m=util_name))

rawDescription: Python import submodules by string names?


code:
import pyglet

window = pyglet.window.Window()
image = pyglet.image.Texture.create(256,128)
img1 = pyglet.image.load('img1.png')
img2 = pyglet.image.load('img2.png')
image.blit_into(img1,0,0,0)
image.blit_into(img2,128,0,0)
@window.event
def on_draw():
    window.clear()
    image.blit(0,0)

pyglet.app.run()

rawDescription: Pyglet drawing a set of images to a larger one


code:
import numpy as np
def nvisits_before_display(x):
    try:
        return np.where(x > 0)[0].item(0) + 1
    except IndexError:
        return 0

rawDescription: Pandas: groupby and get index of first row matching condition


code:
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt

NA = mpatches.Patch(color='blue', label='North America')
EU = mpatches.Patch(color='green', label='Europe')
AP = mpatches.Patch(color='red', label='Asia/Pacific')
SA = mpatches.Patch(color='yellow', label='South America')
plt.legend(handles=[NA,EU,AP,SA], loc=2)

plt.show()

rawDescription: Custom legend in Pandas bar plot (matplotlib)


code:
class MyCommand(sublime_plugin.TextCommand):
    def __init__(self, view):
        self.view = view # EDIT
        self.thevariable = 'YOUR VALUE'

rawDescription: Sublime Editor Plugin remember variable

description: Sublime Editor Plugin remember variable


code:
import geopandas as gpd

geofile_in = 'UTMgrid.shp'
geofile_out = 'LATLONgrid.shp'

g = gpd.read_file(geofile_in)

originalcrs = {u'units': u'm', u'ellps': u'WGS84', u'datum': u'WGS84', u'proj': u'utm', u'zone': 31}
targetcrs = {u'ellps': u'WGS84', u'datum': u'WGS84', u'proj': u'longlat'}

# Set the original crs (UTM Zone 31 N)
g.crs = originalcrs
# Transform the Grid to the target crs (Lon, Lat)
g.to_crs(crs=targetcrs, inplace=True)
# Save to .shp file
g.to_file(geofile_out)

rawDescription: python - create a shapefile equally spaced spatial grid

description: Python - create a shapefile equally spaced spatial grid


code:
mapIntent = droid.makeIntent("android.intent.action.PACKAGE_FIRST_LAUNCH", str(droid.viewMap(dic["latitude"]+","+dic["longitude"])))
droid.startActivityIntent(mapIntent, True)

rawDescription: Show viewMap until user close it

description: Show viewMap until user close it


rawDescription: Find indices of N concurrences in arrays using numpy


code: X.objects.extra(where=["x.n in (select y.n from y where y.m = '%s')"], params=['m_value'])

rawDescription: Arbitrary joins in Django Models

description: Arbitrary joins in Django Models


rawDescription: How to test for "immutability-at-any-depth" in Python?

description: Test for "immutability-at-any-depth" in Python


code: set(zip(df.number, df.letter))

rawDescription: Distinct combinations values in Pandas DataFrames


code: tuple(max(0, min(tupleone[x] - tupletwo[x], 255)) for x in range(3))

rawDescription: adding value limitations on list comprehension

description: Adding value limitations on list comprehension


code: f = open(file_path, 'rb')

rawDescription: Download Excel file

description: Download Excel file


code:
from ..interfaces import IBulkModifyContentChanger
from zope.interface import implements

class TextContentAdapters(object):
    """This is OK for every know plone.app.contenttypes dexterity item"""

    implements(IBulkModifyContentChanger)

    def __init__(self, context):
        self.context = context

    def _get_text(self):
        return self._get_utext().encode('utf-8')

    def _set_text(self, text):
        raise NotImplementedError("%s doesn't implements setter for 8-bit string" % self.context.portal_type)

    def _get_utext(self):
        text_data = getattr(self.context, 'text', None)
        if text_data:
            return text_data.raw

    def _set_utext(self, text):
        self.context.text = text
        self.context.reindexObject(idxs=['SearchableText'])

    text = property(_get_text, _set_text)
    utext = property(_get_utext, _set_utext)

rawDescription: How to search and replace dexterity content in Plone using rt.bulkmodify

description: Search and replace dexterity content in Plone using rt.bulkmodify


code:
z = df.groupby('value_group').size()
z[sorted(z.index, key=lambda x: float(x.split()[0]))]
z[sorted(z.index, key=lambda x: float(x.split()[0]))].plot(kind='bar')

rawDescription: Sorting Pandas Categorical labels after groupby


rawDescription: map(function, sequence) where function returns two values

description: Map(function, sequence) where function returns two values


code:
rgx = re.compile(r'^Date: .+?\n+(.+?)(?:^diff |\Z)', re.MULTILINE | re.DOTALL)
comments = rgx.findall(txt)

rawDescription: Use regex to get comment block from a git log


code:
s = '+asdf'  # sample data

if s.startswith('+') or s.startswith('-'):
    pass  # do work here

rawDescription: Python- Look for string only in the beginning of a string


code:
# You don't need `a` to be a list here, just iterate the `range` object
for num in range(13):
    if len(b) < 3:
        b.append(num)
    else:
        # Add `b` to `final_list` here itself, so that you don't have
        # to check if `b` has 3 elements in it, later in the loop.
        final_list.append(b)

        # Since `b` already has 3 elements, create a new list with one element
        b = [num]

# `b` might have few elements but not exactly 3. So, add it if it is not empty
if len(b) != 0:
    final_list.append(b)

rawDescription: populate a list of list in python

description: Populate a list of list in python


code:
import string
from math import *

def main():
    n=4
    abscissa=[-5,-2,3,7]
    ordinate=[4,-6,8,1]
    result = ''
    for j,y in enumerate(ordinate):
        if j!=0:
            result += '+'
        LP=str(y)
        denom="1"
        for k,x in enumerate(abscissa):
            if k!=j:
                denom += '*({}-{})'.format(abscissa[j],x)
                LP += '*(x-{})'.format(x)
        LP += '/' + denom
        result += LP
    print(result)
main()

rawDescription: Program is written but cant get it to concatenate


code:
# obviously adapt this to your actual model
schools = School.objects.order_by('name').all()

school_dict = {}
for school in schools:
    first_letter = school.name[0].lower()
    if first_letter in school_dict:
        school_dict[first_letter].append(school)
    else:
        school_dict[first_letter] = [school]

rawDescription: Django Output Indices for an Ordered Set of Objects


code:
from ctypes import *
# if on Windows, may need to change following to use WinDLL instead of CDLL
vix = CDLL('vix.dll')

# user defined types
VixHandle = c_int
VixHandleType = c_int
VixError = c_uint64
VixPropertyType = c_int
VixPropertyID = c_int
VixEventType = c_int
VixHostOptions = c_int
VixServiceProvider = c_int
VixFindItemType = c_int
VixVMOpenOptions = c_int
VixPumpEventsOptions = c_int
VixVMPowerOpOptions = c_int
VixVMDeleteOptions = c_int
VixPowerState = c_int
VixToolsState = c_int
VixRunProgramOptions = c_int
VixRemoveSnapshotOptions = c_int
VixCreateSnapshotOptions = c_int
VixMsgSharedFolderOptions = c_int
VixCloneType = c_int
VixEventProc = CFUNCTYPE(VixHandle,
    VixEventType,
    VixHandle,
    c_void_p)

# constant definitions
VIX_INVALID_HANDLE = 0
VIX_HANDLETYPE_NONE = 0
VIX_HANDLETYPE_HOST = 2
VIX_HANDLETYPE_VM = 3
VIX_HANDLETYPE_NETWORK = 5
VIX_HANDLETYPE_JOB = 6
VIX_HANDLETYPE_SNAPSHOT = 7
VIX_HANDLETYPE_PROPERTY_LIST = 9
VIX_HANDLETYPE_METADATA_CONTAINER = 11
VIX_OK = 0
VIX_E_FAIL = 1
VIX_E_OUT_OF_MEMORY = 2
VIX_E_INVALID_ARG = 3
VIX_E_FILE_NOT_FOUND = 4
VIX_E_OBJECT_IS_BUSY = 5
VIX_E_NOT_SUPPORTED = 6
VIX_E_FILE_ERROR = 7
VIX_E_DISK_FULL = 8
VIX_E_INCORRECT_FILE_TYPE = 9
VIX_E_CANCELLED = 10
VIX_E_FILE_READ_ONLY = 11
VIX_E_FILE_ALREADY_EXISTS = 12
VIX_E_FILE_ACCESS_ERROR = 13
VIX_E_REQUIRES_LARGE_FILES = 14
VIX_E_FILE_ALREADY_LOCKED = 15
VIX_E_VMDB = 16
VIX_E_NOT_SUPPORTED_ON_REMOTE_OBJECT = 20
VIX_E_FILE_TOO_BIG = 21
VIX_E_FILE_NAME_INVALID = 22
VIX_E_ALREADY_EXISTS = 23
VIX_E_BUFFER_TOOSMALL = 24
VIX_E_OBJECT_NOT_FOUND = 25
VIX_E_HOST_NOT_CONNECTED = 26
VIX_E_INVALID_UTF8_STRING = 27
VIX_E_OPERATION_ALREADY_IN_PROGRESS = 31
VIX_E_UNFINISHED_JOB = 29
VIX_E_NEED_KEY = 30
VIX_E_LICENSE = 32
VIX_E_VM_HOST_DISCONNECTED = 34
VIX_E_AUTHENTICATION_FAIL = 35
VIX_E_HOST_CONNECTION_LOST = 36
VIX_E_DUPLICATE_NAME = 41
VIX_E_INVALID_HANDLE = 1000
VIX_E_NOT_SUPPORTED_ON_HANDLE_TYPE = 1001
VIX_E_TOO_MANY_HANDLES = 1002
VIX_E_NOT_FOUND = 2000
VIX_E_TYPE_MISMATCH = 2001
VIX_E_INVALID_XML = 2002
VIX_E_TIMEOUT_WAITING_FOR_TOOLS = 3000
VIX_E_UNRECOGNIZED_COMMAND = 3001
VIX_E_OP_NOT_SUPPORTED_ON_GUEST = 3003
VIX_E_PROGRAM_NOT_STARTED = 3004
VIX_E_CANNOT_START_READ_ONLY_VM = 3005
VIX_E_VM_NOT_RUNNING = 3006
VIX_E_VM_IS_RUNNING = 3007
VIX_E_CANNOT_CONNECT_TO_VM = 3008
VIX_E_POWEROP_SCRIPTS_NOT_AVAILABLE = 3009
VIX_E_NO_GUEST_OS_INSTALLED = 3010
VIX_E_VM_INSUFFICIENT_HOST_MEMORY = 3011
VIX_E_SUSPEND_ERROR = 3012
VIX_E_VM_NOT_ENOUGH_CPUS = 3013
VIX_E_HOST_USER_PERMISSIONS = 3014
VIX_E_GUEST_USER_PERMISSIONS = 3015
VIX_E_TOOLS_NOT_RUNNING = 3016
VIX_E_GUEST_OPERATIONS_PROHIBITED = 3017
VIX_E_ANON_GUEST_OPERATIONS_PROHIBITED = 3018
VIX_E_ROOT_GUEST_OPERATIONS_PROHIBITED = 3019
VIX_E_MISSING_ANON_GUEST_ACCOUNT = 3023
VIX_E_CANNOT_AUTHENTICATE_WITH_GUEST = 3024
VIX_E_UNRECOGNIZED_COMMAND_IN_GUEST = 3025
VIX_E_CONSOLE_GUEST_OPERATIONS_PROHIBITED = 3026
VIX_E_MUST_BE_CONSOLE_USER = 3027
VIX_E_VMX_MSG_DIALOG_AND_NO_UI = 3028
VIX_E_NOT_ALLOWED_DURING_VM_RECORDING = 3029
VIX_E_NOT_ALLOWED_DURING_VM_REPLAY = 3030
VIX_E_OPERATION_NOT_ALLOWED_FOR_LOGIN_TYPE = 3031
VIX_E_LOGIN_TYPE_NOT_SUPPORTED = 3032
VIX_E_EMPTY_PASSWORD_NOT_ALLOWED_IN_GUEST = 3033
VIX_E_INTERACTIVE_SESSION_NOT_PRESENT = 3034
VIX_E_INTERACTIVE_SESSION_USER_MISMATCH = 3035
VIX_E_UNABLE_TO_REPLAY_VM = 3039
VIX_E_CANNOT_POWER_ON_VM = 3041
VIX_E_NO_DISPLAY_SERVER = 3043
VIX_E_VM_NOT_RECORDING = 3044
VIX_E_VM_NOT_REPLAYING = 3045
VIX_E_VM_NOT_FOUND = 4000
VIX_E_NOT_SUPPORTED_FOR_VM_VERSION = 4001
VIX_E_CANNOT_READ_VM_CONFIG = 4002
VIX_E_TEMPLATE_VM = 4003
VIX_E_VM_ALREADY_LOADED = 4004
VIX_E_VM_ALREADY_UP_TO_DATE = 4006
VIX_E_VM_UNSUPPORTED_GUEST = 4011
VIX_E_UNRECOGNIZED_PROPERTY = 6000
VIX_E_INVALID_PROPERTY_VALUE = 6001
VIX_E_READ_ONLY_PROPERTY = 6002
VIX_E_MISSING_REQUIRED_PROPERTY = 6003
VIX_E_INVALID_SERIALIZED_DATA = 6004
VIX_E_PROPERTY_TYPE_MISMATCH = 6005
VIX_E_BAD_VM_INDEX = 8000
VIX_E_INVALID_MESSAGE_HEADER = 10000
VIX_E_INVALID_MESSAGE_BODY = 10001
VIX_E_SNAPSHOT_INVAL = 13000
VIX_E_SNAPSHOT_DUMPER = 13001
VIX_E_SNAPSHOT_DISKLIB = 13002
VIX_E_SNAPSHOT_NOTFOUND = 13003
VIX_E_SNAPSHOT_EXISTS = 13004
VIX_E_SNAPSHOT_VERSION = 13005
VIX_E_SNAPSHOT_NOPERM = 13006
VIX_E_SNAPSHOT_CONFIG = 13007
VIX_E_SNAPSHOT_NOCHANGE = 13008
VIX_E_SNAPSHOT_CHECKPOINT = 13009
VIX_E_SNAPSHOT_LOCKED = 13010
VIX_E_SNAPSHOT_INCONSISTENT = 13011
VIX_E_SNAPSHOT_NAMETOOLONG = 13012
VIX_E_SNAPSHOT_VIXFILE = 13013
VIX_E_SNAPSHOT_DISKLOCKED = 13014
VIX_E_SNAPSHOT_DUPLICATEDDISK = 13015
VIX_E_SNAPSHOT_INDEPENDENTDISK = 13016
VIX_E_SNAPSHOT_NONUNIQUE_NAME = 13017
VIX_E_SNAPSHOT_MEMORY_ON_INDEPENDENT_DISK = 13018
VIX_E_SNAPSHOT_MAXSNAPSHOTS = 13019
VIX_E_SNAPSHOT_MIN_FREE_SPACE = 13020
VIX_E_SNAPSHOT_HIERARCHY_TOODEEP = 13021
VIX_E_HOST_DISK_INVALID_VALUE = 14003
VIX_E_HOST_DISK_SECTORSIZE = 14004
VIX_E_HOST_FILE_ERROR_EOF = 14005
VIX_E_HOST_NETBLKDEV_HANDSHAKE = 14006
VIX_E_HOST_SOCKET_CREATION_ERROR = 14007
VIX_E_HOST_SERVER_NOT_FOUND = 14008
VIX_E_HOST_NETWORK_CONN_REFUSED = 14009
VIX_E_HOST_TCP_SOCKET_ERROR = 14010
VIX_E_HOST_TCP_CONN_LOST = 14011
VIX_E_HOST_NBD_HASHFILE_VOLUME = 14012
VIX_E_HOST_NBD_HASHFILE_INIT = 14013
VIX_E_DISK_INVAL = 16000
VIX_E_DISK_NOINIT = 16001
VIX_E_DISK_NOIO = 16002
VIX_E_DISK_PARTIALCHAIN = 16003
VIX_E_DISK_NEEDSREPAIR = 16006
VIX_E_DISK_OUTOFRANGE = 16007
VIX_E_DISK_CID_MISMATCH = 16008
VIX_E_DISK_CANTSHRINK = 16009
VIX_E_DISK_PARTMISMATCH = 16010
VIX_E_DISK_UNSUPPORTEDDISKVERSION = 16011
VIX_E_DISK_OPENPARENT = 16012
VIX_E_DISK_NOTSUPPORTED = 16013
VIX_E_DISK_NEEDKEY = 16014
VIX_E_DISK_NOKEYOVERRIDE = 16015
VIX_E_DISK_NOTENCRYPTED = 16016
VIX_E_DISK_NOKEY = 16017
VIX_E_DISK_INVALIDPARTITIONTABLE = 16018
VIX_E_DISK_NOTNORMAL = 16019
VIX_E_DISK_NOTENCDESC = 16020
VIX_E_DISK_NEEDVMFS = 16022
VIX_E_DISK_RAWTOOBIG = 16024
VIX_E_DISK_TOOMANYOPENFILES = 16027
VIX_E_DISK_TOOMANYREDO = 16028
VIX_E_DISK_RAWTOOSMALL = 16029
VIX_E_DISK_INVALIDCHAIN = 16030
VIX_E_DISK_KEY_NOTFOUND = 16052
VIX_E_DISK_SUBSYSTEM_INIT_FAIL = 16053
VIX_E_DISK_INVALID_CONNECTION = 16054
VIX_E_DISK_ENCODING = 16061
VIX_E_DISK_CANTREPAIR = 16062
VIX_E_DISK_INVALIDDISK = 16063
VIX_E_DISK_NOLICENSE = 16064
VIX_E_DISK_NODEVICE = 16065
VIX_E_DISK_UNSUPPORTEDDEVICE = 16066
VIX_E_CRYPTO_UNKNOWN_ALGORITHM = 17000
VIX_E_CRYPTO_BAD_BUFFER_SIZE = 17001
VIX_E_CRYPTO_INVALID_OPERATION = 17002
VIX_E_CRYPTO_RANDOM_DEVICE = 17003
VIX_E_CRYPTO_NEED_PASSWORD = 17004
VIX_E_CRYPTO_BAD_PASSWORD = 17005
VIX_E_CRYPTO_NOT_IN_DICTIONARY = 17006
VIX_E_CRYPTO_NO_CRYPTO = 17007
VIX_E_CRYPTO_ERROR = 17008
VIX_E_CRYPTO_BAD_FORMAT = 17009
VIX_E_CRYPTO_LOCKED = 17010
VIX_E_CRYPTO_EMPTY = 17011
VIX_E_CRYPTO_KEYSAFE_LOCATOR = 17012
VIX_E_CANNOT_CONNECT_TO_HOST = 18000
VIX_E_NOT_FOR_REMOTE_HOST = 18001
VIX_E_INVALID_HOSTNAME_SPECIFICATION = 18002
VIX_E_SCREEN_CAPTURE_ERROR = 19000
VIX_E_SCREEN_CAPTURE_BAD_FORMAT = 19001
VIX_E_SCREEN_CAPTURE_COMPRESSION_FAIL = 19002
VIX_E_SCREEN_CAPTURE_LARGE_DATA = 19003
VIX_E_GUEST_VOLUMES_NOT_FROZEN = 20000
VIX_E_NOT_A_FILE = 20001
VIX_E_NOT_A_DIRECTORY = 20002
VIX_E_NO_SUCH_PROCESS = 20003
VIX_E_FILE_NAME_TOO_LONG = 20004
VIX_E_TOOLS_INSTALL_NO_IMAGE = 21000
VIX_E_TOOLS_INSTALL_IMAGE_INACCESIBLE = 21001
VIX_E_TOOLS_INSTALL_NO_DEVICE = 21002
VIX_E_TOOLS_INSTALL_DEVICE_NOT_CONNECTED = 21003
VIX_E_TOOLS_INSTALL_CANCELLED = 21004
VIX_E_TOOLS_INSTALL_INIT_FAILED = 21005
VIX_E_TOOLS_INSTALL_AUTO_NOT_SUPPORTED = 21006
VIX_E_TOOLS_INSTALL_GUEST_NOT_READY = 21007
VIX_E_TOOLS_INSTALL_SIG_CHECK_FAILED = 21008
VIX_E_TOOLS_INSTALL_ERROR = 21009
VIX_E_TOOLS_INSTALL_ALREADY_UP_TO_DATE = 21010
VIX_E_TOOLS_INSTALL_IN_PROGRESS = 21011
VIX_E_WRAPPER_WORKSTATION_NOT_INSTALLED = 22001
VIX_E_WRAPPER_VERSION_NOT_FOUND = 22002
VIX_E_WRAPPER_SERVICEPROVIDER_NOT_FOUND = 22003
VIX_E_WRAPPER_PLAYER_NOT_INSTALLED = 22004
VIX_E_WRAPPER_RUNTIME_NOT_INSTALLED = 22005
VIX_E_WRAPPER_MULTIPLE_SERVICEPROVIDERS = 22006
VIX_E_MNTAPI_MOUNTPT_NOT_FOUND = 24000
VIX_E_MNTAPI_MOUNTPT_IN_USE = 24001
VIX_E_MNTAPI_DISK_NOT_FOUND = 24002
VIX_E_MNTAPI_DISK_NOT_MOUNTED = 24003
VIX_E_MNTAPI_DISK_IS_MOUNTED = 24004
VIX_E_MNTAPI_DISK_NOT_SAFE = 24005
VIX_E_MNTAPI_DISK_CANT_OPEN = 24006
VIX_E_MNTAPI_CANT_READ_PARTS = 24007
VIX_E_MNTAPI_UMOUNT_APP_NOT_FOUND = 24008
VIX_E_MNTAPI_UMOUNT = 24009
VIX_E_MNTAPI_NO_MOUNTABLE_PARTITONS = 24010
VIX_E_MNTAPI_PARTITION_RANGE = 24011
VIX_E_MNTAPI_PERM = 24012
VIX_E_MNTAPI_DICT = 24013
VIX_E_MNTAPI_DICT_LOCKED = 24014
VIX_E_MNTAPI_OPEN_HANDLES = 24015
VIX_E_MNTAPI_CANT_MAKE_VAR_DIR = 24016
VIX_E_MNTAPI_NO_ROOT = 24017
VIX_E_MNTAPI_LOOP_FAILED = 24018
VIX_E_MNTAPI_DAEMON = 24019
VIX_E_MNTAPI_INTERNAL = 24020
VIX_E_MNTAPI_SYSTEM = 24021
VIX_E_MNTAPI_NO_CONNECTION_DETAILS = 24022
VIX_E_MNTAPI_INCOMPATIBLE_VERSION = 24300
VIX_E_MNTAPI_OS_ERROR = 24301
VIX_E_MNTAPI_DRIVE_LETTER_IN_USE = 24302
VIX_E_MNTAPI_DRIVE_LETTER_ALREADY_ASSIGNED = 24303
VIX_E_MNTAPI_VOLUME_NOT_MOUNTED = 24304
VIX_E_MNTAPI_VOLUME_ALREADY_MOUNTED = 24305
VIX_E_MNTAPI_FORMAT_FAILURE = 24306
VIX_E_MNTAPI_NO_DRIVER = 24307
VIX_E_MNTAPI_ALREADY_OPENED = 24308
VIX_E_MNTAPI_ITEM_NOT_FOUND = 24309
VIX_E_MNTAPI_UNSUPPROTED_BOOT_LOADER = 24310
VIX_E_MNTAPI_UNSUPPROTED_OS = 24311
VIX_E_MNTAPI_CODECONVERSION = 24312
VIX_E_MNTAPI_REGWRITE_ERROR = 24313
VIX_E_MNTAPI_UNSUPPORTED_FT_VOLUME = 24314
VIX_E_MNTAPI_PARTITION_NOT_FOUND = 24315
VIX_E_MNTAPI_PUTFILE_ERROR = 24316
VIX_E_MNTAPI_GETFILE_ERROR = 24317
VIX_E_MNTAPI_REG_NOT_OPENED = 24318
VIX_E_MNTAPI_REGDELKEY_ERROR = 24319
VIX_E_MNTAPI_CREATE_PARTITIONTABLE_ERROR = 24320
VIX_E_MNTAPI_OPEN_FAILURE = 24321
VIX_E_MNTAPI_VOLUME_NOT_WRITABLE = 24322
VIX_E_NET_HTTP_UNSUPPORTED_PROTOCOL = 30001
VIX_E_NET_HTTP_URL_MALFORMAT = 30003
VIX_E_NET_HTTP_COULDNT_RESOLVE_PROXY = 30005
VIX_E_NET_HTTP_COULDNT_RESOLVE_HOST = 30006
VIX_E_NET_HTTP_COULDNT_CONNECT = 30007
VIX_E_NET_HTTP_HTTP_RETURNED_ERROR = 30022
VIX_E_NET_HTTP_OPERATION_TIMEDOUT = 30028
VIX_E_NET_HTTP_SSL_CONNECT_ERROR = 30035
VIX_E_NET_HTTP_TOO_MANY_REDIRECTS = 30047
VIX_E_NET_HTTP_TRANSFER = 30200
VIX_E_NET_HTTP_SSL_SECURITY = 30201
VIX_E_NET_HTTP_GENERIC = 30202
VIX_PROPERTYTYPE_ANY = 0
VIX_PROPERTYTYPE_INTEGER = 1
VIX_PROPERTYTYPE_STRING = 2
VIX_PROPERTYTYPE_BOOL = 3
VIX_PROPERTYTYPE_HANDLE = 4
VIX_PROPERTYTYPE_INT64 = 5
VIX_PROPERTYTYPE_BLOB = 6
VIX_PROPERTY_NONE = 0
VIX_PROPERTY_META_DATA_CONTAINER = 2
VIX_PROPERTY_HOST_HOSTTYPE = 50
VIX_PROPERTY_HOST_API_VERSION = 51
VIX_PROPERTY_VM_NUM_VCPUS = 101
VIX_PROPERTY_VM_VMX_PATHNAME = 103
VIX_PROPERTY_VM_VMTEAM_PATHNAME = 105
VIX_PROPERTY_VM_MEMORY_SIZE = 106
VIX_PROPERTY_VM_READ_ONLY = 107
VIX_PROPERTY_VM_NAME = 108
VIX_PROPERTY_VM_GUESTOS = 109
VIX_PROPERTY_VM_IN_VMTEAM = 128
VIX_PROPERTY_VM_POWER_STATE = 129
VIX_PROPERTY_VM_TOOLS_STATE = 152
VIX_PROPERTY_VM_IS_RUNNING = 196
VIX_PROPERTY_VM_SUPPORTED_FEATURES = 197
VIX_PROPERTY_VM_IS_RECORDING = 236
VIX_PROPERTY_VM_IS_REPLAYING = 237
VIX_PROPERTY_JOB_RESULT_ERROR_CODE = 3000
VIX_PROPERTY_JOB_RESULT_VM_IN_GROUP = 3001
VIX_PROPERTY_JOB_RESULT_USER_MESSAGE = 3002
VIX_PROPERTY_JOB_RESULT_EXIT_CODE = 3004
VIX_PROPERTY_JOB_RESULT_COMMAND_OUTPUT = 3005
VIX_PROPERTY_JOB_RESULT_HANDLE = 3010
VIX_PROPERTY_JOB_RESULT_GUEST_OBJECT_EXISTS = 3011
VIX_PROPERTY_JOB_RESULT_GUEST_PROGRAM_ELAPSED_TIME = 3017
VIX_PROPERTY_JOB_RESULT_GUEST_PROGRAM_EXIT_CODE = 3018
VIX_PROPERTY_JOB_RESULT_ITEM_NAME = 3035
VIX_PROPERTY_JOB_RESULT_FOUND_ITEM_DESCRIPTION = 3036
VIX_PROPERTY_JOB_RESULT_SHARED_FOLDER_COUNT = 3046
VIX_PROPERTY_JOB_RESULT_SHARED_FOLDER_HOST = 3048
VIX_PROPERTY_JOB_RESULT_SHARED_FOLDER_FLAGS = 3049
VIX_PROPERTY_JOB_RESULT_PROCESS_ID = 3051
VIX_PROPERTY_JOB_RESULT_PROCESS_OWNER = 3052
VIX_PROPERTY_JOB_RESULT_PROCESS_COMMAND = 3053
VIX_PROPERTY_JOB_RESULT_FILE_FLAGS = 3054
VIX_PROPERTY_JOB_RESULT_PROCESS_START_TIME = 3055
VIX_PROPERTY_JOB_RESULT_VM_VARIABLE_STRING = 3056
VIX_PROPERTY_JOB_RESULT_PROCESS_BEING_DEBUGGED = 3057
VIX_PROPERTY_JOB_RESULT_SCREEN_IMAGE_SIZE = 3058
VIX_PROPERTY_JOB_RESULT_SCREEN_IMAGE_DATA = 3059
VIX_PROPERTY_JOB_RESULT_FILE_SIZE = 3061
VIX_PROPERTY_JOB_RESULT_FILE_MOD_TIME = 3062
VIX_PROPERTY_JOB_RESULT_EXTRA_ERROR_INFO = 3084
VIX_PROPERTY_FOUND_ITEM_LOCATION = 4010
VIX_PROPERTY_SNAPSHOT_DISPLAYNAME = 4200
VIX_PROPERTY_SNAPSHOT_DESCRIPTION = 4201
VIX_PROPERTY_SNAPSHOT_POWERSTATE = 4205
VIX_PROPERTY_SNAPSHOT_IS_REPLAYABLE = 4207
VIX_PROPERTY_GUEST_SHAREDFOLDERS_SHARES_PATH = 4525
VIX_PROPERTY_VM_ENCRYPTION_PASSWORD = 7001
VIX_EVENTTYPE_JOB_COMPLETED = 2
VIX_EVENTTYPE_JOB_PROGRESS = 3
VIX_EVENTTYPE_FIND_ITEM = 8
VIX_EVENTTYPE_CALLBACK_SIGNALLED = 2
VIX_FILE_ATTRIBUTES_DIRECTORY = 0x0001
VIX_FILE_ATTRIBUTES_SYMLINK = 0x0002
VIX_HOSTOPTION_USE_EVENT_PUMP = 0x0008
VIX_SERVICEPROVIDER_DEFAULT = 1
VIX_SERVICEPROVIDER_VMWARE_SERVER = 2
VIX_SERVICEPROVIDER_VMWARE_WORKSTATION = 3
VIX_SERVICEPROVIDER_VMWARE_PLAYER = 4
VIX_SERVICEPROVIDER_VMWARE_VI_SERVER = 10
VIX_API_VERSION = -1
VIX_FIND_RUNNING_VMS = 1
VIX_FIND_REGISTERED_VMS = 4
VIX_VMOPEN_NORMAL = 0x0
VIX_PUMPEVENTOPTION_NONE = 0
VIX_VMPOWEROP_NORMAL = 0
VIX_VMPOWEROP_FROM_GUEST = 0x0004
VIX_VMPOWEROP_SUPPRESS_SNAPSHOT_POWERON = 0x0080
VIX_VMPOWEROP_LAUNCH_GUI = 0x0200
VIX_VMPOWEROP_START_VM_PAUSED = 0x1000
VIX_VMDELETE_DISK_FILES = 0x0002
VIX_POWERSTATE_POWERING_OFF = 0x0001
VIX_POWERSTATE_POWERED_OFF = 0x0002
VIX_POWERSTATE_POWERING_ON = 0x0004
VIX_POWERSTATE_POWERED_ON = 0x0008
VIX_POWERSTATE_SUSPENDING = 0x0010
VIX_POWERSTATE_SUSPENDED = 0x0020
VIX_POWERSTATE_TOOLS_RUNNING = 0x0040
VIX_POWERSTATE_RESETTING = 0x0080
VIX_POWERSTATE_BLOCKED_ON_MSG = 0x0100
VIX_POWERSTATE_PAUSED = 0x0200
VIX_POWERSTATE_RESUMING = 0x0800
VIX_TOOLSSTATE_UNKNOWN = 0x0001
VIX_TOOLSSTATE_RUNNING = 0x0002
VIX_TOOLSSTATE_NOT_INSTALLED = 0x0004
VIX_VM_SUPPORT_SHARED_FOLDERS = 0x0001
VIX_VM_SUPPORT_MULTIPLE_SNAPSHOTS = 0x0002
VIX_VM_SUPPORT_TOOLS_INSTALL = 0x0004
VIX_VM_SUPPORT_HARDWARE_UPGRADE = 0x0008
VIX_LOGIN_IN_GUEST_REQUIRE_INTERACTIVE_ENVIRONMENT = 0x08
VIX_RUNPROGRAM_RETURN_IMMEDIATELY = 0x0001
VIX_RUNPROGRAM_ACTIVATE_WINDOW = 0x0002
VIX_VM_GUEST_VARIABLE = 1
VIX_VM_CONFIG_RUNTIME_ONLY = 2
VIX_GUEST_ENVIRONMENT_VARIABLE = 3
VIX_SNAPSHOT_REMOVE_CHILDREN = 0x0001
VIX_SNAPSHOT_INCLUDE_MEMORY = 0x0002
VIX_SHAREDFOLDER_WRITE_ACCESS = 0x04
VIX_CAPTURESCREENFORMAT_PNG = 0x01
VIX_CAPTURESCREENFORMAT_PNG_NOCOMPRESS = 0x02
VIX_CLONETYPE_FULL = 0
VIX_CLONETYPE_LINKED = 1
VIX_INSTALLTOOLS_MOUNT_TOOLS_INSTALLER = 0x00
VIX_INSTALLTOOLS_AUTO_UPGRADE = 0x01
VIX_INSTALLTOOLS_RETURN_IMMEDIATELY = 0x02

# functions
vix.Vix_GetErrorText.restype = c_char_p
vix.Vix_GetErrorText.argtypes = [VixError,c_char_p]
vix.Vix_ReleaseHandle.restype = None
vix.Vix_ReleaseHandle.argtypes = [VixHandle]
vix.Vix_AddRefHandle.restype = None
vix.Vix_AddRefHandle.argtypes = [VixHandle]
vix.Vix_GetHandleType.restype = VixHandleType
vix.Vix_GetHandleType.argtypes = [VixHandle]
vix.Vix_GetProperties.restype = VixError
# warning - vix.Vix_GetProperties takes variable argument list
vix.Vix_GetProperties.argtypes = [VixHandle,VixPropertyID]
vix.Vix_GetPropertyType.restype = VixError
vix.Vix_GetPropertyType.argtypes = [VixHandle,VixPropertyID,POINTER(VixPropertyType)]
vix.Vix_FreeBuffer.restype = None
vix.Vix_FreeBuffer.argtypes = [c_void_p]
vix.VixHost_Connect.restype = VixHandle
vix.VixHost_Connect.argtypes = [c_int,VixServiceProvider,c_char_p,c_int,c_char_p,c_char_p,VixHostOptions,VixHandle,POINTER(VixEventProc),c_void_p]
vix.VixHost_Disconnect.restype = None
vix.VixHost_Disconnect.argtypes = [VixHandle]
vix.VixHost_RegisterVM.restype = VixHandle
vix.VixHost_RegisterVM.argtypes = [VixHandle,c_char_p,POINTER(VixEventProc),c_void_p]
vix.VixHost_UnregisterVM.restype = VixHandle
vix.VixHost_UnregisterVM.argtypes = [VixHandle,c_char_p,POINTER(VixEventProc),c_void_p]
vix.VixHost_FindItems.restype = VixHandle
vix.VixHost_FindItems.argtypes = [VixHandle,VixFindItemType,VixHandle,c_int32,POINTER(VixEventProc),c_void_p]
vix.VixHost_OpenVM.restype = VixHandle
vix.VixHost_OpenVM.argtypes = [VixHandle,c_char_p,VixVMOpenOptions,VixHandle,POINTER(VixEventProc),c_void_p]
vix.Vix_PumpEvents.restype = None
vix.Vix_PumpEvents.argtypes = [VixHandle,VixPumpEventsOptions]
vix.VixPropertyList_AllocPropertyList.restype = VixError
# warning - vix.VixPropertyList_AllocPropertyList takes variable argument list
vix.VixPropertyList_AllocPropertyList.argtypes = [VixHandle,POINTER(VixHandle),c_int]
vix.VixVM_Open.restype = VixHandle
vix.VixVM_Open.argtypes = [VixHandle,c_char_p,POINTER(VixEventProc),c_void_p]
vix.VixVM_PowerOn.restype = VixHandle
vix.VixVM_PowerOn.argtypes = [VixHandle,VixVMPowerOpOptions,VixHandle,POINTER(VixEventProc),c_void_p]
vix.VixVM_PowerOff.restype = VixHandle
vix.VixVM_PowerOff.argtypes = [VixHandle,VixVMPowerOpOptions,POINTER(VixEventProc),c_void_p]
vix.VixVM_Reset.restype = VixHandle
vix.VixVM_Reset.argtypes = [VixHandle,VixVMPowerOpOptions,POINTER(VixEventProc),c_void_p]
vix.VixVM_Suspend.restype = VixHandle
vix.VixVM_Suspend.argtypes = [VixHandle,VixVMPowerOpOptions,POINTER(VixEventProc),c_void_p]
vix.VixVM_Pause.restype = VixHandle
vix.VixVM_Pause.argtypes = [VixHandle,c_int,VixHandle,POINTER(VixEventProc),c_void_p]
vix.VixVM_Unpause.restype = VixHandle
vix.VixVM_Unpause.argtypes = [VixHandle,c_int,VixHandle,POINTER(VixEventProc),c_void_p]
vix.VixVM_Delete.restype = VixHandle
vix.VixVM_Delete.argtypes = [VixHandle,VixVMDeleteOptions,POINTER(VixEventProc),c_void_p]
vix.VixVM_BeginRecording.restype = VixHandle
vix.VixVM_BeginRecording.argtypes = [VixHandle,c_char_p,c_char_p,c_int,VixHandle,POINTER(VixEventProc),c_void_p]
vix.VixVM_EndRecording.restype = VixHandle
vix.VixVM_EndRecording.argtypes = [VixHandle,c_int,VixHandle,POINTER(VixEventProc),c_void_p]
vix.VixVM_BeginReplay.restype = VixHandle
vix.VixVM_BeginReplay.argtypes = [VixHandle,VixHandle,c_int,VixHandle,POINTER(VixEventProc),c_void_p]
vix.VixVM_EndReplay.restype = VixHandle
vix.VixVM_EndReplay.argtypes = [VixHandle,c_int,VixHandle,POINTER(VixEventProc),c_void_p]
vix.VixVM_WaitForToolsInGuest.restype = VixHandle
vix.VixVM_WaitForToolsInGuest.argtypes = [VixHandle,c_int,POINTER(VixEventProc),c_void_p]
vix.VixVM_LoginInGuest.restype = VixHandle
vix.VixVM_LoginInGuest.argtypes = [VixHandle,c_char_p,c_char_p,c_int,POINTER(VixEventProc),c_void_p]
vix.VixVM_LogoutFromGuest.restype = VixHandle
vix.VixVM_LogoutFromGuest.argtypes = [VixHandle,POINTER(VixEventProc),c_void_p]
vix.VixVM_RunProgramInGuest.restype = VixHandle
vix.VixVM_RunProgramInGuest.argtypes = [VixHandle,c_char_p,c_char_p,VixRunProgramOptions,VixHandle,POINTER(VixEventProc),c_void_p]
vix.VixVM_ListProcessesInGuest.restype = VixHandle
vix.VixVM_ListProcessesInGuest.argtypes = [VixHandle,c_int,POINTER(VixEventProc),c_void_p]
vix.VixVM_KillProcessInGuest.restype = VixHandle
vix.VixVM_KillProcessInGuest.argtypes = [VixHandle,c_uint64,c_int,POINTER(VixEventProc),c_void_p]
vix.VixVM_RunScriptInGuest.restype = VixHandle
vix.VixVM_RunScriptInGuest.argtypes = [VixHandle,c_char_p,c_char_p,VixRunProgramOptions,VixHandle,POINTER(VixEventProc),c_void_p]
vix.VixVM_OpenUrlInGuest.restype = VixHandle
vix.VixVM_OpenUrlInGuest.argtypes = [VixHandle,c_char_p,c_int,VixHandle,POINTER(VixEventProc),c_void_p]
vix.VixVM_CopyFileFromHostToGuest.restype = VixHandle
vix.VixVM_CopyFileFromHostToGuest.argtypes = [VixHandle,c_char_p,c_char_p,c_int,VixHandle,POINTER(VixEventProc),c_void_p]
vix.VixVM_CopyFileFromGuestToHost.restype = VixHandle
vix.VixVM_CopyFileFromGuestToHost.argtypes = [VixHandle,c_char_p,c_char_p,c_int,VixHandle,POINTER(VixEventProc),c_void_p]
vix.VixVM_DeleteFileInGuest.restype = VixHandle
vix.VixVM_DeleteFileInGuest.argtypes = [VixHandle,c_char_p,POINTER(VixEventProc),c_void_p]
vix.VixVM_FileExistsInGuest.restype = VixHandle
vix.VixVM_FileExistsInGuest.argtypes = [VixHandle,c_char_p,POINTER(VixEventProc),c_void_p]
vix.VixVM_RenameFileInGuest.restype = VixHandle
vix.VixVM_RenameFileInGuest.argtypes = [VixHandle,c_char_p,c_char_p,c_int,VixHandle,POINTER(VixEventProc),c_void_p]
vix.VixVM_CreateTempFileInGuest.restype = VixHandle
vix.VixVM_CreateTempFileInGuest.argtypes = [VixHandle,c_int,VixHandle,POINTER(VixEventProc),c_void_p]
vix.VixVM_GetFileInfoInGuest.restype = VixHandle
vix.VixVM_GetFileInfoInGuest.argtypes = [VixHandle,c_char_p,POINTER(VixEventProc),c_void_p]
vix.VixVM_ListDirectoryInGuest.restype = VixHandle
vix.VixVM_ListDirectoryInGuest.argtypes = [VixHandle,c_char_p,c_int,POINTER(VixEventProc),c_void_p]
vix.VixVM_CreateDirectoryInGuest.restype = VixHandle
vix.VixVM_CreateDirectoryInGuest.argtypes = [VixHandle,c_char_p,VixHandle,POINTER(VixEventProc),c_void_p]
vix.VixVM_DeleteDirectoryInGuest.restype = VixHandle
vix.VixVM_DeleteDirectoryInGuest.argtypes = [VixHandle,c_char_p,c_int,POINTER(VixEventProc),c_void_p]
vix.VixVM_DirectoryExistsInGuest.restype = VixHandle
vix.VixVM_DirectoryExistsInGuest.argtypes = [VixHandle,c_char_p,POINTER(VixEventProc),c_void_p]
vix.VixVM_ReadVariable.restype = VixHandle
vix.VixVM_ReadVariable.argtypes = [VixHandle,c_int,c_char_p,c_int,POINTER(VixEventProc),c_void_p]
vix.VixVM_WriteVariable.restype = VixHandle
vix.VixVM_WriteVariable.argtypes = [VixHandle,c_int,c_char_p,c_char_p,c_int,POINTER(VixEventProc),c_void_p]
vix.VixVM_GetNumRootSnapshots.restype = VixError
vix.VixVM_GetNumRootSnapshots.argtypes = [VixHandle,POINTER(c_int)]
vix.VixVM_GetRootSnapshot.restype = VixError
vix.VixVM_GetRootSnapshot.argtypes = [VixHandle,c_int,POINTER(VixHandle)]
vix.VixVM_GetCurrentSnapshot.restype = VixError
vix.VixVM_GetCurrentSnapshot.argtypes = [VixHandle,POINTER(VixHandle)]
vix.VixVM_GetNamedSnapshot.restype = VixError
vix.VixVM_GetNamedSnapshot.argtypes = [VixHandle,c_char_p,POINTER(VixHandle)]
vix.VixVM_RemoveSnapshot.restype = VixHandle
vix.VixVM_RemoveSnapshot.argtypes = [VixHandle,VixHandle,VixRemoveSnapshotOptions,POINTER(VixEventProc),c_void_p]
vix.VixVM_RevertToSnapshot.restype = VixHandle
vix.VixVM_RevertToSnapshot.argtypes = [VixHandle,VixHandle,VixVMPowerOpOptions,VixHandle,POINTER(VixEventProc),c_void_p]
vix.VixVM_CreateSnapshot.restype = VixHandle
vix.VixVM_CreateSnapshot.argtypes = [VixHandle,c_char_p,c_char_p,VixCreateSnapshotOptions,VixHandle,POINTER(VixEventProc),c_void_p]
vix.VixVM_EnableSharedFolders.restype = VixHandle
vix.VixVM_EnableSharedFolders.argtypes = [VixHandle,c_byte,c_int,POINTER(VixEventProc),c_void_p]
vix.VixVM_GetNumSharedFolders.restype = VixHandle
vix.VixVM_GetNumSharedFolders.argtypes = [VixHandle,POINTER(VixEventProc),c_void_p]
vix.VixVM_GetSharedFolderState.restype = VixHandle
vix.VixVM_GetSharedFolderState.argtypes = [VixHandle,c_int,POINTER(VixEventProc),c_void_p]
vix.VixVM_SetSharedFolderState.restype = VixHandle
vix.VixVM_SetSharedFolderState.argtypes = [VixHandle,c_char_p,c_char_p,VixMsgSharedFolderOptions,POINTER(VixEventProc),c_void_p]
vix.VixVM_AddSharedFolder.restype = VixHandle
vix.VixVM_AddSharedFolder.argtypes = [VixHandle,c_char_p,c_char_p,VixMsgSharedFolderOptions,POINTER(VixEventProc),c_void_p]
vix.VixVM_RemoveSharedFolder.restype = VixHandle
vix.VixVM_RemoveSharedFolder.argtypes = [VixHandle,c_char_p,c_int,POINTER(VixEventProc),c_void_p]
vix.VixVM_CaptureScreenImage.restype = VixHandle
vix.VixVM_CaptureScreenImage.argtypes = [VixHandle,c_int,VixHandle,POINTER(VixEventProc),c_void_p]
vix.VixVM_Clone.restype = VixHandle
vix.VixVM_Clone.argtypes = [VixHandle,VixHandle,VixCloneType,c_char_p,c_int,VixHandle,POINTER(VixEventProc),c_void_p]
vix.VixVM_UpgradeVirtualHardware.restype = VixHandle
vix.VixVM_UpgradeVirtualHardware.argtypes = [VixHandle,c_int,POINTER(VixEventProc),c_void_p]
vix.VixVM_InstallTools.restype = VixHandle
vix.VixVM_InstallTools.argtypes = [VixHandle,c_int,c_char_p,POINTER(VixEventProc),c_void_p]
vix.VixJob_Wait.restype = VixError
# warning - vix.VixJob_Wait takes variable argument list
vix.VixJob_Wait.argtypes = [VixHandle,VixPropertyID]
vix.VixJob_CheckCompletion.restype = VixError
vix.VixJob_CheckCompletion.argtypes = [VixHandle,POINTER(c_byte)]
vix.VixJob_GetError.restype = VixError
vix.VixJob_GetError.argtypes = [VixHandle]
vix.VixJob_GetNumProperties.restype = c_int
vix.VixJob_GetNumProperties.argtypes = [VixHandle,c_int]
vix.VixJob_GetNthProperties.restype = VixError
# warning - vix.VixJob_GetNthProperties takes variable argument list
vix.VixJob_GetNthProperties.argtypes = [VixHandle,c_int,c_int]
vix.VixSnapshot_GetNumChildren.restype = VixError
vix.VixSnapshot_GetNumChildren.argtypes = [VixHandle,POINTER(c_int)]
vix.VixSnapshot_GetChild.restype = VixError
vix.VixSnapshot_GetChild.argtypes = [VixHandle,c_int,POINTER(VixHandle)]
vix.VixSnapshot_GetParent.restype = VixError
vix.VixSnapshot_GetParent.argtypes = [VixHandle,POINTER(VixHandle)]

rawDescription: Use of ctypes module

description: Use of ctypes module


code:
match = re.search(r"\bOne\b(.*?)\bThree\b", text, re.DOTALL)
if match:
    betweenwords = match.group(1)
    dates = re.findall(r'\d\d (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{4}', betweenwords)

rawDescription: python regex of a date in some text, enclosed by two keywords

description: Python regex of a date in some text, enclosed by two keywords


code:
cancel = False
class_list = []

while (True):
    name = input("Give the name of the user you want to add: ")
    homework = [int(i) for i in input("Homework marks (seperated by spaces): ").split(" ")]
    quizzes = [int(i) for i in input("Quiz marks (seperated by spaces): ").split(" ")]
    tests = [int(i) for i in input("Test marks (seperated by spaces): ").split(" ")]

    class_list.append({
        "name": name,
        "homework": homework,
        "quizzes": quizzes,
        "tests": tests
    })

    cont = input("Want to add another? (Y/N)")
    if cont == "N":
        break;

print(class_list)

rawDescription: Using user input to create dictionaries in Python


code:
from pymel.core import *
class RetopoWindow(object):

    def __init__(self):
        self.window = window('myWin')
        columnLayout(adj=1)
        button('retopoplz',ann='Select a Mesh to Retopologize', bgc=[.15,.15,.15],l='START RETOPOLOGY', c = self.do_retopo)
        self.TextToMakeLive=textField(ann='Mesh Selected', bgc=[.2,0,0],edit=0,tx='NONE')

    def show(self):
        showWindow(self.window)

    def do_retopo(self, *_):
        #This tool selects the object to retopologize
        MakeLiveField= textField(self.TextToMakeLive,q=1,tx=1)
        MakeSelectionLive=(ls(sl=1))
        if MakeSelectionLive is None:
            warning('Please select an object to retopologize')
        if len( MakeSelectionLive) == 1:
            TextToMakeLive=textField(self.TextToMakeLive,ed=1,tx=MakeSelectionLive,bgc=[0,.2,0])
            shape=ls(s=MakeSelectionLive[0])
            setAttr((shape+'.backfaceCulling'),3)
            createDisplayLayer(n='RetopoLayer',num=1,nr=1)
            makeLive(shape)
            print('Retopology Activated!')
        else:
            warning('Select only ONE Object')

rawDescription: replace text in textField with object name - Pymel

description: Replace text in textField with object name - Pymel


code: sorteddata = sorted(dicttmp.items(), key=lambda d: d[1])

rawDescription: How can I sort the dictionary by its value?

description: Sort the dictionary by its value


code:
class MyBaseForm(Form):
    class Meta:
        def bind_field(self, form, unbound_field, options):
            filters = unbound_field.kwargs.get('filters', [])
            filters.append(my_strip_filter)
            return unbound_field.bind(form=form, filters=filters, **options)

def my_strip_filter(value):
    if value is not None and hasattr(value, 'strip'):
        return value.strip()
    return value

rawDescription: Automatically strip() all values in WTForms?


code:
sample = [[["1"],"1"],["2",[["123",[[["23"]]],23],[12.3,"23"]]],[["5"],"1","1"]]
def traverse(l, f):
    result = []
    for item in l:
        if isinstance(item, list):
            result.append(traverse(item))
        else:
            result.append(f(item))
    return result

rawDescription: How to reach every single element which is not list in random nested list?

description: Reach every single element which is not list in random nested list


code:
iter1 = ['\t'.join('1'*10) for _ in range(3)]

result = '\n'.join(iter1).replace('\t', '\n')

rawDescription: split and join strings

description: Split and join strings


code: {k: tuple(sum(x) for x in zip(*v)) for k, v in data.items()}

rawDescription: Sum values in tuple (values in dict) Python 2.7


code:
class MyModel(models.Model):

    my_nullable_string = models.CharField(max_length=15, null=True, blank=True)

    def save(self, *args, **kwargs):
         if not self.my_nullable_string:
              self.my_nullable_string = None
         super(MyModel, self).save(*args, **kwargs)

rawDescription: How can I allow django admin to set a field to NULL?

description: Allow django admin to set a field to NULL


code:
from collections import defaultdict
from itertools import combinations
triangles = [(1,2,3), (2,3,4), (1,3,5), (3,4,5), (5,6,7), (4,5,6)]
# For each edge set triangles containing that edge
edge2trias = defaultdict(list)  # edge (v1,v2) -> list of triangles
for t_ind, ps in enumerate(triangles):
    for edge in zip(ps, ps[1:]+ps[:1]):
        edge2trias[tuple(sorted(edge))].append(t_ind)
# For each edge, set pair(s) of neighbouring triangles
tria2neigh = defaultdict(list)  # triangle index -> list of neighbouring triangles
for edge, trias in edge2trias.iteritems():
    for t1, t2 in combinations(trias, 2):
        tria2neigh[t1].append(t2)
        tria2neigh[t2].append(t1)

rawDescription: Is there a python library capable of calculating the dual of a 3D mesh?


code:
import os

find = ['x.txt', 'y.txt']

found_dirs = []
for root, dirs, files in os.walk('/path/to/folder'):
    if any(filename in files for filename in find):
        found_dirs.append(root)

#found_dirs now contains all of the directories which matched

rawDescription: Search directory for a directory with certain files?


code: odd_column_header = data_header[0::2]

rawDescription: How to get odd column headers in Python?

description: Get odd column headers in Python


code:
from functools import partial
def foo(x, y): return x + y
my_foo = partial(foo, y=50)
my_foo(100)
Out[433]: 150

rawDescription: Default argument to Python attribute that is a function


code:
def paraula(file,wordtofind):
    f = open(file,"r")
    text = f.read()
    f.close()
    count = 0
    index = text.find(wordtofind) # Returns the index of the first instance of the word
    while index != -1:
        count += 1
        text = text[index+len(wordtofind):] # Cut text starting from after that word
        index = text.find(wordtofind) # Search again
    return count

paraula (file,wordtofind)

rawDescription: Count how many times a word appears in a text file


code:
# bootstrap your django instance

from django.core.handlers.wsgi import WSGIHandler
application = WSGIHandler()

import sys
sys.argv += '-no web --wsgi=<module_name>.application --port=8081'.split()

from twisted.scripts.twistd import run
run()

rawDescription: How to use twistedweb with django on windows

description: Use twistedweb with django on windows


code:
def gamma_condition(self):
    temp = []
    maxValue = 0
    temp = [[item.groupIdentifier, JOIN_TRESHOLD - self.get_agent_distance_from_groupCenter(item.groupCenter)] for item in Group.Group.GroupList]
    for item in temp:
        maxValue = max(float(i) for i in item[1])
    if maxValue > 0:
        index = temp.index(maxValue)
        NearestGroupIdToJoin = temp[index][0]
        return NearestGroupIdToJoin
    else:
        return None

rawDescription: How to query on a list by list comprehension and min/max functionalities

description: Query on a list by list comprehension and min/max functionalities


code:
urlpatterns = patterns('',
    url('^tasks/', include('djcelery.urls')),
)

rawDescription: How can I use Ajax to check the status and result of a django-celery task?

description: Use Ajax to check the status and result of a django-celery task


rawDescription: Python modifying copy of array affects original?


code:
import wx

########################################################################
class GenericPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent, color):
        """Constructor"""
        wx.Panel.__init__(self, parent, size=(200, 100))
        self.SetBackgroundColour(color)

########################################################################
class MainPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent)

        left_sizer = wx.BoxSizer(wx.VERTICAL)
        for i in range(3):
            panel = GenericPanel(self, 'red')
            left_sizer.Add(panel, 0, wx.ALL, 5)

        top_right_sizer = wx.BoxSizer(wx.HORIZONTAL)
        for i in range(2):
            panel = GenericPanel(self, 'green')
            top_right_sizer.Add(panel, 0, wx.ALL, 5)

        bottom_right_sizer = wx.BoxSizer(wx.HORIZONTAL)
        for i in range(2):
            panel = GenericPanel(self, 'blue')
            bottom_right_sizer.Add(panel, 0, wx.ALL, 5)

        stack_sizer = wx.BoxSizer(wx.VERTICAL)
        stack_sizer.Add(top_right_sizer)
        stack_sizer.Add(bottom_right_sizer)

        main_sizer = wx.BoxSizer(wx.HORIZONTAL)
        main_sizer.Add(left_sizer)
        main_sizer.Add(stack_sizer)
        main_sizer.AddStretchSpacer(prop=1)
        self.SetSizer(main_sizer)

########################################################################
class MainFrame(wx.Frame):
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.Frame.__init__(self, None, title='Boxes', size=(700,400))
        panel = MainPanel(self)
        self.Show()

if __name__ == '__main__':
    app = wx.App(False)
    frame = MainFrame()
    app.MainLoop()

rawDescription: wxpython sizers expands issue

description: Wxpython sizers expands issue


code: mod = sys.modules[__module__]

rawDescription: How do I get the module instance for a class in Python?

description: Get the module instance for a class in Python


code:
import socket
timeout = 10
socket.setdefaulttimeout(timeout)

rawDescription: Setting timeouts to parse webpages using python lxml


code:
A,B,C = empty_matrices( 2, 3 ) # sets A, B, C as 3 2x2 matrices
A, = empty_matrices( 2, 1 ) # sets A as a 2x2 matrix

rawDescription: I'm looking for a neat way to return multiple matrices in python


code:
try:
    from cStringIO import StringIO
except ImportError:
    from StringIO import StringIO

class ConcatenatedFiles( object ):
    def __init__(self, file_objects):
        self.fds= list(reversed(file_objects))

    def read( self, size=None ):
        remaining= size
        data= StringIO()
        while self.fds and (remaining>0 or remaining is None):
            data_read= self.fds[-1].read(remaining or -1)
            if len(data_read)<remaining or remaining is None: #exhausted file
                self.fds.pop()
            if not remaining is None:
                remaining-=len(data_read)
            data.write(data_read)
        return data.getvalue()

rawDescription: Stream multiple files into a readable object in Python


code:
def myprint(times):
    print(times*"foobar")
foo = random.randint(1, 6)
myprint(foo)

rawDescription: How to make a function print many times on the same line, e.g. print('test')*3

description: Make a function print many times on the same line, e.g. print('test')*3


code:
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np

# create the sample data
# after http://matplotlib.org/examples/images_contours_and_fields/pcolormesh_levels.html
dx, dy = 0.05, 0.05
y, x = np.mgrid[slice(1, 5 + dy, dy),
                slice(1, 5 + dx, dx)]

z = np.sin(x) ** 10 + np.cos(10 + y * x) * np.cos(x)

fig, ax = plt.subplots(figsize=(6,6))
ax.axis('off')

# with a normalizer you can set the range against which you want to map
norm = mpl.colors.Normalize(vmin=-1, vmax=1)
# the cmap of your choice
cmap = plt.cm.jet

# create a 'mapper'
mapper = mpl.cm.ScalarMappable(norm=norm, cmap=cmap)

# map the data to a rgba array
rgba = mapper.to_rgba(z)

# make some adjustments to the alpha
rgba[:,:,3] = 0.5

# and plot
# there is no need for vmin, cmap etc keywords, its already rgba
ax.imshow(rgba)

rawDescription: Plot data with alpha values resulting in one color image - Matplotlib


code:
def make_ext(modname, pyxfilename):
    from distutils.extension import Extension
    return Extension(name=modname,
                     sources=[pyxfilename],
                     language='c++')

rawDescription: How do you tell pyximport to use the cython --cplus option?

description: Tell pyximport to use the cython --cplus option


code:
import pygame
from pygame.locals import *

Clock = pygame.time.Clock()
Display = pygame.display.set_mode((100,100))

Running = True

while Running:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            Running = False
            sys.exit()
            break

    Clock.tick(30)

rawDescription: Why Pygame wont QUIT properly?

description: Why Pygame wont QUIT properly


code:
def do_baz():
    messages = json.dumps({"main":"Condition failed on page baz"})
    session['messages'] = messages
    return redirect(url_for('.do_foo', messages=messages))

@app.route('/foo')
def do_foo():
    messages = request.args['messages']  # counterpart for url_for()
    messages = session['messages']       # counterpart for session
    return render_template("foo.html", messages=json.loads(messages))

rawDescription: Flask: redirect while passing arguments?

description: Flask: redirect while passing arguments


code:
class MyMixIn(object):
    def op_custom(self):
        print("foo")

class MyOperation(models.Model, MyMixIn):
    def op_normal(self):
        print("bar")

rawDescription: How to add new method to Django class from other modules?

description: Add new method to Django class from other modules


code:
with open('result_file', 'w') as file:
    for i in xrange(10000):
        result = somethingTakesTime()
        file.write(str(result), '\n')
        file.flush()

rawDescription: In Python, how to write strings in a file in a loop and before the loop stops, I can get the results runtimely?


code:
table_choice.add_argument(
    '-f', '--fast-table',
    dest='fast',
    help='fast table data',
    default=fast(),
    nargs='?',
    const='value_if_noarg'
)

rawDescription: Argparse: mutually exclusive groups with defaults


rawDescription: Python: replacing an element in an array without changing array shape


code:
dicta is dictb
dicta['A'] is dictb['A']
dicta['A'] is dicte['A']

rawDescription: Copying dictionaries in python

description: Copying dictionaries in python


code:
e = int(filename[-6:-4])
new_filename = '%s%02d-E%02d%s' % (filename[:-6], e*2-1, e*2, filename[-4:])

rawDescription: Renaming File Names Using Python

description: Renaming File Names Using Python


code:
from collections import OrderedDict
d=OrderedDict()
for i,j,k in array1:
   d.setdefault((i,j),[]).append(k)

[[i,j,k] for (i,j),k in d.items()]

rawDescription: Grouping items in a list based on their contents


code:
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

f = plt.figure()

plt.suptitle("Different vertical spacings")

gs1 = GridSpec(5, 2)
gs1.update(left=0.05, right=0.48, wspace=0)
ax1 = plt.subplot(gs1[0,0])
ax2 = plt.subplot(gs1[1, 0])
#Add the other subplots for left hand side

gs2 = GridSpec(5, 2)
gs2.update(left=0.55, right=0.98, wspace=0)
ax11 = plt.subplot(gs2[0,0])
ax12 = plt.subplot(gs2[1,0])
#Add the other subplots for right hand side

plt.show()

rawDescription: Separating some subplots but not others; Python, Matplotlib


code:
from subprocess import call # call runs an external program and waits for it to quit

for command in ("samtools merge filename.bam file1.sorted.bam file2.sorted.bam file3.sorted.bam file4.sorted.bam",
                "samtools index filename.bam",
                "samtools idxstats filename.bam > filename.txt",
                "samtools pileup -vcf path/filename.fa filename_sorted.bam"):
    # shell=True is so you can handle redirects like in the 3rd command
    call(command, shell=True)

rawDescription: How can I call/run a software by python?

description: Call/run a software by python


code:
agent_ids = agents_collection.find().distinct('_id')
agent_ids
agent_id2 = [str(id) for id in agents_collection.find().distinct('_id')]
agent_id2

rawDescription: How do I get a list of just the ObjectId's using pymongo?

description: Get a list of just the ObjectId's using pymongo


code:
# convert `y` to a numpy array for more convenient indexing
y = np.array(y)

# find unique group labels and their corresponding indices
label, idx = np.unique(x, return_inverse=True)

# make a list of arrays containing the y-values corresponding to each unique label
groups = [y[idx == i] for i, l in enumerate(label)]

# use `*` to unpack the list as a sequence of arguments to `stats.kruskal`
H, p = stats.kruskal(*groups)

print(H, p)
# 2.94545454545 0.22929927

rawDescription: Use groups in scipy.stats.kruskal similar to R cran kruskal.test


code:
def shear3(a, strength=1, shift_axis=0, increase_axis=1):
    if shift_axis > increase_axis:
        shift_axis -= 1
    res = numpy.empty_like(a)
    index = numpy.index_exp[:] * increase_axis
    roll = numpy.roll
    for i in range(0, a.shape[increase_axis]):
        index_i = index + (i,)
        res[index_i] = roll(a[index_i], -i * strength, shift_axis)
    return res

rawDescription: Shear a numpy array

description: Shear a numpy array


rawDescription: Select a subset of array based on inequality in Python


code:
def f(foo, bar):
    g(foo=foo)

rawDescription: Python dictionary simple way to add a new key value pair


rawDescription: Highlighting last data point in pandas plot


code:
ip_addr = re.findall(RE_ADDRESSES, response)
non_private = [ x for x in ip_addr if not re.match(RE_PRIVATE, x) ]
if non_private:
    return non_private[0]
# They're all private: return first one
elif ip_addr:
    return ip_addr[0]

mailserver = re.findall(...)[0]
return mailserver

rawDescription: Regex: How best to combine regex's with conditionals (in Python)?


rawDescription: Replace space with hyphen using regular expression


code:
from selenium import webdriver
driver = webdriver.Firefox()
driver.get('http://google.com')
print(driver.page_source)

rawDescription: Python WebDriver how to print whole page source (html)


code:
# When plotting initially, save the handle
plot_handle, = self.map.plot(x,y,'ro')
...

# When changing the data, change the xdata and ydata and redraw
plot_handle.set_ydata(new_y)
plot_handle.set_xdata(new_x)
self.figure.canvas.draw()

rawDescription: Redrawing plot on Basemap in Python

description: Redrawing plot on Basemap in Python


code:
from subprocess import Popen
process = Popen(['firefox', '-P', '-no-remote'])

rawDescription: How to execute python files separately as a python script?

description: Execute python files separately as a python script


code:
def closest_to_average(xs):
    avg = sum(xs)/len(xs)
    min_diff = None
    closest = None
    for i in xs:
        diff = abs(avg - i)
        if min_diff is None or diff < min_diff:
            min_diff = diff
            closest = i
    return closest

rawDescription: Python - Looping (Closest to Average)

description: Python - Looping (Closest to Average)


code:
mystr = '9,2,...'
tuple(map(ord, mystr))

rawDescription: Python ascii tuple

description: Python ascii tuple


code:
df = pd.DataFrame(dict(exp1=[1.2,2.1],exp2=[1.5,0.7]), index=["run1", "run2"])
df_min, df_max, df_mean = df.min(), df.max(), df.mean()
df_min.name, df_max.name, df_mean.name = "min", "max", "mean"
pd.concat((df.T, df_min, df_max, df_mean), axis=1).T

rawDescription: Calculate minimum value for each column of multi-indexed DataFrame in pandas


code: data[data.index.month == 2]

rawDescription: How to filter DateFrameGroupBy object by datetime index

description: Filter DateFrameGroupBy object by datetime index


code: plot(x1, y1, x2, y2, antialised=False)

rawDescription: Is it possible to alternate the use of *args and **kwargs?


code:
class ExternalFriends(models.Model):
    # columns

    class Meta:
        unique_together = ('external_user', 'name', 'external_account_id'),

rawDescription: In Django, how do I make uniques on 3 fields?


code:
from Crypto import RSA
from Crypto import Random

random_generator = Random.new().read
key = RSA.generate(1024, random_generator)
exportedKey = key.exportKey('PEM', 'my secret', pkcs=1)

rawDescription: PyCrypto: Generate RSA key protected with DES3 password


code:
# Run script on local machine.
def run_local_script(self, path, script):
    print("Path:"+path)
    with lcd(path):
        local('.' + script)

rawDescription: Python fabric is not executng script locally


rawDescription: matplotlib write text in the margin

description: Matplotlib write text in the margin


code:
from setuptools import setup

setup(
    # other arguments here...
    entry_points = {
        'console_scripts': [
            'foo = package.module:func',
            'bar = othermodule:somefunc',
        ],
    }
)

rawDescription: What's the best way to distribute python command-line tools?


code:
import pygame

pygame.init()
screen = pygame.display.set_mode((300, 300))
ck = (127, 33, 33)
size = 25
while True:
  if pygame.event.get(pygame.MOUSEBUTTONDOWN):
    s = pygame.Surface((50, 50))

    # first, "erase" the surface by filling it with a color and
    # setting this color as colorkey, so the surface is empty
    s.fill(ck)
    s.set_colorkey(ck)

    pygame.draw.circle(s, (255, 0, 0), (size, size), size, 2)

    # after drawing the circle, we can set the
    # alpha value (transparency) of the surface
    s.set_alpha(75)

    x, y = pygame.mouse.get_pos()
    screen.blit(s, (x-size, y-size))

  pygame.event.poll()
  pygame.display.flip()

rawDescription: Drawn surface transparency in pygame?

description: Drawn surface transparency in pygame


code:
from jinja2 import Template, DebugUndefined
template = Template("{{ var1 }}-{{ var2 }}", undefined=DebugUndefined)
rendered1 = template.render(var1=5) # "5-{{ var2 }}"
print(rendered1)
rendered2 = Template(rendered1).render(var2=6) # "5-6"
print(rendered2)

rawDescription: Multiple renders of jinja2 templates?

description: Multiple renders of jinja2 templates


code:
for result in my_results:
    print('n={}, a={}, t={}, g={}, c={}'.format(*result))

rawDescription: Labeling tuple variables in print statement


code:
from threading import Thread

t = Thread(target=http_server)
t.start()

rawDescription: Threading/Multiprocessing in Python

description: Threading/Multiprocessing in Python


code:
from matplotlib import pyplot
import math
pyplot.plot([x for x in range(100)],[math.exp(y) for y in range(100)] )
pyplot.xlabel('arbitrary')
pyplot.ylabel('arbitrary')
pyplot.title('arbitrary')

#pyplot.xscale('log')
pyplot.yscale('log')

pyplot.show()

rawDescription: how to visualize values on logarithmic scale on matplotalib?

description: Visualize values on logarithmic scale on matplotalib


code:
import numpy

matrix = numpy.asarray(matrix,dtype=numpy.float64) + 5.555

rawDescription: Python: speed of conversion of type of 3d matrix element


code:
import tornado.wsgi
from fanstatic import Fanstatic

from your_tornado_app import MainHandler # tornado.web.RequestHandler

app = tornado.wsgi.WSGIApplication([
    (r"/", MainHandler),
])
app = Fantastic(app)

if __name__ == '__main__':
    from wsgiref.simple_server import make_server

    server = make_server('127.0.0.1', 8080, app)
    server.serve_forever()

rawDescription: Integrating fanstatic with tornado web?

description: Integrating fanstatic with tornado web


code:
import collections
...
hash = collections.defaultdict(list)
r = stsize-mersize+1

for i in range(0, r):
    mer = st[i:i+mersize]
    hash[mer].append(i)

rawDescription: Fastest way to update a dictionary & check for keys


code:
#!/usr/local/bin/python2.7

marks = {} #a dictionary, it's a list of (key : value) pairs (eg. "Maths" : 34)
subjects = ["Tamil","English","Maths","Science","Social"] # this is a list

#here we populate the dictionary with the marks for every subject
for subject in subjects:
   marks[subject] = input("Enter the " + subject + " marks: ")

#and finally the calculation of the total and the average
total = sum(marks.itervalues())
average = float(total) / len(marks)

print ("The total is " + str(total) + " and the average is " + str(average))

rawDescription: how to calculate percentage in python

description: Calculate percentage in python


code:
import requests
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

related = MIMEMultipart('related')

submission = MIMEText('text', 'xml', 'utf8')
submission.set_payload(open('submission_set.xml', 'rb').read())
related.attach(submission)

document = MIMEText('text', 'plain')
document.set_payload(open('document.txt', 'rb').read())
related.attach(document)

body = related.as_string().split('\n\n', 1)[1]
headers = dict(related.items())

r = requests.post(url, data=body, headers=headers)

rawDescription: How to send a “multipart/related” with requests in python?

description: Send a “multipart/related” with requests in python


code:
import tkinter as tk # this is in python 3.4. For python 2.x import Tkinter
from PIL import Image, ImageTk

class ExampleApp(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.x = self.y = 0
        self.canvas = tk.Canvas(self, width=512, height=512, cursor="cross")
        self.canvas.pack(side="top", fill="both", expand=True)
        self.canvas.bind("<ButtonPress-1>", self.on_button_press)
        self.canvas.bind("<B1-Motion>", self.on_move_press)
        self.canvas.bind("<ButtonRelease-1>", self.on_button_release)

        self.rect = None

        self.start_x = None
        self.start_y = None

        self._draw_image()

    def _draw_image(self):
         self.im = Image.open('./resource/lena.jpg')
         self.tk_im = ImageTk.PhotoImage(self.im)
         self.canvas.create_image(0,0,anchor="nw",image=self.tk_im)

    def on_button_press(self, event):
        # save mouse drag start position
        self.start_x = event.x
        self.start_y = event.y

        # create rectangle if not yet exist
        #if not self.rect:
        self.rect = self.canvas.create_rectangle(self.x, self.y, 1, 1, fill="black")

    def on_move_press(self, event):
        curX, curY = (event.x, event.y)

        # expand rectangle as you drag the mouse
        self.canvas.coords(self.rect, self.start_x, self.start_y, curX, curY)

    def on_button_release(self, event):
        pass

if __name__ == "__main__":
    app = ExampleApp()
    app.mainloop()

rawDescription: Drawing rectangle using mouse events in Tkinter


code:
from selenium import webdriver

driver = webdriver.Firefox()
driver.get("http://www.python.org")
driver.implicitly_wait(10)
elem = driver.find_element_by_link_text("About")
driver.implicitly_wait(10)
elem.click()

rawDescription: Selenium - 'site' object has no attribute 'find_element_by_link_text'


code:
xidx = (raw[:,0]-xrange[0]).astype(int)
yidx = (raw[:,1]-yrange[0]).astype(int)

Z[xidx, yidx] = raw[:,2]

rawDescription: Converting a list of points to a numpy 2D array


code:
import numpy as np
import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5, 6]
y = [1.2, 1.2, 2.1, 2.1, -4.1, -4.1]

plt.plot(x, y, 'm--')

pair_x_array = np.reshape(x, (-1, 2))
pair_y_array = np.reshape(y, (-1, 2))
for i, pair_x in enumerate(pair_x_array):
    pair_y = pair_y_array[i]
    plt.plot(pair_x, pair_y, 'm', linewidth=3)

plt.show()

rawDescription: Two point segment plot in matplotlib

description: Two point segment plot in matplotlib


code: subnet: "{{ deployment|hash|int(base=16) % 255 }}"

rawDescription: Hash deployment environment to subnet

description: Hash deployment environment to subnet


code:
with open("first.txt","r") as input:
    with open("last.txt","w") as output:
        for line in input:
            line = line.strip() # clear white space
            try:
                int(line) #is this a number ?
            except ValueError:
                output.write(line + "\n")

rawDescription: Removing page numbers from a .txt file in Python


code:
def replstr(orig, old, new):
    i = 0
    output = ''
    temp = ''
    for c in orig:
        if c == old[i]:
            i += 1
            temp += c
        else:
            i = 0
            if temp:
                output += temp
                temp = ''
            output += c
        if len(temp) == len(old):
            output += new
            temp = ''
            i = 0
    else:
        if temp:
            output += temp

rawDescription: Python - replace multiple characters without .replace()


code:
class MyThing( object ):
    def __init__( self, theInstance ):
        self.ec2_instance = theInstance

rawDescription: Cast a class instance to a subclass

description: Cast a class instance to a subclass


code:
class QueueView:
    def __init__(self, joinable):
        self.joinable = joinable
        self.other = collections.deque()
    def get(self, block=True, timeout=None):
        if self.other:
            return self.other.popleft()
        self.joinable.get(block, timeout)
    def __contains__(self, item):
        if item in self.other:
            return True
        try:
            while True:
                o = self.joinable.get(block=False)
                self.other.append(o)
        except Queue.Empty:
            pass
        return item in self.other

rawDescription: 'JoinableQueue' object is not iterable

description: 'JoinableQueue' object is not iterable


code:
def add_sparse_vectors(v1, v2):
    combined_dict = dict(Counter(lst1)+Counter(lst2))
    key_val_pairs = [str(k)+":"+str(v) for k,v in combined_dict.items()]
    output = "{" + ", ".join(key_val_pairs) + "}"
    return output

rawDescription: Removing spaces from dictionaries key-value pairs


code:
r.expr(doc).do(lambda d: # doc as input
  r.do(
    [d['id'], r.uuid(d['id'].coerce_to('string'))],
    d.without('id').values(),
    lambda x, y:
      # x is the pair
      # y is the values of bar and foo
      ...))

rawDescription: how to unpack array into variables

description: Unpack array into variables


code:
class Item1(Item):
    location = Field()
    salary = Field()
    job_description = Field()
    more_job_description = Field()
    others = Field()
    title = Field()
    link = Field()
    job_type = Field()

class Item2(Item):
    company = Field()
    about_company = Field()

class SQLAlchemyPipeline(object):

    def process_item(self, item, spider):
        if isinstance(item, Item1):
            save_in_table1
        if isinstance(item, Item2):
            save_in_table2

    def process_item2(self, item, spider):
        item1 = item
        item2 = item1['item2']
        job_id = save_in_table1(item1)
        save_in_table2(item2, job_id)

rawDescription: Is it possible to scrape data to two different database tables?


code:
column_widths = []
for row in data:
    for i, cell in enumerate(row):
        if len(column_widths) > i:
            if len(cell) > column_widths[i]:
                column_widths[i] = len(cell)
        else:
            column_widths += [len(cell)]

for i, column_width in enumerate(column_widths):
    worksheet.column_dimensions[get_column_letter(i+1)].width = column_width

rawDescription: Python openpyxl column width size adjust


code:
callable, args, state, _, _ = x.__reduce_ex__(2)
y = callable(*args)
if deepcopying:
    state = deepcopy(state)
y.__dict__.update(state)
return y

rawDescription: Default behavior of copy module on user-defined classes


code:
def max_divisors(my_list):
    #Takes each number in list
    n=my_list

    # NEW LINES: initialise max_divs and max_divs_elem vars
    max_divs = 0
    max_divs_elem = 0

    for k in n:
        #calculate how many divisors each number has
        i=2
        count=2
        while(i**2 < k):
            if(k%i==0):
                count+=2
            i+=1
        count+=(1 if i**2==k else 0)
        # update  max_divs and max_divs_elem if needed
        if max_divs < count:
            max_divs = count
            max_divs_elem = k
        print(k,"has",count, "divisors")

    # NEW LINES: print values of max_divs, max_divs_elem
    print(max_divs_elem, "has maximal dividers:", max_divs)
print(max_divisors([100,5, 6]))

rawDescription: How to return the number that has maximum value of divisor?

description: Return the number that has maximum value of divisor


code: allowed_domains = ["reddit.com", "imgur.com"]

rawDescription: Stuck with scrapy following imgur links from subreddits


code:
labels=[' ','Millennials','Generation X','Baby Boomers','Tradionalists']
a['category']  = pd.cut(a['age'], bins=[1, 16,46,52,71, 200],labels=labels)
a

rawDescription: Making python lambda func work inside apply method in Pandas Dataframe


code:
from django.contrib.auth import authenticate, login, logout
user = authenticate(username=request.POST['username'], password=request.POST['password'])
if user is not None:
    if user.is_active:
        login(request, user)
        redirect('logged_in_url')
    else:
        redirect('user_not_active_url')
else:
    redirect('bad_username_or_password_url')

rawDescription: Django CreateView Auto Login

description: Django CreateView Auto Login


code:
def save(self):
    from django.template.defaultfilters import slugify

    if not self.slug:
        self.slug = slugify(self.title)

    super(Your_Model_Name,self).save()

rawDescription: Is there a way to define which fields in the model are editable in the admin app?


code: self.mySplitter.setStyleSheet("QSplitter::handle { image: none; }")

rawDescription: Remove QSplitter line between widgets

description: Remove QSplitter line between widgets


code:
links = Link.objects.select_related().annotate(votes=Count('vote'))
for link in links:
    delta_in_hours = (int(datetime.now().strftime("%s")) - int(link.created.strftime("%s"))) / 3600
    link.popularity = ((link.votes - 1) / (delta_in_hours + 2)**1.5)

links = sorted(links, key=lambda x: x.popularity, reverse=True)

rawDescription: Django: Applying Calculations To A Query Set


code:
from __future__ import division
import cv2

img = cv2.imread('1.jpg')

screen_res = 1280, 720
scale_width = screen_res[0] / img.shape[1]
scale_height = screen_res[1] / img.shape[0]
scale = min(scale_width, scale_height)
window_width = int(img.shape[1] * scale)
window_height = int(img.shape[0] * scale)

cv2.namedWindow('dst_rt', cv2.WINDOW_NORMAL)
cv2.resizeWindow('dst_rt', window_width, window_height)

cv2.imshow('dst_rt', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

rawDescription: Python - OpenCV - imread - Displaying Image


code:
import numpy as np
import matplotlib.pyplot as plt

N = 80
bottom = 8
max_height = 4

theta = np.linspace(0.0, 2 * np.pi, N, endpoint=False)
radii = max_height*np.random.rand(N)
width = (2*np.pi) / N

ax = plt.subplot(111, polar=True)
bars = ax.bar(theta, radii, width=width, bottom=bottom)

# Use custom colors and opacity
for r, bar in zip(radii, bars):
    bar.set_facecolor(plt.cm.jet(r / 10.))
    bar.set_alpha(0.8)

plt.show()

rawDescription: Circular Histogram for Python

description: Circular Histogram for Python


code:
hex(ord(u'°'))
hex(ord(u'ç'))

rawDescription: How can I get unicode characters from a URL parameter?

description: Get unicode characters from a URL parameter


code:
import time
print("something")
time.sleep(5.5)    # pause 5.5 seconds
print("something")

rawDescription: Correct way to pause Python program

description: Correct way to pause Python program


code:
import ipyparallel as ipp
c = ipp.Client()
c.shutdown(hub=True)

rawDescription: How to stop an IPython cluster without the ipcluster command

description: Stop an IPython cluster without the ipcluster command


rawDescription: XPATH: Specific word in paragraph

description: XPATH: Specific word in paragraph


code:
pattern = re.compile(u'<\/?\w+\s*[^>]*?\/?>', re.DOTALL | re.MULTILINE | re.IGNORECASE | re.UNICODE)
text = pattern.sub(u" ", text)

rawDescription: Regular Expression to remove html tags from a string in Python


code: dates_table.setColumnSelectionInterval( 0, 0 )

rawDescription: Jython - anyone got an idea why this Action isn't doing what I want?


code:
def askIP():
    TheIP = raw_input('Okay, what is it? E.X 112.13.141.9: ')
    if AskYesNo('Are you sure '+TheIP+' is the correct IP? You will not be able to change this later!!') != True:
        print('Ok, get it right this time!');
        return askIP()
    else:
        return TheIP

rawDescription: Asking "are you sure" then letting user correct not working


code:
def __init__(self, group=None, target=None, name=None,
             args=(), kwargs=None, *, daemon=None):
    assert group is None, "group argument must be None for now"

rawDescription: Python 3 get all thread names in group

description: Python 3 get all thread names in group


code:
# Copyright (c) 2006 by Seo Sanghyeon
# 2006-07-13 sanxiyn Created
# 2006-07-19 sanxiyn Added unidata_version, normalize
# Modified 2011 - Greg Gauthier - To provide needed functionality for rdflib
#                                 and other utilities, in IronPython 2.7.0

unidata_version = '3.2.0'

# --------------------------------------------------------------------
# Normalization

from System import String
from System.Text import NormalizationForm

def normalize(form, string):
    return String.Normalize(string, _form_mapping[form])

_form_mapping = {
    'NFC': NormalizationForm.FormC,
    'NFKC': NormalizationForm.FormKC,
    'NFD': NormalizationForm.FormD,
    'NFKD': NormalizationForm.FormKD,
}

# --------------------------------------------------------------------
# Character properties

from System.Globalization import CharUnicodeInfo

def _handle_default(function):
    def wrapper(unichr, default=None):
        result = function(unichr)
        if result != -1:
            return result
        if default is None:
            raise ValueError()
        return default
    return wrapper

decimal = _handle_default(CharUnicodeInfo.GetDecimalDigitValue)
digit = _handle_default(CharUnicodeInfo.GetDigitValue)
numeric = _handle_default(CharUnicodeInfo.GetNumericValue)

def category(unichr):
    uc = CharUnicodeInfo.GetUnicodeCategory(unichr)
    return _category_mapping[int(uc)]

_category_mapping = {
    0: 'Lu',
    1: 'Ll',
    2: 'Lt',
    3: 'Lm',
    4: 'Lo',
    5: 'Mn',
    6: 'Mc',
    7: 'Me',
    8: 'Nd',
    9: 'Nl',
    10: 'No',
    11: 'Zs',
    12: 'Zl',
    13: 'Zp',
    14: 'Cc',
    15: 'Cf',
    16: 'Cs',
    17: 'Co',
    18: 'Pc',
    19: 'Pd',
    20: 'Ps',
    21: 'Pe',
    22: 'Pi',
    23: 'Pf',
    24: 'Po',
    25: 'Sm',
    26: 'Sc',
    27: 'Sk',
    28: 'So',
    29: 'Cn',
}

# added for rdflib/ironpython
def decomposition(unichr):
    return String.Normalize(unichr.ToString(), NormalizationForm.FormD)

rawDescription: Is there a unicodedata module for IronPython?


code:
NS = 'urn:...'

class Attr(ComplexModel):
    __namespace__ = NS
    _type_info = [
        ('ID', XmlAttribute(UnsignedInteger32)),
    ]

class ModifyRequest(ComplexModel):
    __namespace__ = NS
    _type_info = [
        ('returnData', XmlAttribute(Unicode(values=['everything', 'something', 'anything', 'etc']))),
        ('attr', Attr),
        ('data', AnyXml),
    ]

class SomeService(ServiceBase):
    @rpc(ModifyRequest, _body_style='bare')
    def modifyRequest(ctx, request):
        pass

rawDescription: Building a service for a given request

description: Building a service for a given request


code:
from operator import itemgetter
sorted(map(itemgetter(1,-1),lists),key=itemgetter(-1))

rawDescription: Python: Sorting and printing lists within lists


code:
from pylab import *

figure(0)
plot([1,2,3])

figure(1)
plot([10, 20, 30])

figure(0)
plot([4, 5, 6])

figure(1)
plot([40, 50, 60])

show()

rawDescription: Python with matplotlib - drawing multiple figures in parallel


rawDescription: Clone an image in cv2 python

description: Clone an image in cv2 python


code:
spider = FollowAllSpider(domain=domain)
spider.start_urls = ['http://google.com']

rawDescription: Setting Scrapy start_urls from a Script

description: Setting Scrapy start_urls from a Script


code:
import os

pyc_files = []
py_files = []

for root, dirnames, filenames in os.walk('.'):
    for filename in filenames:
        if filename.endswith('.pyc'):
            pyc_files.append(os.path.join(root, filename))
        elif filename.endswith('.py'):
            py_files.append(os.path.join(root, filename))

for py_file in py_files:
    if py_file + 'c' not in pyc_files:
        os.remove(py_file)

rawDescription: Delete all .py files which dont have a corresponding .pyc file


code:
jStr = "aabbbbbaabbbbb"
count = 1
res= "" # strings are immutable so we have to create a new string.
for s in jStr:
    if count == 5 and s == "b": # if count is 5 we have our fifth "b", change to "c" and reset count
        res +=  "c"
        count = 1
    elif s == "b": # if it is a "b" but not the fifth just add b to res and increase count
        count += 1
        res += "b"
    else:           # else it is not a "b", just add to res
        res += s
print(res)
aabbbbcaabbbbc

rawDescription: How can I replace the nth occurence of a substring/character within a string? [Python 3]

description: Replace the nth occurence of a substring/character within a string? [Python 3]


code:
import datetime
import pylab as plt

# Some sample data
X = [datetime.datetime(2000, 3, 2, n) for n in xrange(9,13)]
Y = [4,8,3,2]

# Set the limits
start_time = datetime.datetime(2000, 3, 2, 7)
end_time = datetime.datetime(2000, 3, 2, 14)

plt.bar(X, Y, align='center',width=.015)
plt.gcf().autofmt_xdate()
plt.xlim(start_time, end_time)
plt.show()

rawDescription: pyplot distance between axis and plot

description: Pyplot distance between axis and plot


code:
TIMEOUT = 5.0 # timeout in seconds
pythonwhois.net.socket.setdefaulttimeout(TIMEOUT)
pythonwhois.get_whois("example.com")

rawDescription: How to avoid program freezing when connecting to server

description: Avoid program freezing when connecting to server


code:
if glob.glob(pattern):
    print('There are some files matching the pattern.')
else:
    print('No files matching the pattern.')

rawDescription: glob on non existant file with patter matching

description: Glob on non existant file with patter matching


code:
url = "some url of login page"
payload = {'username': 'p05989', 'password': '123456'}
with requests.session() as s:
    # fetch the login page
    s.get(url)

    # post to the login form
    r = s.post(url1, data=payload)
    print(r.text)

rawDescription: how to use python to login page which requires session id responded by server on first request?

description: Use python to login page which requires session id responded by server on first request


code:
def SysInfo():
  oldstdout = sys.stdout
  sys.stdout = open("sysinfo.txt","w")
  psutil.test()
  sys.stdout.close()
  sys.stdout = oldstdout
SysInfo()

rawDescription: writing function to file, getting none

description: Writing function to file, getting none


code:
def walkPath(fn):
    def wrapper(outside, *args, **kwargs):
        for dirname, dirnames, filenames in os.walk(args[0]):
            for filename in filenames:
                outside = fn(outside, filename, dirname, *args, **kwargs)
        return outside
    return wrapper

@walkPath
def countL(outside, filename, dirname, extension = '.wrd'):
    if (filename[-4:]  == extension):
        with open(os.path.join(dirname, filename), 'r') as input:
            data = input.readlines()
        for i in range(len(data)):
            temp = data[i].split()
            if (int(temp[1]) - int(temp[0]) > outside):
                outside = int(temp[1]) - int(temp[0])
    return outside

rawDescription: Walking Path in Python using a Decorator


code:
for g in genres:
    self.genreMenu.add_command(label=g,
        command=lambda genre=g: self.change_genre(genre))

rawDescription: Python: Tkinter: Trying to Populate a Menu Dynamically With a Set


code:
import pandas as pd
import difflib

df = pd.DataFrame({'Fruit': ['banana', 'apple', 'mango', 'melon'],
                   'Rank': [1, 2, 3, 4]})

top = df['Fruit'][df.Rank == 1][0]
df['similarity_score'] = df['Fruit'].apply(lambda x: difflib.SequenceMatcher(
                                           None, top, x).ratio())

rawDescription: Python dataframes

description: Python dataframes


code:
import collections

# Produce a Counter mapping each point to how many times it appears.
counts = collections.Counter(zip(X_List, Y_List))

# Find the point with the highest count.
MostCommonPoint = max(counts, key=counts.get)

rawDescription: Python: find most common element in corresponding two lists


rawDescription: Pandas get date from datetime stamp

description: Pandas get date from datetime stamp


code:
import math

from Tkinter import *

def Solar_Param():
   d = Interface.get()
   S_E = 1367*(1 + 0.0334 * math.cos(((math.pi*360)/180) * (d - 2.7206) / 365.25))

   result_label.configure(text=S_E)
   return S_E

nGui = Tk()
Interface = IntVar()

nGui.title("Solar Calculations")

nlabel = Label(text = "User Interface for Solar Calculation")
nlabel.pack()

nbutton = Button(nGui, text = "Calculate", command = Solar_Param).pack()
nEntry = Entry(nGui, textvariable = Interface).pack()

result_label = Label(nGui, text="")
result_label.pack(side="top", fill="x")

nGui.mainloop()

rawDescription: Store User Value in an Entry box to calculate a value in Tkinter


code:
from matplotlib.font_manager import findSystemFonts
import random
from PIL import ImageFont, Image, ImageDraw
import numpy
from mpl_toolkits.mplot3d.axes3d import Axes3D
import matplotlib.pyplot as plt

def rand_font(fonts=[], fontpaths=None, fontext='ttf', font_encoding='', min_size=24, max_size=36):
    if fonts == []:
        fonts = findSystemFonts(fontpaths, fontext)
    requested_font = fonts[random.randint(0, len(fonts)-1)]
    font_size = random.randint(min_size, max_size)
    return ImageFont.truetype(requested_font, font_size, encoding=font_encoding)

def create_captcha(text):
    def _rand_color():
        colors = ['red', 'orange', 'purple', 'green', 'yellow']
        return colors[random.randint(0, len(colors)-1)]

    # First font just gets the general offsets
    font = rand_font()
    text_width, text_height = font.getsize(text)

    # Dont draw text here first
    img = Image.new("L", (text_width * 3, text_height * 3), "white")
    draw = ImageDraw.Draw(img)

    fig = plt.figure(figsize=(12, 8))
    axes = Axes3D(fig)

    # Do this way if you want random fonts AND colors
    #=================
    prev_x = 0
    for character in text:
        cfont = rand_font()
        char_wid, char_height = cfont.getsize(character)
        draw.text((prev_x+text_width, text_height), character, font=cfont)

        X, Y = numpy.meshgrid(range(prev_x+text_width, prev_x+text_width+char_wid),
                              range(text_height, text_height+char_height))
        Z = 1 - numpy.asarray(img.crop((prev_x+text_width, text_height,
                                        prev_x+text_width+char_wid,
                                        text_height+char_height))) / 255
        axes.plot_wireframe(X, -Y, Z, rstride=1, cstride=1, color=_rand_color())

        prev_x += char_wid # trying to offset the characters by an x value so they dont overlap
    #=================

    # Do this way if you want just random fonts on each letter all one color
    #=================
    prev_x = 0
    for character in text:
        cfont = rand_font()
        char_wid, char_height = cfont.getsize(character)
        draw.text((prev_x+text_width, text_height), character, font=cfont)

        prev_x += char_wid # trying to offset the characters by an x value so they dont overlap

    X, Y = numpy.meshgrid(range(img.size[0]), range(img.size[1]))
    Z = 1 - numpy.asarray(img) / 255
    axes.plot_wireframe(X, -Y, Z, rstride=1, cstride=1, color=_rand_color())
    #=================

    axes.set_zlim((-3, 3))
    axes.set_xlim((text_width * 1.1, text_width * 1.9))
    axes.set_ylim((-text_height * 1.9, -text_height* 1.1))
    axes.set_axis_off()
    axes.view_init(elev=60, azim=-90)
    plt.show()

create_captcha('TEST')

rawDescription: Creating 3D captcha with different fonts


code:
import tkinter as tk
from tkinter import *

class Color:
    def __init__(self, r, g, b):
        self.r = r
        self.g = g
        self.b = b

def requestColor(default=Color(0, 0, 0)):

    # this will be modified later by the save command
    result = Color(default.r, default.g, default.b)

    colorGUI = tk.Tk()
    colorGUI.title('Select Color')

    rLabel = Label(colorGUI, text='R: ', anchor=tk.E)
    gLabel = Label(colorGUI, text='G: ', anchor=tk.E)
    bLabel = Label(colorGUI, text='B: ', anchor=tk.E)

    rEntry = Entry(colorGUI)
    gEntry = Entry(colorGUI)
    bEntry = Entry(colorGUI)

    def saveCommand():
        # set the new values
        result.r = int(rEntry.get())
        result.g = int(gEntry.get())
        result.b = int(bEntry.get())
        colorGUI.destroy()

    def quitCommand():
        # keep the default values
        colorGUI.destroy()

    saveButton = Button(colorGUI, text='SAVE', command=saveCommand)
    quitButton = Button(colorGUI, text='CANCEL', command=quitCommand)

    rEntry.insert(0, default.r)
    gEntry.insert(0, default.g)
    bEntry.insert(0, default.b)

    rLabel.grid(row=0, column=0, sticky=tk.E)
    rEntry.grid(row=0, column=1)
    gLabel.grid(row=1, column=0, sticky=tk.E)
    gEntry.grid(row=1, column=1)
    bLabel.grid(row=2, column=0, sticky=tk.E)
    bEntry.grid(row=2, column=1)
    quitButton.grid(row=3, column=0, sticky=tk.E+tk.W)
    saveButton.grid(row=3, column=1, sticky=tk.E+tk.W)

    colorGUI.mainloop()

    return result

color = requestColor()

print('Color(%s, %s, %s)' % (color.r, color.g, color.b))

rawDescription: Return from inside a function defined inside another function in Python


code:
from bokeh.plotting import figure
from bokeh.client import push_session
from bokeh.io import curdoc
from bokeh.models import ColumnDataSource, CustomJS, BoxSelectTool, Range1d, Rect

source = ColumnDataSource(data=dict(x=[], y=[], width=[], height=[]))

callback = CustomJS(args=dict(source=source), code="""

        var data = source.get('data');
        var geometry = cb_data['geometry'];

        var width = geometry['x1'] - geometry['x0'];
        var height = geometry['y1'] - geometry['y0'];
        var x = geometry['x0'] + width/2;
        var y = geometry['y0'] + height/2;

        data['x'].push(x);
        data['y'].push(y);
        data['width'].push(width);
        data['height'].push(height);

        source.trigger('change');
    """)

box_select = BoxSelectTool(callback=callback)

p = figure(plot_width=400,
           plot_height=400,
           tools=[box_select],
           title="Select Below",
           x_range=Range1d(start=0.0, end=1.0),
           y_range=Range1d(start=0.0, end=1.0))

rect = Rect(x='x',
            y='y',
            width='width',
            height='height',
            fill_alpha=0.3,
            fill_color='#009933')

p.add_glyph(source, rect, selection_glyph=rect, nonselection_glyph=rect, name="selectionbox")

session = push_session(curdoc())

def toolEventsCallback(attr, old, new):
    print("callback", new)
    x0 = new[0]['x0']
    x1 = new[0]['x1']
    print("x0=%f  x1=%f" % (x0, x1))

p.tool_events.on_change("geometries", toolEventsCallback)

session.show()
session.loop_until_closed()

rawDescription: How can I get data from a ColumnDataSource object which is synchronized with local variables of Bokeh's CustomJS function?

description: Get data from a ColumnDataSource object which is synchronized with local variables of Bokeh's CustomJS function


code:
element = browser.find_element_by_xpath("//body")
element.send_keys(Keys.CONTROL, 'p')

rawDescription: Performing browser UI operations with Selenium and Python


code:
import mimetypes
...
mime = mimetypes.guess_type(file)

rawDescription: How can I detect if a file is binary (non-text) in python?

description: Detect if a file is binary (non-text) in python


code:
import unittest

def testFailed():
    print("test failed")

class T(unittest.TestCase):
    def test_x(self):
        try:
            self.assertTrue(False)
        except AssertionError:
            testFailed()
            raise

if __name__ == "__main__":
    suite = unittest.defaultTestLoader.loadTestsFromTestCase(T)
    unittest.TextTestRunner().run(suite)

rawDescription: run code when unit test assert fails

description: Run code when unit test assert fails


code:
df = pd.read_csv("file1.csv", dtype={"id": int, "attr2": str})
df
df.dtypes

rawDescription: How do I prevent pandas from recasting my integer values to floats?

description: Prevent pandas from recasting my integer values to floats


rawDescription: How to write a lambda function that is conditional on two variables (columns) in python

description: Write a lambda function that is conditional on two variables (columns) in python


code:
def connect_to(db, *args):
    if db == "MySQL":
        return MySQL(*args)
    elif db == "Oracle":
        return Oracle(*args)
    else:
        raise ValueError("unknown database type: %r" % db)

rawDescription: Most Pythonic way to handle splitting a class into multiple classes


code:
from tkinter import *

import time

class Application:
    def __init__(self):
        self.fen = Tk()
        self.fen.title('Rom-rom-roooooom')
        self.butt1 = Button(self.fen, text = ' Quit ', command = self.fen.quit)
        self.can1 = Canvas(self.fen, width = 300, height = 300, bg = 'ivory')
        self.can1.grid(row = 1)
        self.butt1.grid(row = 2)
        self.fen.bind("<Button-1>", self.create_obj)
        self.fen.mainloop()

    def create_obj(self, event):
        d = self.can1.create_oval(150,150, 170, 170, fill='red', width = 2)
        time.sleep(3)
        self.can1.delete(d)

appp = Application()

rawDescription: Delete an instance of the object

description: Delete an instance of the object


rawDescription: Python - sort a list of nested lists

description: Python - sort a list of nested lists


code:
import imaplib
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('myusername@gmail.com', 'mypassword')
mail.list()
# Out: list of "folders" aka labels in gmail.
mail.select("inbox") # connect to inbox.

result, data = mail.search(None, "ALL")

ids = data[0] # data is a list.
id_list = ids.split() # ids is a space separated string
latest_email_id = id_list[-1] # get the latest

result, data = mail.fetch(latest_email_id, "(RFC822)") # fetch the email body (RFC822) for the given ID

raw_email = data[0][1] # here's the body, which is raw text of the whole email
# including headers and alternate payloads

rawDescription: Receve replys from Gmail with smtplib - Python


code: balance = {item.Currency: item.Amount for item in response.Balance}

rawDescription: Parsing Suds SOAP complex data type into Python dict


code:
#!/usr/bin/python
# _*_ coding: utf-8 _*_
import wx

class wxappsubclass(wx.App):
  def OnInit(self):
    frame=wxframesubclass(None, -1, 'MyName')
    frame.Show(True)
    return True

class wxframesubclass(wx.Frame):
  def __init__(self, parent, id, title):
    wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, size=(320, 240))
    self.panel=panel1(self)
    menubar=wx.MenuBar()
    menufile=wx.Menu()
    ExitItem=menufile.Append(wx.NewId(), '&Exit\tCtrl+Q', "Exit")
    menubar.Append(menufile, '&File')
    self.SetMenuBar(menubar)

    ## BINDING ##
    self.Bind(wx.EVT_MENU, self.CloseProgramFromFrame, ExitItem)
    self.Bind(wx.EVT_BUTTON, self.CloseProgramFromFrame, self.panel.ExitButton)

  def CloseProgramFromFrame(self, event):
    self.Close(True)

class panel1(wx.Panel):
  def __init__(self, parent):
    wx.Panel.__init__(self, parent, -1)
    ID_EXIT_BUTTON=wx.NewId()
    self.ExitButton=wx.Button(self, wx.NewId(), label="Exit")

if __name__ == '__main__':
  app=wxappsubclass()
  app.MainLoop()

rawDescription: wxPython: binding multiple widgets - Frame e Panel - to the same handler

description: WxPython: binding multiple widgets - Frame e Panel - to the same handler


code: request.get('submitedform', 0)

rawDescription: Plone : Check if a form was submitted

description: Plone : Check if a form was submitted


rawDescription: regular expression to match two digits numbers in a random string without matching 3 or more digit numbers

description: Regular expression to match two digits numbers in a random string without matching 3 or more digit numbers


code:
b = [[-1, 2], [-2, 1], [0, 4], [3, 5], [-3, 1], [-10, -7], [6, 8]]
b.sort()
result = []
current = b[0]
for interval in b[1:]:
    if current[1] >= interval[0]:
        current[1] = interval[1]
    else:
        result.append(current)
        current = interval
result.append(current)
print(result)  # [[-10, -7], [-3, 5], [6, 8]]

rawDescription: How to merge some

description: Merge some


code:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-s', type=int)
parser.add_argument('-p', type=int, nargs='*')
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('-r', action='store_true')
group.add_argument('-w', action='store_true')
group.add_argument('-c', action='store_true')
parser.parse_args("-s 1 -p 0 1 2 3 -r".split())

rawDescription: How to use argparse to grab command line arguments in Python?

description: Use argparse to grab command line arguments in Python


rawDescription: .wav file doesn't play any sounds

description: .wav file doesn't play any sounds


code:
import numpy as np
import numpy.random
import matplotlib.pyplot as plt

a=256*np.random.rand(64,64)

f0=plt.figure()
plt.imshow(a,cmap=plt.gray())
plt.suptitle("imshow")

f1=plt.figure()
plt.figimage(a,cmap=plt.gray())
plt.suptitle("figimage")

plt.show()

rawDescription: matplotlib plot small image without resampling

description: Matplotlib plot small image without resampling


code:
view_functions = [news_view, foo_view, bar_view]

for view in ['news', 'foo', 'bar']:
  for translation in translations[view]:
     app.add_url_rule('/{}/'.format(translation), view, view_functions[view])

rawDescription: Multilingual urls in flask

description: Multilingual urls in flask


code:
for count in range(1,200):
    df=pd.merge(df, dforig, on='ID', suffixes=(count, count+1), copy=True, how='left')
    df=df.rename(columns={'VARIABLE'+str(count):'VARIABLE' + str(count-2),
                          'VARIABLE'+str(count+1):'VARIABLE'})

rawDescription: loop over columns with different names

description: Loop over columns with different names


code: df2 = pd.DataFrame(df.transpose().apply(lambda x: [', '.join(x)], axis=1))

rawDescription: Using apply on a column

description: Using apply on a column


code:
import numpy as np

arr = np.random.randint(1, 200000, (180000, 47))

np.save('test.npy', arr)  # 250 milisec on my system
loaded_arr = np.load('test.npy')  # 55 milisec on my system

# alternatively using text based files:
np.savetxt('test.txt', arr)  # 19 seconds
loaded_arr = np.loadtxt('test.txt', dtype=np.int)  # 32 seconds

rawDescription: Issue reading arrays from a .txt file

description: Issue reading arrays from a .txt file


code: inp = int(inputbox.ask(screen, 'Message')) #inp will equal whatever the input is

rawDescription: Using text inputs in pygame

description: Using text inputs in pygame


code: samp.apply(lambda x: vincenty((x['biz_lat'],x['biz_lon']), (x['id_lat'],   x['id_lon'])).miles, axis=1)

rawDescription: Distance calculation in Geopy

description: Distance calculation in Geopy


code:
# check nested json
import collections
from functools import reduce
import datetime

#this is json from GET session
myjson = {
    "accessed": "Wed, 31 Jul 2013 13:03:38 GMT",
    "created": "Wed, 31 Jul 2013 13:03:38 GMT",
    "dnUrls": [
        "http://135.86.180.69:8580/ucc/api/v1/session/dns/50000"
    ],
    "expires": "Wed, 31 Jul 2013 13:03:48 GMT",
    "modified": "Wed, 31 Jul 2013 13:03:38 GMT",
    "name": "KW50000",
    "person": {
        "employeeId": "KW50000",
        "firstName": "KW50000",
        "lastName": "Dev5"
    },
    "previewRedirect": {
        "destination": "",
        "enabled": False,
        "setupEnabled": False
    }
}

# returns dictionary with key= fieldname, value = result,
# either True (Test Pass), False (test Failed)
def check_json(obj, checker):
    """params json to check, template comparison object
       returns dictionary of keys to pass/fail values"""

    result = {}
    for k, (mFlag, chk) in checker.items():
        if not k in obj:
            result[k] = not mFlag
        elif isinstance(chk, collections.Callable):
            result[k] = chk(obj[k])
        elif(isinstance(chk, collections.Mapping)):
            result[k] = check_json(obj[k], chk)
        else:
            result[k] = chk == obj[k]
    return result

    def isDate(s):
        try:
            datetime.datetime.strptime(s, '%a, %d %b %Y %H:%M:%S GMT')
            return True
        except Exception:
            print("conversion to date failed")
            return False

#checker object made up of dictionary with string key and tuple value (a pair)
#tuple first filed is flag indicating whether key is mandatory or not.
# tuple 2nd key is value to expect or a checker function
checker = {
    "accessed": (True, check_json.isDate),
    "created": (True, check_json.isDate),
    "dnUrls": (True, lambda l: (reduce(lambda c, v:\
                     c + (1 if v.startswith('http://') else -1), l, 0) > 0)),
    "expires": (True, check_json.isDate),
    "modified": (True, check_json.isDate),
    "name": (True, "KW50000"),
    "person": (True, {
        "employeeId": (True, lambda s: s.isalnum()),
        "firstName": (False, True),
        "lastName": (False, True)
    }),
    "previewRedirect": (True, {
        "destination": (False, True),
        "enabled": (True, lambda s: type(s) is bool),
        "setupEnabled": (False, lambda s: type(s) is bool)
    })
}

def with_and(v1, v2):
    return functools.reduce(with_and, v2.values(), v1)\
                    if isinstance(v2, collections.Mapping) else v1 and v2

r = check_json(myjson, checker)
print("r={}".format(r))
isOK = functools.reduce(with_and, r.values(), True)
print("Result is {}: {}".format(isOK, r))

rawDescription: How can I remove need for these checking functions to be global

description: Remove need for these checking functions to be global


code:
class A(object):
    pass

a = A()
f = 'field'
setattr(a, f, 42)
a.field

rawDescription: Adding variably named fields to Python classes


code:
import cherrypy
import MySQLdb

def connect(thread_index):
    # Create a connection and store it in the current thread
    cherrypy.thread_data.db = MySQLdb.connect('host', 'user', 'password', 'dbname')
    cherrypy.thread_data.db2 = MySQLdb.connect('host', 'user', 'password', 'dbname2')

# Tell CherryPy to call "connect" for each thread, when it starts up
cherrypy.engine.subscribe('start_thread', connect)

class Root:
    def index(self):
        # Sample page that displays the number of records in "table"
        # Open a cursor, using the DB connection for the current thread
        c = cherrypy.thread_data.db.cursor()
        c.execute('select count(*) from table')
        res = c.fetchone()
        c.close()

        c = cherrypy.thread_data.db2.cursor()
        c.execute('select count(*) from table2')
        res = c.fetchone()
        return "Hello, you have %d records in your table" % res[0]
    index.exposed = True

cherrypy.quickstart(Root())

rawDescription: Can I connect to multiple databases in CherryPy?

description: Connect to multiple databases in CherryPy