code:
('Hello, ' + 'world!') is 'Hello, world!'
('Hello, ' + 'world!') == 'Hello, world!'

rawDescription: Python: __cmp__ and testing list membership


code:
from modules import SmallClass
from modules import AnotherClass

class BigClass(object):
    def __init__(self, server=None):
        """construct the big class"""
        self.reset_class(server)

    def reset_class(self, server=None):
        """reset the big class"""
        self.server = server
        self.small_class = SmallClass(self.server)
        self.another_class = AnotherClass(small_class)

rawDescription: Effects of calling __init__() from inside the object


code:
def knightTour(current, limit, path):
    path.append(current)    # add current before returning, or the last
    if len(path) == limit:  # node will be missing in the returned path
        return path
                            # (no need to check length)
    for i in graph[current]:
        if i not in path:   # (no point in creating a set in each iteration)
            tour = knightTour(i, limit, path)
            if tour:        # only return the path if it is not None, i.e.
                return tour # if the recusion was succesful (backtracking)
    else:
        path.pop()          # (use implicit return None)

rawDescription: What am I missing in DFS in knight tour?

description: What am I missing in DFS in knight tour


code: row = table.rowAt(point.y())

rawDescription: Get row in a qtablewidget from a qpoint object in pyqt4


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

dat = np.random.randn(10,10)
plt.imshow(dat, interpolation='none')

clb = plt.colorbar()
clb.ax.set_title('This is a title')

plt.show()

rawDescription: Top label for matplotlib colorbars

description: Top label for matplotlib colorbars


code: seaborn.distplot(C77_diam, rug=True, hist=True, kde=True).set(xlim=(0, max_diam))

rawDescription: lower bound to kernel density estimation with seaborn for matplotlib in python

description: Lower bound to kernel density estimation with seaborn for matplotlib in python


rawDescription: Numpy: 2D array access with 2D array of indices


code:
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt

def mysys(z, t):
    """A slightly damped oscillator."""
    return [z[1] - 0.02*z[0], -z[0]]

if __name__ == "__main__":
    # Note that t starts at 0 and goes "backwards"
    t = np.linspace(0, -50, 501)

    z0 = [1, 1]
    sol = odeint(mysys, z0, t)

    plt.plot(t, sol)
    plt.xlabel('t')
    plt.show()

rawDescription: Backward integration in time using scipy odeint


code:
memoByVal = {}
memoByRef = {id(None): 0}
nextId = 1

# produce an integer that represents the tree's content
def getTreeId(tree):
  if id(tree) in memoByRef:
    return memoByRef[id(tree)]
  # nodes are represented by the (left, right, value) combination
  # let's assume that leafs just have left == right == None
  l, r = getTreeId(tree.left), getTreeId(tree.right)
  if (l, r, tree.value) not in memoByVal:
    memoByVal[l, r, tree.value] = nextId
    nextId += 1
  res = memoByVal[l, r, tree.value]
  memoByRef[id(tree)] = res
  return res

# this is now trivial
def equals(a, b):
  return getTreeId(a) == getTreeId(b)

rawDescription: Efficient equality function on trees

description: Efficient equality function on trees


code:
import  javax.servlet.http.HttpServlet

import  cStringIO
import  gzip
import  string

def compressBuf(buf):
    zbuf = cStringIO.StringIO()
    zfile = gzip.GzipFile(mode = 'wb',  fileobj = zbuf, compresslevel = 6)
    zfile.write(buf)
    zfile.close()
    return zbuf.getvalue()

rawDescription: python (jython) archiving library

description: Python (jython) archiving library


code:
firststring = "aaccddee"
secondstring = "bb"
combinedstring = firststring[:2] + secondstring + firststring[2:]
print(combinedstring)

rawDescription: how to append a smaller string in between a larger string in python?

description: Append a smaller string in between a larger string in python


rawDescription: How would you unpack a 32bit int in Python?


code: contact_info = ArrayField(models.CharField(max_length=15), blank=True)

rawDescription: Django models -Best way to store multiple contact numbers


code:
def getGenerator(self, keyIterator):
    results = []
    def bufferFullCallback(list_of_keys):
        results.extend(api_call(list_of_keys))
    for key in keyIterator:
        with MyBuffer(self.buffer_size, bufferFullCallback) as buf:
            buf.addToBuffer(key)
            for value in results:
                yield value

rawDescription: How can I yield a value from within a callback to a calling generator

description: Yield a value from within a callback to a calling generator


code:
with open('myfile.csv', 'w') as f:
        w = csv.writer(f, dialect = 'excel-tab') #use `delimiter = ','` for ',' in file
        for item in data:
            lis = [item[0]] +   [y for x in item[1] for y in x]
            w.writerow(lis)

rawDescription: How to write a complex nested list to a csv file without brackets in python?

description: Write a complex nested list to a csv file without brackets in python


code:
d = addresses_table.delete(addresses_table.c.retired == 1)
d.execute()

rawDescription: How to delete rows from a table using an SQLAlchemy query without ORM?

description: Delete rows from a table using an SQLAlchemy query without ORM


code:
listOfA, listOfB = [], []

for idx, x in enumerate(s):
    target = listOfA if x == 'A' else listOfB
    target.append(idx)

rawDescription: Python list comprehensions to create multiple lists


code:
date_inserted    = models.DateTimeField(auto_now_add=True)
date_last_update = models.DateTimeField(auto_now=True)

rawDescription: Datetime field on Django to store the date of insertion of row?


code:
import sqlalchemy.types as types

class UUID(types.TypeEngine):
    def get_col_spec(self):
        return "uuid"

    def bind_processor(self, dialect):
        def process(value):
            return value
        return process

    def result_processor(self, dialect):
        def process(value):
            return value
        return process

table = Table('foo', meta,
    Column('id', UUID(), primary_key=True),
)

rawDescription: How can I use UUIDs in SQLAlchemy?

description: Use UUIDs in SQLAlchemy


code: out1 = raw_input("Where would you like to save this? ")

rawDescription: saving the data after it was printed to screen python

description: Saving the data after it was printed to screen python


code:
import getpass
x = getpass.getpass("enter password: ")
print(x)

rawDescription: Is there an easy way to add a hide password type feature in python code?


code:
def vector_intersection(v1,v2,d1,d2):
    '''
    v1 and v2 - Vector points
    d1 and d2 - Direction vectors
    returns the intersection point for the two vector line equations.
    '''
    if d1[0] == 0 and d2[0] != 0 or d1[1] == 0 and d2[1] != 0:
        if d1[0] == 0 and d2[0] != 0:
            mu = float(v1[0] - v2[0])/d2[0]
        elif d1[1] == 0 and d2[1] != 0:
            mu = float(v1[1] - v2[1])/d2[1]
        return (v2[0] + mu* d2[0],v2[1] + mu * d2[1])
    else:
        if d1[0] != 0 and d1[1] != 0 and d2[0] != 0 and d2[1] != 0:
            if d1[1]*d2[0] - d1[0]*d2[1] == 0:
                raise ValueError('Direction vectors are invalid. (Parallel)')
            lmbda = float(v1[0]*d2[1] - v1[1]*d2[0] - v2[0]*d2[1] + v2[1]*d2[0])/(d1[1]*d2[0] - d1[0]*d2[1])
        elif d2[0] == 0 and d1[0] != 0:
            lmbda = float(v2[0] - v1[0])/d1[0]
        elif d2[1] == 0 and d1[1] != 0:
            lmbda = float(v2[1] - v1[1])/d1[1]
        else:
            raise ValueError('Direction vectors are invalid.')
        return (v1[0] + lmbda* d1[0],v1[1] + lmbda * d1[1])

rawDescription: Finding the intersection of two vector equations


code:
checkList = set(['a', 'b', 'c'])

for i in textList:
    check, rest = i.split(':', 1)
    if check.strip() not in checkList:
        continue
    data = rest.strip()
    # insert data into database; check is your column name.

rawDescription: How to elegantly grab data with python?

description: Elegantly grab data with python


code:
a = (1,2,3)
res = []
res.extend(a)
res
list(a)

rawDescription: Python MysqlDb-How to store results of fetchone() in a list?


code:
import functools

def protected(fun):
    @functools.wraps(fun)
    def wrapper(self, *args, **kwargs):
        if not self.checkLogin():
            raise UserLoginError()
        return fun(self, *args, **kwargs)

    return wrapper # this is what replaces the original method

@protected
def doIfLoggedIn(self):
    ...

rawDescription: Python - Decorating a Class Method to test Class Attributes


code:
import re

s = "Tough Fox"
re.split(r"\s(?=[A-Z])", s, maxsplit=1)

['Tough', 'Fox']

rawDescription: Pythonic sentence splitting on words starting with capital letter


code:
size = 8
value = 171
unsigned = value % 2**size
signed = unsigned - 2**size if unsigned >= 2**(size-1) else unsigned
signed

rawDescription: convert python integer to its signed binary representation

description: Convert python integer to its signed binary representation


rawDescription: Python3 ASCII Hexadecimal to Binary String Conversion


code:
with open("new.csv", 'r') as infile:
    readie=csv.reader(infile, delimiter=',')
    with open("output.csv", 'wt') as output:
        outwriter=csv.writer(output, delimiter=',')
        i = 0
        for row in readie:
             outwriter.writerow(row)
             i += 1
             if i % 5 == 0:
                 # write the empty row
                 outwriter.writerow([])

rawDescription: Insert blank rows every fifth row in csv file python


code:
x = input("Enter your blood type: ")
if x == 'O':
    for y in range(6):
        print("O O O O O O")
elif x == 'A':
    for y in range(6):
        print("A A A A A A")
elif x == 'B':
    for y in range(6):
        print("B B B B B B")
elif x == 'AB':
    for y in range(3):
        print("AB AB AB")
else:
    print("N/A blood type! Are you alien?")

rawDescription: Have an issue with input command

description: Have an issue with input command


code:
param1 = sys.argv[1]
param2 = sys.argv[2]
query = "SELECT ? FROM (table_name) where id = ?"
cursor.execute(query, (param1,param2))

rawDescription: Can I use string formatting while querying a database in python

description: Use string formatting while querying a database in python


code:
def clean(self):
    cleaned_data = super(SignUpForm, self).clean()
    email = cleaned_data.get('email')
    email_conf = cleaned_data.get('email_conf')

    if email and email_conf and email != email_conf:
        self._errors['email_conf'] = self.error_class(['Emails do not match.'])
        del self.cleaned_data['email_conf']
    return cleaned_data

rawDescription: Django Forms: How to validate if two fields are the same, e.g. email or password?


code:
class A:
    pass

class B(A):
    pass

A.B = B
B.__name__ = ...
B.__qualname__ = ...

rawDescription: python - inheriting parent class

description: Python - inheriting parent class


code:
import numpy as np
import matplotlib.pylab as plot
import math as m
#initialize variables
#velocity, gravity
v = 30
g = 9.8
#increment theta 25 to 60 then find  t, x, y
#define x and y as arrays

theta = np.arange(m.pi/6, m.pi/3, m.pi/36)

t = np.linspace(0, 5, num=100) # Set time as 'continous' parameter.

for i in theta: # Calculate trajectory for every angle
    x1 = []
    y1 = []
    for k in t:
        x = ((v*k)*np.cos(i)) # get positions at every point in time
        y = ((v*k)*np.sin(i))-((0.5*g)*(k**2))
        x1.append(x)
        y1.append(y)
    p = [i for i, j in enumerate(y1) if j < 0] # Don't fall through the floor
    for i in sorted(p, reverse = True):
        del x1[i]
        del y1[i]

    plot.plot(x1, y1) # Plot for every angle

plot.show() # And show on one graphic

rawDescription: projectile motion simple simulation using numpy matplotlib python

description: Projectile motion simple simulation using numpy matplotlib python


code:
import sys
from PyQt4.QtGui import *

class MainWindow(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        # making tabs
        tabs = QTabWidget()
        tabs.setUsesScrollButtons(False) #here is

        tabs.addTab(QWidget(), '111111')
        tabs.addTab(QWidget(), '222222')
        tabs.addTab(QWidget(), '333333')
        tabs.addTab(QWidget(), '444444')
        # inserting in vbox
        vbox = QVBoxLayout(self)
        vbox.addWidget(tabs)

app = QApplication(sys.argv)
myapp = MainWindow()
myapp.show()
sys.exit(app.exec_())

rawDescription: PyQt - resize parent widget to its child


code:
def Print_PDF(request):
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="resume.pdf"'

    p = canvas.Canvas(response)

    p.drawString(100, 100, "Some text in first page.")
    p.showPage()

    p.drawString(200, 100, "Some text in second page.")
    p.showPage()

    p.drawString(300, 100, "Some text in third page")
    p.showPage()

    p.save()
    return response

rawDescription: Multiple pages using Reportlab - Django

description: Multiple pages using Reportlab - Django


code:
import csv
with open(filename, 'w') as f:
   writer = csv.writer(f, delimiter=',')
   writer.writerows(my_list)  #considering my_list is a list of lists.

rawDescription: Writing multi-dimensional list value to a file in Python


code:
class ProfileIndex(indexes.SearchIndex, indexes.Indexable):
    # your other fields, most likely model attributes
    role_name = indexes.CharField()

    def get_model(self):
        return Person

    def prepare_role_name(self, person):
        return person.workplace.role_name

rawDescription: How to filter Haystack SearchQuerySets by related models

description: Filter Haystack SearchQuerySets by related models


rawDescription: Taking the floor of a float

description: Taking the floor of a float


code:
from PyQt4 import QtGui, QtCore
from PyQt4 import *
from PyQt4.QtCore import *
import sys

CurrentTime = 0
class widgetWindow(QtGui.QWidget):
    def __init__(self, parent = None):
        QtGui.QWidget.__init__(self,parent)
        super(widgetWindow, self).__init__()
        widgetWindow.start(self)

    def start(self):
        window = QtGui.QMainWindow(self)
        window.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        CentralWidget = QtGui.QWidget()
        self.timeSlider = QtGui.QSlider(QtCore.Qt.Horizontal, self)
        CentralWidgetLayout = QtGui.QHBoxLayout()
        VBox = QtGui.QVBoxLayout()
        CentralWidgetLayout.addWidget(self.timeSlider)
        VBox.addLayout(CentralWidgetLayout)
        CentralWidget.setLayout(VBox)
        window.setCentralWidget(CentralWidget)
        window.show()

        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.updateTime)
        self.timer.start(1000)

    def updateTime(self):
        global CurrentTime
        CurrentTime = CurrentTime + 1
        self.timeSlider.setValue(CurrentTime)

class MainWindow(QtGui.QMainWindow,widgetWindow):#here add subclass
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)
        self.central = QtGui.QWidget(self)
        self.setCentralWidget(self.central)

        self.hboxPB = QtGui.QHBoxLayout()
        self.vboxPB = QtGui.QVBoxLayout()
        self.MyButton = QtGui.QPushButton(self.central)
        self.MyButton.setText("Push Me")
        self.hboxPB.addWidget(self.MyButton)
        self.vboxPB.addLayout(self.hboxPB)
        self.MyButton.resize(90,90)
        self.MyButton.clicked.connect(lambda: widgetWindow.start(self))

def main():
    app = QtGui.QApplication(sys.argv)
    win = MainWindow()
    win.show()
    win.resize(800,450)
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

rawDescription: Unable to acces a "def" in a sub window - "MainWindow object has no attribute 'updateTime' "


code:
t = Template("template.tmpl")
t.multiple = multiple

rawDescription: Cheetah template engine calling python base function


code:
import re
pattern = re.compile(r'<[c|d][^>]*>(?P<text>[^<]*)</[c|d]>')
with open('filename', 'r') as f:
    for txt in pattern.finditer(f.read()):
        print(txt.group('text').strip())

rawDescription: Python - Fastest way to find elements in XML documents


code:
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains

driver = webdriver.Firefox()
driver.get("your.site.with.dragndrop.functionality.com")
source_element = driver.find_element_by_name('your element to drag')
dest_element = driver.find_element_by_name('element to drag to')
ActionChains(driver).drag_and_drop(source_element, dest_element).perform()

rawDescription: Python Selenium WebDriver drag-and-drop

description: Python Selenium WebDriver drag-and-drop


code:
with open(your_file_path) as f:
    lines = f.read_lines()
    lines[1] = '#MOAB -l walltime={0}'.format(new_walltime_str)

with open(your_file_path, 'w') as f:
    f.write('\n'.join(lines))

rawDescription: Python3: copy / amend a file

description: Python3: copy / amend a file


code:
class Whatever(object):

  def __getstate__(self):
    state = self.__dict__.copy()
    del state['view']
    return state

rawDescription: problem with pickle and tkinter

description: Problem with pickle and tkinter


code:
connect.execute(tobeexec, params);
connect.commit()
connect.close()

rawDescription: Python sqlite3 saving data

description: Python sqlite3 saving data


code:
N = 5
coords = np.random.uniform(size=(N, 2))
coords
coords.sum(axis=0)
(coords.sum(axis=0)**2).sum()

rawDescription: vectorized code for python

description: Vectorized code for python


code:
import turtle

unVar1 = 25
unVar2 = 100
unVar3 = 90
unVar4 = 150
unVar5 = -30
unVar6 = 75
unVar7 = 50

def polySquare(t, x, y, length):
    t.goto(x, y)
    t.setheading(270)

    t.begin_poly()

    for count in range(4):
        t.forward(length)
        t.left(90)

    t.end_poly()

    return t.get_poly()

def polyRectangle(t, x, y, length1, length2):
    t.goto(x, y)
    t.setheading(270)

    t.begin_poly()

    for count in range(2):
        t.forward(length1)
        t.left(90)
        t.forward(length2)
        t.left(90)

    t.end_poly()

    return t.get_poly()

def tankCursor():

    """
    Create the tank cursor.  An alternate solution is to toss the temporary turtle
    and use the commented out polygon assignments instead of the poly* function calls
    """

    temporary = turtle.Turtle()

    screen = turtle.getscreen()

    delay = screen.delay()

    screen.delay(0)

    temporary.hideturtle()
    temporary.penup()

    tank = turtle.Shape("compound")

    # tire1 = ((10, unVar1), (10, unVar1 - unVar6), (10 + 30, unVar1 - unVar6), (10 + 30, unVar1))
    tire1 = polyRectangle(temporary, 10, unVar1, unVar6, 30)  # Tire #1
    tank.addcomponent(tire1, "gray", "black")

    # tire2 = ((110, unVar1), (110, unVar1 - unVar6), (110 + 30, unVar1 - unVar6), (110 + 30, unVar1))
    tire2 = polyRectangle(temporary, 110, unVar1, unVar6, 30)  # Tire #2
    tank.addcomponent(tire2, "gray", "black")

    # tire3 = ((110, unVar2), (110, unVar2 - unVar6), (110 + 30, unVar2 - unVar6), (110 + 30, unVar2))
    tire3 = polyRectangle(temporary, 110, unVar2, unVar6, 30)  # Tire #3
    tank.addcomponent(tire3, "gray", "black")

    # tire4 = ((10, unVar2), (10, unVar2 - unVar6), (10 + 30, unVar2 - unVar6), (10 + 30, unVar2))
    tire4 = polyRectangle(temporary, 10, unVar2, unVar6, 30)  # Tire #4
    tank.addcomponent(tire4, "gray", "black")

    # bodyTank = ((20, unVar3), (20, unVar3 - 130), (20 + 110, unVar3 - 130), (20 + 110, unVar3))
    bodyTank = polyRectangle(temporary, 20, unVar3, 130, 110)
    tank.addcomponent(bodyTank, "black", "gray")

    # gunTank = ((65, unVar4), (65, unVar4 - 100), (65 + 20, unVar4 - 100), (65 + 20, unVar4))
    gunTank = polyRectangle(temporary, 65, unVar4, 100, 20)   # Gun
    tank.addcomponent(gunTank, "black", "gray")

    # exhaustTank = ((50, unVar5), (50, unVar5 - 20), (50 + 10, unVar5 - 20), (50 + 10, unVar5))
    exhaustTank = polyRectangle(temporary, 50, unVar5, 20, 10)
    tank.addcomponent(exhaustTank, "black", "gray")

    # turretTank = ((50, unVar7), (50, unVar7 - 50), (50 + 50, unVar7 - 50), (50 + 50, unVar7))
    turretTank = polySquare(temporary, 50, unVar7, 50)  # Turret
    tank.addcomponent(turretTank, "red", "gray")

    turtle.addshape("tank", shape=tank)

    del temporary

    screen.delay(delay)

tankCursor()  # creates and registers the "tank" cursor shape

turtle.shape("tank")

turtle.up()  # get rid of the ink

# show our tank in motion

turtle.setheading(90)
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
turtle.left(45)
turtle.forward(100)

turtle.done()

rawDescription: Change appearance of turtle

description: Change appearance of turtle


code:
X = vectorizer.transform(docs)
terms = np.array(vectorizer.get_feature_names())
terms_for_first_doc = zip(terms, X.toarray()[0])

rawDescription: How can i get highest frequency terms out of TD-idf vectors , for each files in scikit-learn?

description: Get highest frequency terms out of TD-idf vectors , for each files in scikit-learn


code:
try:
    import serial
except ImportError:
    pass    # couldn't import serial, so do nothing
else:       # we successfully imported serial, so define the class that uses it

    class SerialReader(Reader): # (Should only be interpreted in a PC device)
        def __init__(self, portname='/dev/ttyACM2', baudrate=115200, magic0=0x42, magic1=0x41):
            super(SerialReader, self).__init__()
            self.ser = serial.Serial(portname, baudrate=baudrate, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=None)

        # Implements other abstract methods and **uses Serial object***

rawDescription: How do I prevent python interpreter to see and import modules that are not installed; do not belong to the system?

description: Prevent python interpreter to see and import modules that are not installed; do not belong to the system


rawDescription: How to convert ip like `127.0.0.1` to `127.0.0.0/24` use regex?

description: Convert ip like `127.0.0.1` to `127.0.0.0/24` use regex


code:
import itertools

data1 = range(10)

# This creates a NEW list
data1[2:5]

# This creates an iterator that iterates over the EXISTING list
itertools.islice(data1, 2, 5)

data2 = [1, 2, 3]
data3 = [4, 5, 6]

# This creates a NEW list
data2 + data3

# This creates an iterator that iterates over the EXISTING lists
itertools.chain(data2, data3)

rawDescription: Why would I want to use itertools.islice instead of normal list slicing?


code: df = pd.read_csv(results_file, delimiter='\t')

rawDescription: Producing pandas DataFame from table in text file


code:
import csv
from itertools import *

# see recipies section in itertools docs
# http://docs.python.org/2/library/itertools.html
def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

with open('input.csv') as f:
    data = csv.reader(f, skipinitialspace=True)
    with open('output.csv', 'w') as output_f:
        output = csv.writer(output_f)
        for city, names, blank in grouper(data, 3, []):
            if not (city[0] == 'Paris' and 'Trevor Wilson' in names):
                output.writerow(city)
                output.writerow(names)
                output.writerow('')

rawDescription: Cross matching and deleting rows from a csv using data from text file


code: df

rawDescription: Create group identifiers for regressions


code:
from PIL import Image

img = Image.new('RGB', (width, height))
img.putdata(my_list)
img.save('image.png')

rawDescription: In Python, how do I easily generate an image file from some source data?


code:
# this is very close to how it's done in C using get_*/set_* accessors.
window = Gtk.Window(Gtk.WindowType.TOPLEVEL)
window.set_title("Hello")

# setting properties as keyword arguments to the constructor
window = Gtk.Window(type=Gtk.WindowType.TOPLEVEL, title="Hello")

# set_properties() can be used to set properties after construction
window = Gtk.Window()
window.set_properties(title="Hello")

rawDescription: PyGObject GTK+ 3 - Documentation?

description: PyGObject GTK+ 3 - Documentation


code: object = MyModel.objects.get(slug=slug)

rawDescription: Django: how to retrieve an object selected by the ``object_detail`` generic view?


code:
def n_lower_chars(string):
    return sum(1 for c in string if c.islower())

rawDescription: Count lower case characters in a string

description: Count lower case characters in a string


code:
import os
os._exit(0)

rawDescription: Exiting Python interpreter without running garbage collection


rawDescription: Multidimensional list match in python

description: Multidimensional list match in python


code:
from Tkinter import Tk, Frame, BOTH
import Tkinter
from PIL import Image, ImageTk

class Example(Frame):

    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initUI()

    def initUI(self):
        self.parent.title("PISE")
        self.pack(fill=BOTH, expand=1)

root = Tk()
root.geometry("1111x675+300+300")
app = Example(root)

im = Image.open('Test1.png')
tkimage = ImageTk.PhotoImage(im)
myvar=Tkinter.Label(root,image = tkimage)
myvar.place(x=0, y=0, relwidth=1, relheight=1)

custName = StringVar(None)
yourName = Entry(root, textvariable=custName)
yourName.pack()

relStatus = StringVar()
relStatus.set(None)

labelText = StringVar()
labelText.set('Accuracy Level')
label1 = Label(root, textvariable=labelText, height=2)
label1.pack()

def beenClicked1():
    pass

def beenClicked5():
    pass

radio1 = Radiobutton(root, text='100%', value='1', variable = relStatus, command=beenClicked1).pack()
radio2 = Radiobutton(root, text='50%', value='5', variable = relStatus, command=beenClicked5).pack()

root.mainloop()

rawDescription: how to set background image to a window using Tkinter python 2.7

description: Set background image to a window using Tkinter python 2.7


code:
def repl(matchobj):
    if matchobj.group(1):
        return "1" #something
    if matchobj.group(2):
        return "1" #something

new=re.sub(r"\\begin{longtable}\[(.*)\]{(.*)}(.*)\\end{longtable}",repl,string)

rawDescription: Work with the result of re.findall()

description: Work with the result of re.findall()


code:
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import cgi

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.end_headers()
        self.wfile.write("""
            <html><head></head>
            <body>
            <form method="POST">
            your mood:
            <textarea name="mood">
            </textarea>
            <input type="submit" name="submit" value="submit">
            </form>
            </body>
            </html>
            """)
        return

    def do_POST(self):
        form = cgi.FieldStorage(
            fp=self.rfile,
            headers=self.headers,
            environ={'REQUEST_METHOD':'POST',
                     'CONTENT_TYPE':self.headers['Content-Type'],
                     })
        themood = form["mood"]
        hap=['amused','beaming','blissful','blithe','cheerful','cheery','delighted']
        sad=['upset','out','sorry','not in mood','down']
        sad_count=0
        happy_count=0
        happy_count=len(filter(lambda x:x in themood.value,hap))
        sad_count=len(filter(lambda x:x in themood.value,sad))
        if(happy_count>sad_count):
            self.wfile.write("Hey buddy...your mood is HAPPY :-)")
        elif(sad_count>happy_count):
            self.wfile.write("Ouch! Your Mood is Sad :-(")
        elif(happy_count==sad_count):
            if(happy_count>0 and sad_count>0):
                self.wfile.write("oops! You are in CONFUSED mood :o")
            else:
                self.wfile.write("Sorry,No mood found :>")
        return
server = HTTPServer(('', 8181), Handler)
server.serve_forever()

rawDescription: Python :- passing HTML form input to python code and execute it


code:
html = urllib2.urlopen(url).read()
bs = BeautifulSoup(html)
table = bs.find(lambda tag: tag.name=='table' and tag.has_key('id') and tag['id']=="Table1")
rows = table.findAll(lambda tag: tag.name=='tr')

rawDescription: BeautifulSoup: Get the contents of a specific table


code:
import pylab as pl
data = pl.random((25,25)) # 25x25 matrix of values
pl.pcolor(data)
pl.colorbar()
pl.show()

rawDescription: Generating heatmap using pylab

description: Generating heatmap using pylab


code:
import pytz
local_tz = pytz.timezone(timezone_name)
return timestamp_utc.replace(tzinfo=pytz.utc).astimezone(local_tz).replace(tzinfo=None)

rawDescription: Converting UTC datetime to user's local date and time


rawDescription: is there putAll like method for dict in python?

description: Is there putAll like method for dict in python


code:
lst = ['a', 'b', 'c']
i = lst.index('b') # This raises ValueError if there's no 'b' in the list.
lst[i:i+1] = 'b1', 'b2', 'b3'
lst

rawDescription: search for element in list and replace it by multiple items

description: Search for element in list and replace it by multiple items


code:
def mult(n, m):
    if m == 0:
        return 0
    elif m == 1:
        return n
    elif m < 0:
        return mult(-n, -m)

    return n + mult(n, m-1)

rawDescription: How can we multiply two integers without using * operator in python?


code: np.sqrt(np.sum(a*a, axis=0))

rawDescription: Calculating norm of columns as vectors in a matrix


code:
import ast
d['members'] = ast.literal_eval(d['members'])
d['members']['as.wso2.com']

rawDescription: Remove quotes in python dictionary

description: Remove quotes in python dictionary


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

# create data
N = 4097
T = 100.0
t = np.linspace(-T/2,T/2,N)
f = np.exp(-np.pi*t**2)

# perform FT and multiply by dt
dt = t[1]-t[0]
ft = np.fft.fft(f) * dt
freq = np.fft.fftfreq(N, dt)
freq = freq[:N/2+1]

# plot results
plt.plot(freq, np.abs(ft[:N/2+1]),'o')
plt.plot(freq, np.exp(-np.pi * freq**2),'r')
plt.legend(('numpy fft * dt', 'exact solution'), loc='upper right')
plt.xlabel('f')
plt.ylabel('amplitude')
plt.xlim([0, 1.4])
plt.show()

rawDescription: amplitude of numpy's fft results is to be multiplied by sampling period?

description: Amplitude of numpy's fft results is to be multiplied by sampling period


rawDescription: Pyplot set tick frequency and tick labels


code:
def walk(d, path):
    paths = []
    if len(d) == 0:
        return path
    for k, v in d.iteritems():
        child_path = path + k + '/'
        if isinstance(v, basestring):
            paths.append(child_path + v)
        else:
            paths.extend(walk(v, child_path))
    return paths

rawDescription: Extracting all path from a multi-level dictionary


code:
df = pandas.DataFrame({'A': range(20)}, index=pandas.date_range('2012-01-01', freq='1H', periods=20))
df.plot()

rawDescription: Show xticks with specified interval on pandas DataFrame


code:
import re
s = "rebar bar barbed"
regex = re.compile(r"\bbar\b")
for match in regex.finditer(s):
    print(match.group(), match.start(), match.end())

rawDescription: Python regular expression string search to return start index


code:
import os
import glob
import xlsxwriter
import csv

flist = [os.path.basename(x) for x in glob.glob(os.getcwd() + '\\*.csv')]

workbook = xlsxwriter.Workbook('split_book.xlsx')

for sh in flist:
    worksheet = workbook.add_worksheet(sh)
    with open(sh, 'rb') as f:
        reader = csv.reader(f)
        for r, row in enumerate(reader):
            for c, col in enumerate(row):
                worksheet.write(r, c, col)

workbook.close()

rawDescription: Add new sheet to Workbook in xlsxwriter

description: Add new sheet to Workbook in xlsxwriter


rawDescription: how to generate range date from date string in python?

description: Generate range date from date string in python


code:
class ActionRegistry(type):
  registry = {}
  def __init__(cls, name, bases, dic):
    if 'regex' in dic:
      cls.registry[dic['regex']] = cls
    super(ActionRegistry, cls).__init__(name, bases, dic)

class Action(object):
  __metaclass__ = ActionRegistry

class Sing(Action):
  regex = r'^SING [0-9]+'

class Dance(Action):
  regex = r'^DANCE [0-9]+'

rawDescription: Good way to organize all sub classes into a dictionary in python?


code:
import redis
r = redis.Redis()
for x in r.scan_iter('dummy*'):
  print(x)

rawDescription: Paginating "KEYS" command on Redis

description: Paginating "KEYS" command on Redis


code:
from itertools import combinations
L=[1,2,3,4]
[",".join(map(str,comb)) for comb in combinations(L, 3)]

rawDescription: Get unique combinations of elements from a python list


code: db = DAL('mysql://user1:P%40sswd@localhost/test', decode_credentials=True)

rawDescription: Escaping special characters in web2py database connection strings


code:
valid_values = 'AVE', 'TRL', 'ST'
for row in cursor:
    value = row.getValue(field)
    if value in valid_values:
        continue

    print("Invalid value: OBJECTID={}, StSuffix={}".format(
        row.getValue(field1),
        value
    ))

rawDescription: Need to display a text list of records not on my list


code:
import Tkinter as tk

root = tk.Tk()
w = tk.Scale(root, from_=0, to=100, orient=tk.HORIZONTAL)
w.grid(column=0, row=1, columnspan=2, rowspan=1)
tk.Label(root,text="column 0").grid(row=0,column=0)
tk.Label(root,text="column 1").grid(row=0,column=1)

root.mainloop()

rawDescription: Multiple columns:Gridview

description: Multiple columns:Gridview


code:
class Egg(models.Model):
    chicken = models.ForeignKey(Chicken, related_name='eggs')
    layed_on = models.DateField(auto_add_now=True)

from django.db.models import Max
Chicken.objects.annotate(last_egg=Max('eggs__layed_on'))

rawDescription: Django: How to access a list of backward relationships in a view?


code:
from scrapyd_api import ScrapydAPI

scrapyd = ScrapydAPI('http://localhost:6800')
scrapyd.schedule('project_name', 'spider_name')

rawDescription: Starting Scrapy from a Django view

description: Starting Scrapy from a Django view


code:
class BigWidget(QWidget):
    def __init__(self, parent=None, **kwargs):
        QWidget.__init__(self, parent, **kwargs)

        ...

    def DrawManyWidgets(self, parent):
        self.setVisible(False)

        ...

        self.setVisible(True)

rawDescription: PYQT - help profiling python code {built-in method exec_}


Print 1.41069562657e-25 as 1.41*10^-25


code:
client_key = 'client key'
client_secret = 'secret'
callback_uri = 'https://yourhost.com/callback'
# Using OAuth1Session
oauth = OAuth1Session(client_key, client_secret=client_secret, callback_uri=callback_uri)

rawDescription: putting a callback uri in a Oauth request

description: Putting a callback uri in a Oauth request


code:
list_of_strings = ['Hello!, my name is Carl', 'Hello!, my name is Steve', 'Hello!, my name is Betty', 'My Name is Josh']
[s.find('Hello!') for s in list_of_strings]

rawDescription: Using .find to search a string inside a list


code:
pos_1 = 234
pos_n = 12890
min_width = len(str(pos_n))

raw_str = '... from %0*d to %0*d ...' % (min_width, pos_1, min_width, pos_n)

rawDescription: python String Formatting Operations

description: Python String Formatting Operations


code:
import string
string.punctuation

rawDescription: Python String Constants

description: Python String Constants


rawDescription: 2d numpy.array() comparing one string to all others, and repeated for each string


code:
def recursive_max(seq, key=None):
    # if key isn't given, call it again with key being returning the value itself
    if not key: return recursive_max(seq, lambda a: a)

    # error checking: can't get max of empty sequence
    if not seq: raise ValueError("max of empty seq")

    # base case: seq of 1, the max is the first element
    if len(seq) == 1: return seq[0]

    # get the max of the rest of the list
    sub_max = recursive_max(seq[1:], key)

    # if that's bigger than 1st element, return that, else return 1st element
    return sub_max if key(sub_max) > key(seq[0]) else seq[0]

rawDescription: recursive function find the max value on python

description: Recursive function find the max value on python


code:
class X(object):
    def __round__(self, n=0): return 1.
    def __float__(self): return 2.

x = X()
round(x)
float(x)
old_round = round
def round(x, n=0):
    try:
            return x.__round__(n)
    except AttributeError:
            return old_round(x)

round(x)
float(x)

rawDescription: __float__ and __round__ in python 2 and 3


code:
class Email(models.Model):

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super(Email, self).save(*args, **kwargs) # save the object first
        question_objs = Question.objects.all()
        self.questions.add(*question_objs) # add all questions using *

rawDescription: Create many to many relation with query set of another model in Django


code:
list_of_tuples = [('a', 1),('b',2),('c',1),('a',2),('d',3)]
d = {}
for item in list_of_tuples:
    d.setdefault(item[1],[]).append(item[0])
d

rawDescription: Python list of tuples: organize by unique elements to a dictionary


rawDescription: time.strptime changing output formatting

description: Time.strptime changing output formatting


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

data=np.loadtxt("YourFileName.txt", dtype="YourDataType", delimiter=",")
plt.plot(data)
plt.show()    #if you want to see the plot
plt.savefig("PngFile.png")

rawDescription: how to read files from *.txt and import the data content to a png file that it create a diagram

description: Read files from *.txt and import the data content to a png file that it create a diagram


code:
mult_factor = 2.20462
print ('Kilogram', 'Pound')
for i in range (0, 100, 10):
    print (i , i * mult_factor)

rawDescription: How to write a function that outputs a two-column table

description: Write a function that outputs a two-column table


code:
import numpy as np
from scipy.optimize import basinhopping

inputarray = [1,2,3,4,5]
coefficient = 100

def objective_function(coefficient, inputarray):

    factorarray = np.empty(len(inputarray))
    factorarrayTrue = np.empty(len(inputarray))
    for i, num in enumerate(inputarray):
        factorarray[i] = num * coefficient
        factorarrayTrue[i] = num *123

    #### SQUARE ERROR
    SEzip = zip(factorarrayTrue, factorarray)
    sse = 0
    for e in SEzip:
        sse += (e[0] - e[1])**2
    return sse

minimizer_kwargs = {"method": "COBYLA", "args": (inputarray) }
result = basinhopping(objective_function, coefficient, minimizer_kwargs = minimizer_kwargs)

print(result)

rawDescription: Scipy to optimize constant based on sum of square error


code:
from BeautifulSoup import BeautifulSoup
html = '''Jay-Z &
Kanye West - Watch the Throne'''
soup = BeautifulSoup(html)
soup.span.contents[-1].strip('- ')

rawDescription: Parsing Content With Beautiful Soup Between Two Closing Tags


code:
import contextlib
import os
import shutil
import tmpfile

from sphinx.websupport import WebSupport

@contextlib.contextmanager
def mkdtemp(suffix='', prefix='tmp', parent_dir=None):
    path = tempfile.mkdtemp(suffix, prefix, parent_dir)
    try:
        yield path
    finally:
        shutil.rmtree(path, ignore_errors=True)

def magic_convert_function(text):
    with mkdtemp() as outdir:
        with mkdtemp() as indir:
            with open(os.path.join(indir, 'test.rst'), 'w') as infile:
                infile.write(text)

            support = WebSupport(srcdir=indir,
                                 builddir=outdir,
                                 search='xapian')
            support.build()

            contents = support.get_document('test')
            return contents['body']

rawDescription: Is there any API for formatting Sphinx text?


code:
import requests

headers = {
   'Accept': 'application/xml',
}

r = requests.get('http://gagnaveita.vegagerdin.is/api/faerd2014_1', headers=headers)

print(r.content)
#print(r.json())

rawDescription: Python parse XML from online web service


code:
Numbers = [1, 2, 3, 4, 5]
x_list = list(combinations(Numbers, 2))
new_list1, new_list2 = list(filter(lambda x: 1 in x, x_list)) ,list(filter(lambda x: x[0] % 2 and x[1] % 2, x_list))

rawDescription: Python 3.4.1 - Elements in Nested List

description: Python 3.4.1 - Elements in Nested List


code:
import ctypes

SendInput = ctypes.windll.user32.SendInput

# C struct redefinitions
PUL = ctypes.POINTER(ctypes.c_ulong)
class KeyBdInput(ctypes.Structure):
    _fields_ = [("wVk", ctypes.c_ushort),
                ("wScan", ctypes.c_ushort),
                ("dwFlags", ctypes.c_ulong),
                ("time", ctypes.c_ulong),
                ("dwExtraInfo", PUL)]

class HardwareInput(ctypes.Structure):
    _fields_ = [("uMsg", ctypes.c_ulong),
                ("wParamL", ctypes.c_short),
                ("wParamH", ctypes.c_ushort)]

class MouseInput(ctypes.Structure):
    _fields_ = [("dx", ctypes.c_long),
                ("dy", ctypes.c_long),
                ("mouseData", ctypes.c_ulong),
                ("dwFlags", ctypes.c_ulong),
                ("time",ctypes.c_ulong),
                ("dwExtraInfo", PUL)]

class Input_I(ctypes.Union):
    _fields_ = [("ki", KeyBdInput),
                 ("mi", MouseInput),
                 ("hi", HardwareInput)]

class Input(ctypes.Structure):
    _fields_ = [("type", ctypes.c_ulong),
                ("ii", Input_I)]

# Actuals Functions
def PressKey(hexKeyCode):
    print('a')
    extra = ctypes.c_ulong(0)
    ii_ = Input_I()
    ii_.ki = KeyBdInput( hexKeyCode, 0x48, 0, 0, ctypes.pointer(extra) )
    x = Input( ctypes.c_ulong(1), ii_ )
    SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))

def ReleaseKey(hexKeyCode):
    print('b')
    extra = ctypes.c_ulong(0)
    ii_ = Input_I()
    ii_.ki = KeyBdInput( hexKeyCode, 0x48, 0x0002, 0, ctypes.pointer(extra) )
    x = Input( ctypes.c_ulong(1), ii_ )
    SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))

def PressEnter():
    time.sleep(2)
    print('Running: Press Enter')
    PressKey(0x0D)      # 0x0D = Enter
    time.sleep(0.2)
    ReleaseKey(0x0D)

rawDescription: Python - Similate RETURN keyboard press

description: Python - Similate RETURN keyboard press


rawDescription: Python: test function changes value

description: Python: test function changes value


code:
students.objects.filter(student_id__contains="97318") \
                .extra({'stident_id_uint': "CAST(student_id as UNSIGNED)"}) \
                .order_by('-student_id_uint')

rawDescription: How do i cast char to integer while querying in django ORM?

description: Cast char to integer while querying in django ORM


code:
from queue import Queue

class MyQueue(Queue):

    def put(self, item, block=True, timeout=None):
        ...

    def get(self, block=True, timeout=None):
        ...

rawDescription: Heavy I/O and python multiprocessing/multithreading


code:
class cached_property(object):
    """Define property caching its value on per instance basis.
    Decorator that converts a method with a single self argument into a
    property cached on the instance.
    """
    def __init__(self, method):
        self.method = method

    def __get__(self, instance, type):
        res = instance.__dict__[self.method.__name__] = self.method(instance)
        return res

rawDescription: python call set property when property missing

description: Python call set property when property missing


code: df1 = df1.merge(df2[['weeknum', 'datetime']], on=['weeknum'])

rawDescription: Pandas lookup, mapping one column in a dataframe to another in a different dataframe


code:
def update_xml_file(sender, instance=False, **kwargs):
    f = open('channelrss.xml', 'w')
    f.write(render_to_string('podcast/show_feed.html', {'object': instance.show}))
    f.close()

rawDescription: Accessing objects with a foreign key relationship in Django?


code:
dates = pd.Series(np.arange(30),
                  index=pd.date_range('2015-10-1', periods=30, freq='D'))
dates.resample('W', 'sum')
dates.resample('W-MON', 'sum')

rawDescription: Change week definition in pandas resample


code:
from IPython.display import YouTubeVideo
# a talk about IPython at Sage Days at U. Washington, Seattle.
# Video credit: William Stein.
YouTubeVideo('1j_HxD4iLn8')

rawDescription: Displaying a Youtube clip in python

description: Displaying a Youtube clip in python


code:
import ast
x = "[1,'Hello',['test','3'],True,2.532]"
y = ast.literal_eval(x)
y
z = str(y)
z

rawDescription: Convert an Array, converted to a String, back to an Array


code: np.pad(A, 1, 'edge')

rawDescription: How can I make a padded numpy array using the first/last row/column as the pad?

description: Make a padded numpy array using the first/last row/column as the pad


code:
timeit("all(b.read(20) for x in xrange(0, 20000000,20)  ) ", "b=open('data.dat')", number=1)
c = open("data.dat").read()
len(c)

rawDescription: Efficient data interchange format using only C-style fprintf() statements?


code:
import wx
import wx.animate

class MyPanel(wx.Panel):

    def __init__(self, parent, id):

        wx.Panel.__init__(self, parent, id)
        self.SetBackgroundColour("black")
        gif_fname = "skYmk.gif"
        gif = wx.animate.GIFAnimationCtrl(self, id, gif_fname, pos=(10, 10))
        gif.GetPlayer().UseBackgroundColour(True)

        self.gif = gif

    def CallMeLater(self, play=True):

        if play:
            self.gif.Play()
        else:
            self.gif.Stop()

app = wx.PySimpleApp()
frame = wx.Frame(None, -1, "wx.animate.GIFAnimationCtrl()", size = (200, 220))
MyPanel(frame, -1)
frame.Show(True)
app.MainLoop()

rawDescription: Animating gif in wxPython

description: Animating gif in wxPython


rawDescription: How was this data conversion performed exactly?


code:
def get(self, **kwargs):
    """
    overwriting get to always include the contact information
    """
    return super(ParentRecordManager, self).select_related(
        'contact'
    ).get(**kwargs)

def filter(self, **kwargs):
    """
    overwriting filter to always include contact in the filter
    :param kwargs:
    :return:
    """
    return super(ParentRecordManager, self).select_related(
        'contact'
    ).filter(**kwargs)

rawDescription: Simplest solution to load foreignkey model with parent


code: num_unique_in_first_column = len(collections.Counter(map(operator.itemgetter(0), rows)))

rawDescription: Parsing through large files, counting the number of unique strings?


code:
f = open('file.ext', 'w')
p = psutil.Process(os.getpid())
p.get_open_files()

rawDescription: Check for open files with Python in Linux


code:
from itertools import islice
l = ['a', 'b', 'c', 'd', 'e', 'f']
n = [2, 1, 3]
it = iter(l)
out = [list(islice(it, size)) for size in n]
out

rawDescription: split list in sub lists by number of elements

description: Split list in sub lists by number of elements


code:
lines = fp.readlines()
new_lines = lines[:loc] + lines_to_add + lines[loc:]

rawDescription: Inserting some lines in btw a file using Python


rawDescription: Find the max value in a dictionary

description: Find the max value in a dictionary


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

plt.figure()
plt.axis([0, 6000, 0, 45000])

# From your example I am assuming that the maximum value is 6000
binBoundaries = np.linspace(0,6000,201)

data['column'][data.value == 0].hist(bins=binBoundaries, label='A')
data['column2'][data.value == 1].hist(bins=binBoundaries, label='B')

plt.title('A Histogram')
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.legend()

rawDescription: Python pyplot histogram: Adjusting bin width, Not number of bins


code:
from datetime import datetime, timedelta

target_time = datetime.now() - timedelta(hours=24)
my_items = MyModel.objects.filter(obj_time__gte=target_time)

rawDescription: How to do a query based on a subtraction result of two datetime objects in a Django query?

description: Do a query based on a subtraction result of two datetime objects in a Django query


code:
s = search.Search()
s = s.fields(["field1", "field2"])
...

rawDescription: How to select specific fields in elasticsearch-dsl python

description: Select specific fields in elasticsearch-dsl python


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

fig, axs = plt.subplots(1,1,figsize=(15,10))

axs.imshow(np.random.rand(50,100) ,cmap='gray', interpolation='none', alpha=0.3)

nplots = 50

fig.canvas.draw()

box = axs._position.bounds
height = box[3] / nplots

for i in arange(nplots):

    tmpax = fig.add_axes([box[0], box[1] + i * height, box[2], height])
    tmpax.set_axis_off()

    tmpax.plot(np.sin(np.linspace(0,np.random.randint(20,1000),1000))*0.4)
    tmpax.set_ylim(-1,1)

rawDescription: overlay matplotlib imshow with line plots that are arranged in a grid

description: Overlay matplotlib imshow with line plots that are arranged in a grid


code:
from graphics import *

window = GraphWin("game", 400, 400)
myimage=Image(Point(200,200),"flower.png")
myimage.draw(window)

rawDescription: How to set picture as background in python? I am only importing Graphics. No pygames or turtles

description: Set picture as background in python? I am only importing Graphics. No pygames or turtles


rawDescription: does python have a comma operator like C

description: Does python have a comma operator like C


code:
import csv
with open("hwa.csv", "rb") as fp:
    reader = csv.DictReader(fp)
    data = next(reader)

data
data["Age"]
float(data["Age"])

rawDescription: How to extract certain csv data based on the header in python

description: Extract certain csv data based on the header in python


rawDescription: cornerWidget disappears when there isn't any tab

description: CornerWidget disappears when there isn't any tab


rawDescription: Evaluate a number from a dataset

description: Evaluate a number from a dataset


code:
import xattr
import biplist

def write_xattr_tags(file_path, tags):
    bpl_tags = biplist.writePlistToString(tags)
    optional_tag = "com.apple.metadata:"
    map(lambda a: xattr.setxattr(file_path, optional_tag + a, bpl_tags),
        ["kMDItemFinderComment", "_kMDItemUserTags", "kMDItemOMUserTags"])

rawDescription: Using multiple keywords in xattr via _kMDItemUserTags or kMDItemOMUserTags


code:
class Grid:
    def __init__(self, cellNum, cellData):
        self.cellNum = cellNum
        self.cellData = cellData

rawDescription: Initating variables in Python

description: Initating variables in Python


code:
def getAddress(rawList):
    toRet = []
    for item in rawList:
        item = item.remove("/>\n")
        rawArr = item.split(" ")
        tempDict = {}
        for x in rawArr:
            y = x.split("=")
            y[1] = y[1:]
            y[1] =y[:- 1]
            tempDict[y[0]] = y[1]
        addr = [tempDict["Street"], tempDict["HouseNo"], tempDict["City"], tempDict["Zip"], tempDict["Country"]]
        toRet.append(' '.join(addr))
    return toRet

rawDescription: Extract desired part of a list - PYTHON

description: Extract desired part of a list - PYTHON


code:
d = ssp.lil_matrix((3,3))
d.setdiag(np.ones(3)*3)
a*d
(a*d).todense()

rawDescription: How to elementwise-multiply a scipy.sparse matrix by a broadcasted dense 1d array?

description: Elementwise-multiply a scipy.sparse matrix by a broadcasted dense 1d array


code:
#!/usr/bin/env python
import numpy as np
from matplotlib import pyplot as plt

# generate data
x = np.r_[0:100:30j]
y = np.r_[0:1:20j]
X, Y = np.meshgrid(x, y)
Z = X*np.exp(1j*Y) # some arbitrary complex data

# plot it
def plotit(z, title):
    plt.figure()
    cs = plt.contour(X,Y,z) # contour() accepts complex values
    plt.clabel(cs, inline=1, fontsize=10) # add labels to contours
    plt.title(title)
    plt.savefig(title+'.png')

plotit(Z, 'real')
plotit(Z.real, 'explicit real')
plotit(Z.imag, 'imagenary')

plt.show()

rawDescription: Use matplotlib.contour with complex data


code:
from config.TestClass import TestClass
TestClass.add_key( "mykey", "newvalue" )

rawDescription: Python class method - Is there a way to make the calls shorter?


code:
connection = MySQLdb.Connect(host='**', user='**', passwd='**', db='**')
cursor = connection.cursor()
query = "LOAD DATA INFILE '/path/to/my/file' INTO TABLE sometable FIELDS TERMINATED BY ';' ENCLOSED BY '\"' ESCAPED BY '\\\\'"
cursor.execute( query )
connection.commit()

rawDescription: MySQL LOAD DATA LOCAL INFILE example in python?


code:
for i in numbersList:
    print(i, i*i)

rawDescription: Printing the number from a list and its square on the same line in python3


code:
class SiteMiddleware(object):
    def process_request(self, request):
        try:
            current_site = Site.objects.get(domain=request.get_host())
        except Site.DoesNotExist:
            current_site = Site.objects.get(id=settings.DEFAULT_SITE_ID)

        request.current_site = current_site
        settings.SITE_ID = current_site.id

rawDescription: Django: Dynamically set SITE_ID in settings.py based on URL?


code:
M = {(1, 0, 0): 2,
     (1, 1, 2): 3,
     (1, 1, 3): 1,
     (1, 2, 4): 5,
     (2, 1, 3): 4,
     (2, 2, 2): 1}
import itertools
newM = {
    key: {k[1:]: M[k] for k in grp}
    for key, grp in
    itertools.groupby(sorted(M), key=lambda k: k[0])
}  # nested dict comprehension
newM

rawDescription: efficient way of grouping dictionary by fist item of key-tuple

description: Efficient way of grouping dictionary by fist item of key-tuple


code:
def __lt__(self, other):
    for offset in range(len(self.original)):
        if self.getOffset(offset) < other.getOffset(offset):
            return True
        elif self.getOffset(offset) > other.getOffset(offset):
            return False
    return False

rawDescription: Implementation of __lt__ to sort list

description: Implementation of __lt__ to sort list


code:
import re
re.sub('<.*?>', '', string)
"i think mabe 124 + but I don't have a big experience it just how I see it in my eyes fun stuff"

rawDescription: Remove Sub String by using Python

description: Remove Sub String by using Python


code:
from bs4 import BeautifulSoup
import requests

myurl = "http://finance.yahoo.com/q/cp?s=^DJI"
# I use requests to get the html content
html = requests.get(myurl).content
soup = BeautifulSoup(html)

# you don't need to iterate the children, just use find
# and you need to use attrs { key: value }, not just 'time_rtq_ticker'
soup.find('span', attrs={'class':'time_rtq_ticker'}).text
u'17,554.47'

rawDescription: Scraping Yahoo Finance for Dow Index in Python


rawDescription: Read values from txt with rows of different sizes into a single numpy array


code:
def find_nth(needle,haystack, n):
    start = haystack.find(needle)
    while start >= 0 and n > 1:
        start = haystack.find(needle, start+len(needle))
        n -= 1
    return start

for i in range(len(s1)) :
        occurrence= s1[:i+1].count(s1[i])

        j=find_nth(s1[i], s2, occurrence)

rawDescription: python find position of characters in a string ignoring special characters in this string

description: Python find position of characters in a string ignoring special characters in this string


code:
import matplotlib.pyplot as plt

x = y = [1,2,3,4,5]
fig, ax = plt.subplots()
ax.plot(x,y)

leg = ax.legend(['line 1'], loc=6, frameon=False)

fig.canvas.draw()

p = leg.get_window_extent().inverse_transformed(ax.transAxes)

ax.annotate('Annotation Text', (p.p0[0], p.p1[1]), xycoords='axes fraction')

rawDescription: why unnable to do annotation adjacent to legend?

description: Why unnable to do annotation adjacent to legend


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

from scipy.ndimage import zoom
from mpl_toolkits.mplot3d import axes3d

# Receive standard Matplotlib data for 3d plot
X, Y, Z = axes3d.get_test_data(1) # '1' is a step requested data

#Calculate smooth data
pw = 10 #power of the smooth
Xsm = zoom(X, pw)
Ysm = zoom(Y, pw)
Zsm = zoom(Z, pw)

# Create blank plot
fig = plt.figure()
#Create subplots
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)
# Plotting
ax1.contour(X, Y, Z)
ax2.contour(Xsm, Ysm, Zsm)

plt.show()

rawDescription: Matplotlib: Data cubic interpolation (or FIT) for Contour plot


code:
def primesbelow(N):
    # http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188
    #""" Input N>=6, Returns a list of primes, 2 <= p < N """
    correction = N % 6 > 1
    N = (N, N-1, N+4, N+3, N+2, N+1)[N%6]
    sieve = [True] * (N // 3)
    sieve[0] = False
    for i in range(int(N ** .5) // 3 + 1):
        if sieve[i]:
            k = (3 * i + 1) | 1
            sieve[k*k // 3::2*k] = [False] * ((N//6 - (k*k)//6 - 1)//k + 1)
            sieve[(k*k + 4*k - 2*k*(i%2)) // 3::2*k] = [False] * ((N // 6 - (k*k + 4*k - 2*k*(i%2))//6 - 1) // k + 1)
    return [2, 3] + [(3 * i + 1) | 1 for i in range(1, N//3 - correction) if sieve[i]]

rawDescription: Why is this algorithm worse?

description: Why is this algorithm worse


rawDescription: eliminate whitespaces in pd.read_csv

description: Eliminate whitespaces in pd.read_csv


code:
class BlogComment(models.Model):
    blog = models.ForeignKey(Blog)
    user = models.ForeignKey(User)
    unapproved = models.Charfield(max_length=1000, default=None, Blank=True)
    approved = models.Charfield(max_length=1000, default=None, Blank=True)

# on submit
BlogComment.unapproved = request.POST['user_comment']

# on approve
BlogComment.approved = BlogComment.unapproved
BlogComment.unapproved = None
BlogComment.save()

rawDescription: django - how to save modified form without overriding original entry

description: Django - how to save modified form without overriding original entry


code:
import win32print, win32ui, win32gui
import win32con, pywintypes

# create a dc (Device Context) object (actually a PyCDC)
dc = win32ui.CreateDC()

# convert the dc into a "printer dc"

# get default printer
printername = win32print.GetDefaultPrinter ()
# leave out the printername to get the default printer automatically
dc.CreatePrinterDC(printername)

# you need to set the map mode mainly so you know how
# to scale your output.  I do everything in points, so setting
# the map mode as "twips" works for me.
dc.SetMapMode(win32con.MM_TWIPS) # 1440 per inch

# here's that scaling I mentioned:
scale_factor = 20 # i.e. 20 twips to the point

# start the document.  the description variable is a string
# which will appear in the print queue to identify the job.
dc.StartDoc('Win32print test')

# to draw anything (other than text) you need a pen.
# the variables are pen style, pen width and pen color.
pen = win32ui.CreatePen(0, int(scale_factor), 0)

# SelectObject is used to apply a pen or font object to a dc.
dc.SelectObject(pen)

# how about a font?  Lucida Console 10 point.
# I'm unsure how to tell if this failed.
font = win32ui.CreateFont({
    "name": "Lucida Console",
    "height": int(scale_factor * 10),
    "weight": 400,
})

# again with the SelectObject call.
dc.SelectObject(font)

# okay, now let's print something.
# TextOut takes x, y, and text values.
# the map mode determines whether y increases in an
# upward or downward direction; in MM_TWIPS mode, it
# advances up, so negative numbers are required to
# go down the page.  If anyone knows why this is a
# "good idea" please email me; as far as I'm concerned
# it's garbage.
dc.TextOut(scale_factor * 72,
    -1 * scale_factor * 72,
    "Testing...")

# for completeness, I'll draw a line.
# from x = 1", y = 1"
dc.MoveTo((scale_factor * 72, scale_factor * -72))
# to x = 6", y = 3"
dc.LineTo((scale_factor * 6 * 72, scale_factor * 3 * -72))

# must not forget to tell Windows we're done.
dc.EndDoc()

rawDescription: How to print directly without showing print dialog using python script in windows?

description: Print directly without showing print dialog using python script in windows


code:
class MyClass(models.Model):
    title = models.CharField(max_length=255)
    slug = models.SlugField(max_length=300)

    @property
    def url_slug(self):
        return '{}-{}'.format(self.slug, self.id)

rawDescription: Django: saving unique entries by automatically appending a counter to the title/slug


code:
import re
import locale

# Remove anything not a digit, comma or period
no_cruft = re.sub(r'[^\d,.-]', '', st)

# Split the result into parts consisting purely of digits
parts = re.split(r'[,.]', no_cruft)

# ...and sew them back together
if len(parts) == 1:
    # No delimeters found
    float_str = parts[0]
elif len(parts[-1]) != 2:
    # >= 1 delimeters found. If the length of last part is not equal to 2, assume it is not a decimal part
    float_str = ''.join(parts)
else:
    float_str = '%s%s%s' % (''.join(parts[0:-1]),
                            locale.localeconv()['decimal_point'],
                            parts[-1])

# Convert to float
my_float = float(float_str)

rawDescription: Parse a string to floats with different separators


code:
grouped = df.groupby('A')
grouped['C'].agg([np.sum, np.mean, np.std])

rawDescription: plyr or dplyr in Python

description: Plyr or dplyr in Python


code:
def markov(L):
   count=0
   c=len(text1)
   for i in range(0,c-2):
       h=L.index(text1[i])
       k=L.index(text1[i+1])
       mat[h,k]=mat[h,k]+1 #matrix

text = [w for g in brown.categories() for w in brown.words(categories=g)]
text1=text[1:500]
arr=set(text1)
arr=list(arr)
mat=lil_matrix((len(arr),len(arr)))
markov(arr)
f = open('spmatrix.pkl','wb')
cPickle.dump(mat,f,-1)
f.close()

rawDescription: Python: how do you store a sparse matrix using python?


code:
m = re.search(r', (?:Staffel|Season|Saison) (\d+)', x);
if (m):
    digits = m.group(1)

rawDescription: Grab digit after one of three words

description: Grab digit after one of three words


rawDescription: Write a method that accesses to a parametric dimension numpy array


code:
figure()
ax = gca()

ax.set_yscale('log')
ax.spines['left'].set_color('#FF9000')
ax.yaxis.label.set_color('#FF9000')

ax.tick_params(axis='y', colors='#FF9000', width=5, which='both')

rawDescription: Set the colour of matplotlib ticks on a log scaled axes


code:
class InterestForm(ModelForm):
    pub_date = DateField(label='Publication date')

    class Meta:
        model = Interest
        exclude = ('userid',)

InterestFormSet = modelformset_factory(Interest, form=InterestForm, extra=2)

rawDescription: Django model formsets - modifying form labels and defaults


code:
b = array([1,2,3])
C = arange(9).reshape(3,3)
dot(diag(b), C)
atleast_2d(b).T * C

rawDescription: numpy: fast way of creating a matrix with entries c_i * C_{ij}

description: Numpy: fast way of creating a matrix with entries c_i * C_{ij}


code:
import os

zfName = 'simonsZip.kmz'
foo = zipfile.ZipFile(zfName, 'w')
foo.write("temp.kml")
# Adding files from directory 'files'
for root, dirs, files in os.walk('files'):
    for f in files:
        foo.write(os.path.join(root, f))
foo.close()
os.remove("temp.kml")

rawDescription: How to zip a folder and file in python?

description: Zip a folder and file in python


code:
def insertion (r, c, grid):
    cellGrid = []
    for x in range(0, r):
        row = []
        for y in range(0, c):
            if (grid[x][y] == '%'):
                what = 0
                cost = 100000000
            elif(grid[x][y] == '-'):
                what = 1
                cost = 1
            elif (grid[x][y] == '.'):
                what = 2
                cost = 0
            else:
                what = 3
            row.append(Cell(what, cost))
        cellGrid.append(row)
    return cellGrid

rawDescription: Creating list of lists containing objects in python


rawDescription: Convert byte string to bytes or bytearray


code:
from scrapy.utils.trackref import iter_all

def close_reactor_if_no_spiders():
    running_spiders = [spider for spider in iter_all('Spider')]

    if not running_spiders:
        reactor.stop()

crawler.signals.connect(close_reactor_if_no_spiders, signal=signals.spider_closed)

rawDescription: How to stop reactor when both spiders finished

description: Stop reactor when both spiders finished


code:
ls = subprocess.Popen(['ls', '/tmp'])
cmd = file("/proc/%d/cmdline" % (ls.pid)).read()

rawDescription: Retrieving the command executed by subprocess


code:
def rec(a, b):
    if isinstance(a, list):
        # If `a` is a list
        for index, item in enumerate(a):
            # then recursively iterate it
            for items in rec(item, b[index]):
                yield items
    else:
        # If `a` is not a list, just yield the current `a` and `b`
        yield a, b

print(list(rec(['a', ['b', ['c', 'd']], 'e'], [1, [2, [3, [4, 5]]], 6])))
# [('a', 1), ('b', 2), ('c', 3), ('d', [4, 5]), ('e', 6)]

rawDescription: Create a list of tuples from two nested lists


code:
a = [[5,5,5,4,6],[3,2,6,6,5],[7,2,2,5,6]]
minn = min(min(x) for x in a) #find the min value
[(i,j) for i,x in enumerate(a) for j,y in enumerate(x) if y==minn]

rawDescription: Returning a list of indexes of the smallest value in a multidimensional list


rawDescription: Downloading a File Protected by NTLM/SSPI Without Prompting For Credentials Using Python on Win32?


code:
ds = datetime.date.today()
dd = datetime.date(2009, 12, 9)
ds - dd

rawDescription: How to compare datetime in Django?

description: Compare datetime in Django


code:
proc = subprocess.Popen(['prog', 'arg'], shell=False, stdin=subprocess.PIPE)
out, err = proc.communicate('some input')

rawDescription: How can I pipe a string to a script when using subprocess.call without a shell

description: Pipe a string to a script when using subprocess.call without a shell


code:
import itertools

def Compare(file1, file2):
    with open(file1+'.txt', 'r') as f1, open(file2+'.txt', 'r') as f2:
        for line in itertools.product(f1, f2): # line equals tuple of (f1[0],f2[0]), (f1[0], f2[1]), etc.
          # lines = [[int(col) for col  in row.split()] for row in line]
          # the tuple only contains 2 elements; first element should go to dict1, second to dict2. Why worry about that with list comprehensions?
          dict1 = {'key': [int(col) for col in line[0].split() ]}
          dict2 = {'key': [int(col) for col in line[1].split() ]}
          print(dict1, dict2)

rawDescription: How do i build a dictionary out of a tuple that holds lists of integers?

description: Build a dictionary out of a tuple that holds lists of integers


code:
re1 = re.compile(r'\[(http[^\s]*)\s(.*)\]')
re2 = re.compile(r'\[(http[^\s]*)\]')
with codecs.open(filename, encoding='utf-8') as F:
    text = F.read()
    pre_filter = re1.sub('\g<2>', text)
    result = re2.sub('\g<1>', pre_filter)

rawDescription: transforming url's, python

description: Transforming url's, python


code:
import matplotlib.pyplot as plt
a = '\\frac{a}{b}'  #notice escaped slash
plt.plot()
plt.text(0.5, 0.5,'$%s$'%a)
plt.show()

rawDescription: Print latex-formula with python

description: Print latex-formula with python


code: match = re.search(r'^(?! *#).*MaxClients ([^,]+)', line )

rawDescription: Python read and search String in a file

description: Python read and search String in a file


code:
tree = {}

for d in objects:
    ids = d['id'].split('.')
    w = d['w']
    # walk into the tree, creating nodes as necessary
    subtree = [0,tree]
    for n in ids:
        if n not in subtree[1]:
            subtree[1][n] = [0,{}] # w, list of nodes
        subtree = subtree[1][n] # recurse
    # subtree is now the relevant node, set w
    subtree[0] = w

## now we have a tree:
## >>> pprint.pprint(tree, width=10)
## {'1': [0.2,
##       {'1': [0.8,
##              {'1': [0.6,
##                     {}],
##               '2': [0.7,
##                     {}],
##               '3': [0.4,
##                     {}]}],
##        '2': [0.2,
##              {'1': [0.3,
##                     {}]}],
##        '3': [0.3,
##              {}]}]}

# now walk the tree and extract the nodes:
result = []
def walk_subtree(subtree, path=[]):
    keyweights = [(subtree[key][0], key) for key in subtree]
    # walk through nodes at this level, outputting.
    for weight, key in sorted(keyweights, reverse=True):
        result.append(('.'.join(path + [key]), weight))
        walk_subtree(subtree[key][1], path=path+[key])

walk_subtree(tree)

##>>> pprint.pprint(result)
##[('1', 0.2),
## ('1.1', 0.8),
## ('1.1.2', 0.7),
## ('1.1.1', 0.6),
## ('1.1.3', 0.4),
## ('1.3', 0.3),
## ('1.2', 0.2),
## ('1.2.1', 0.3)]

rawDescription: "Difficult" sorting under some conditions


code:
def add_invoice(request):
    InvoiceFormSet = inlineformset_factory(Invoice, InvoiceItem)
    if request.POST:
        invoiceForm = InvoiceForm(request.POST)
        invoiceFormSet = InvoiceFormSet(request.POST)
        if invoiceForm.is_valid() and invoiceFormSet.is_valid():
            invoice = invoiceForm.save()
            invoiceItems = invoiceFormSet.save(commit=False)
            for invoiceItem in invoiceItems:
                invoiceItem.invoice = invoice
                invoiceItem.save()
            return redirect('show_invoice', invoice_id=invoice.id)
    else:
        invoiceForm = InvoiceForm()
        invoiceFormSet = InvoiceFormSet()
    context_data = {
            'invoiceForm': invoiceForm,
            'invoiceFormSet': invoiceFormSet,
            }
    return render(request, 'add_invoice.html', context_data)

rawDescription: ModelForm with multiple child models

description: ModelForm with multiple child models


code:
def diskstats_parse(dev=None):
    file_path = '/proc/diskstats'
    result = {}

    # ref: http://lxr.osuosl.org/source/Documentation/iostats.txt
    columns_disk = ['m', 'mm', 'dev', 'reads', 'rd_mrg', 'rd_sectors',
                    'ms_reading', 'writes', 'wr_mrg', 'wr_sectors',
                    'ms_writing', 'cur_ios', 'ms_doing_io', 'ms_weighted']

    columns_partition = ['m', 'mm', 'dev', 'reads', 'rd_sectors', 'writes', 'wr_sectors']

    lines = open(file_path, 'r').readlines()
    for line in lines:
        if line == '': continue
        split = line.split()
        if len(split) == len(columns_disk):
            columns = columns_disk
        elif len(split) == len(columns_partition):
            columns = columns_partition
        else:
            # No match
            continue

        data = dict(zip(columns, split))
        if dev != None and dev != data['dev']:
            continue
        for key in data:
            if key != 'dev':
                data[key] = int(data[key])
        result[data['dev']] = data

    return result

rawDescription: Python library for monitoring /proc/diskstats?


code:
if request.POST:
    f = Create_EventForm(request.POST)
    if f.is_valid():
        event = f.save(commit=False)
        event.other_value = lookup_value()
        event.save()

rawDescription: Add field to django ModelForm that are in the model but not in the form


code:
def contin(message):
    return input(message)

rawDescription: Python input returns None

description: Python input returns None


code:
import sys

for model in (Agent001, Agent002):
    form_name = model.__name__ + 'EditForm'

    class AgentEditForm(forms.ModelForm):
        class Meta:
            model = model
            exclude = ()

    AgentEditForm.__name__ = form_name
    setattr(sys.modules[__name__], form_name , AgentEditForm)
    del AgentEditForm

rawDescription: Django: one ModelForm for subclasses

description: Django: one ModelForm for subclasses


code:
def reverse_bits(x):
    return (int('{:08b}'.format(x)[::-1], 2))

reverse_table = bytes.maketrans(bytes(range(0,256)), bytes(reverse_bits(x) for x in range(0, 256)))

with open('input.txt', 'rb') as f_input, open('output.txt', 'wb') as f_output:
    data = f_input.read()
    f_output.write(data.translate(reverse_table))

rawDescription: Efficient bitswapping in python3

description: Efficient bitswapping in python3


code:
def show_entry_fields():
    global site, score, master
    site = e1.get()
    score = e2.get()
    master.destroy()

rawDescription: tkinter entry variable from function

description: Tkinter entry variable from function


code:
@class_decorator
class SubClassAgain(BaseClass):
    def print_class(self):
        BaseClass.print_class(self)

rawDescription: Class Decorators, Inheritance, super(), and maximum recursion


code:
def split(buf):
    it = buf.get_start_iter()
    while not it.is_end():
        nextpos = it.copy()
        nextpos.forward_to_tag_toggle(None)
        yield buf.get_text(it, nextpos), it.get_tags()
        it = nextpos

rawDescription: Split text buffer text according to tags python gtk


code:
import urllib
import urllib.request
from bs4 import BeautifulSoup

theurl="http://agscompany.com/product-category/fittings/tube-nuts/316-tube/"
for i in range(1,5):
  thepage = urllib.request.urlopen(theurl + '/page/' + str(i) + '/')
  soup = BeautifulSoup(thepage,"html.parser")

  for pn in soup.find_all('div',{"class":"shop-item-text"}):
      pn2 = pn.text
      print(pn2)

rawDescription: slowing down a webscrape using python

description: Slowing down a webscrape using python


code:
import urllib2
import ssl
from suds import transport
from suds.client import Client
from suds.xsd.doctor import Import, ImportDoctor
from pycontrol import pycontrol

IMP = Import('http://schemas.xmlsoap.org/soap/encoding/')
DOCTOR = ImportDoctor(IMP)
ICONTROL_URI = '/iControl/iControlPortal.cgi'
SESSION_WSDL = 'System.Session'

class HTTPSUnVerifiedCertTransport(transport.https.HttpAuthenticated):
    def __init__(self, *args, **kwargs):
        transport.https.HttpAuthenticated.__init__(self, *args, **kwargs)
    def u2handlers(self):
        handlers = []
        handlers.append(urllib2.ProxyHandler(self.proxy))
        handlers.append(urllib2.HTTPBasicAuthHandler(self.pm))
        # python ssl Context support - PEP 0466
        if hasattr(ssl, '_create_unverified_context'):
            ssl_context = ssl._create_unverified_context()
            handlers.append(urllib2.HTTPSHandler(context=ssl_context))
        else:
            handlers.append(urllib2.HTTPSHandler())
        return handlers

def new_get_suds_client(self, url, **kw):
        if not url.startswith('https'):
            t = transport.http.HttpAuthenticated(username=self.username,
                                                 password=self.password)
            c = Client(url, transport=t, username=self.username,
                         password=self.password, doctor=DOCTOR, **kw)
        else:
            t = HTTPSUnVerifiedCertTransport(username=self.username,
                                             password=self.password)
            c = Client(url, transport=t, username=self.username,
                         password=self.password, doctor=DOCTOR, **kw)
        return c

pycontrol.BIGIP._get_suds_client = new_get_suds_client
b = pycontrol.BIGIP(
    hostname = "xx.xx.xx.xx",
    username = "xxxxxxx",
    password = "xxxxxxx",
    fromurl = True,
    wsdls = ['GlobalLB.WideIP','GlobalLB.Pool']
    )

rawDescription: Disable ssl check globally in python 2.7.10 - Pycontrol


code:
import contextlib
import selenium.webdriver as webdriver
import selenium.webdriver.support.ui as ui
with contextlib.closing(webdriver.Firefox()) as driver:
    driver.get('http://www.google.com')
    wait = ui.WebDriverWait(driver, 10) # timeout after 10 seconds
    inputElement = driver.find_element_by_name('q')
    inputElement.send_keys('python')
    inputElement.submit()
    results = wait.until(lambda driver: driver.find_elements_by_class_name('g'))
    for result in results:
        print(result.text)
        print('-'*80)

rawDescription: How can I make Selenium/Python wait for the user to login before continuing to run?

description: Make Selenium/Python wait for the user to login before continuing to run


code:
myTuples = tuple(map(tuple, myList))

cursor.execute("update tablename set flag = 'yes' \
where (id, officeid) in " + str(myTuples))

rawDescription: How to use MySQL executemany to update list of lists in Python?

description: Use MySQL executemany to update list of lists in Python


code:
import re

def parse_users(value):
    usernames = re.findall(r"@\w+", value)
    for username in usernames:
        value = value.replace(username, str(len(username[1:])))

rawDescription: Replace contents after specific character using template filter in django


code:
class MyModel(model.Model):
    image=models.ImageField(upload_to='folder')
    url=models.CharField(...)

    def save(self, *args, **kwargs):
        self.url = self.image.url
        super(Model, self).save(*args, **kwargs)

rawDescription: Is it possible to query Files by their URL in django?


code:
from nltk.corpus import cess_esp as cess
from nltk import UnigramTagger as ut
from nltk import BigramTagger as bt

# Read the corpus into a list,
# each entry in the list is one sentence.
cess_sents = cess.tagged_sents()

# Train the unigram tagger
uni_tag = ut(cess_sents)

sentence = "Hola , esta foo bar ."

# Tagger reads a list of tokens.
uni_tag.tag(sentence.split(" "))

# Split corpus into training and testing set.
train = int(len(cess_sents)*90/100) # 90%

# Train a bigram tagger with only training data.
bi_tag = bt(cess_sents[:train])

# Evaluates on testing data remaining 10%
bi_tag.evaluate(cess_sents[train+1:])

# Using the tagger.
bi_tag.tag(sentence.split(" "))

rawDescription: NLTK Tagging spanish words using a corpus


code: result = max(pairs, key=m)

rawDescription: Most Pythonic Way to Select Particular Tuple from List of Tuples


code:
header = {'HTTP_X_HTTP_METHOD_OVERRIDE': 'PUT'}
response = client.post('/model/1/', content_type='application/json', data=post_data_clean, **header)

rawDescription: Django Test Client Method Override Header


code:
from __future__ import division
from pprint import pprint

weeks = [
    [{u'_id': 193390, u'avgT': 12, u'avgByS': [{u'S': 7, u'avg': 12}]}, {u'_id': 193396, u'avgT': 29, u'avgByS': [{u'S': 7, u'avg': 29}, {u'S': 5, u'avg': 29}]}],
    [{u'_id': 193390, u'avgT': 11, u'avgByS': [{u'S': 7, u'avg': 10}, {u'S': 9, u'avg': 12}]}, {u'_id': 193398, u'avgT': 15, u'avgByS': [{u'S': 7, u'avg': 29}, {u'S': 5, u'avg': 29}]},{u'_id': 193396, u'avgT': 29, u'avgByS': [{u'S': 7, u'avg': 29}, {u'S': 5, u'avg': 29}]}]
]

# First, accumlate the data. Convert lists to dicts.
total = {}
for week in weeks:
    for product in week:
        total_product = total.setdefault(
            product['_id'],
            {
                u'_id':product['_id'],
                u'avgT':[],
                u'avgByS':{}
            })
        total_product['avgT'].append(product['avgT'])
        for store in product['avgByS']:
            total_product['avgByS'].setdefault(store['S'],[]).append(store['avg'])
pprint (total)

# Next, convert dicts to lists and compute averages.
averages = [{
    u'_id': k,
    u'avgT': sum(v['avgT'])/len(v['avgT']),
    u'avgByS': [{
        u'S': kk,
        u'avg': sum(vv)/len(vv),
        }
        for kk,vv in sorted(v['avgByS'].items())]
    }
    for k,v in sorted(total.items())]
pprint(averages)

rawDescription: Fastest way of averaging multiple list of different length in Python


code:
#!/usr/bin/python
from os import listdir
from PIL import Image as PImage

def loadImages(path):
    # return array of images

    imagesList = listdir(path)
    loadedImages = []
    for image in imagesList:
        img = PImage.open(path + image)
        loadedImages.append(img)

    return loadedImages

path = "/path/to/your/images/"

# your images in an array
imgs = loadImages(path)

for img in imgs:
    # you can show every image
    img.show()

rawDescription: How to load images from a directory on the computer in Python

description: Load images from a directory on the computer in Python


code:
def decorator(obj):
    old_func = obj.func # can't call 'by name' because of recursion

    def decorated_func(self):
        # do my stuff here
        old_func() # does not need pass obj
        # do some othere stuff here

    # here is the magic, this get the type of a 'normal method' of a class
    method = type(obj.func)

    # this bounds the method to the object, so self is passed by default
    obj.func = method(decorated_func, obj)

rawDescription: How to decorate an object method?

description: Decorate an object method


code:
import re
import socket
for i, (doc_id, user) in enumerate(ids):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print("\033[1;31m~~~Documnent~~~NB~~~"+str(i+1)+"\033[1;m")
    s.connect(('127.0.0.1', 1234))
    s.sendall('load_document {}\n'.format(doc_id))
    buf = []
    while True:
        r = s.recv(4096).strip()
        print('Got {} for socket'.format(r))
        buf.append(r)
        if r.endswith('.pdf'):
            print('Done')
            break
    result = '\n'.join(buf)
    s.close()
    with open(logtxt, 'a') as f:
        f.write('Document ID= {}\n'.format(doc_id))
        f.write('From User = {}\n'.format(user))
        f.write('{}\n'.format(result))
    filename = re.search('Saved to (.+)$', result).group(1)
    checkandcopy(filename, userdir)

rawDescription: Daemon Output not being written to a TXT


code:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

wait = WebdriverWait(driver, 10)
wait.until(EC.presence_of_element_located((By.ID, "myid")))

print(driver.page_source)

rawDescription: Different page's source code between selenium and the browser itself


code:
class PageLink(Base):
    '''
    Association table.
    '''
    __tablename__ = 'page_links'

    id = Column(Integer,primary_key=True)
    page_from = Column(Integer,ForeignKey('page.id'),primary_key=True)
    page_to = Column(Integer,ForeignKey('page.id'),primary_key=True)
    extra_col1 = Column(String(256),nullable=False)

class Page(Base):
    '''
    main table
    '''

    __tablename__ = 'page'

    id = Column(Integer,primary_key=True)
    name = Column(String(56),nullable=False)

    linked_to = relationship('PageLinks',backref='parent_page',
                             primaryjoin=id==PageLink.page_from)
    linked_from = relationship('PageLinks',backref='child_page',
                               primaryjoin=id==PageLink.page_to)

rawDescription: SQLAlchemy configuring many-to-many relationship to self using Association


code:
class Note(models.Model):
    datetime = models.DateTimeField(default=datetime.now)
    user  = models.ForeignKey(User)
    note = models.TextField()

    def __unicode__(self):
        return unicode(self.user)

class Client(models.Model):
    name = models.CharField(max_length = 40)
    telephone = models.CharField(max_length = 20)
    website = models.URLField(verify_exists = False)
    fax = models.CharField(max_length = 20)
    email = models.EmailField()
    is_active = models.BooleanField()
    note = models.OneToOneField(Note)

    def __unicode__(self):
        return self.name

rawDescription: Django: model question

description: Django: model question


code: [item for item, lemm in list1 for w in list2 if w == lemm]

rawDescription: multiple iteration for finding shared items in two lists

description: Multiple iteration for finding shared items in two lists


code:
class Item(models.Model):
    item_id = models.IntegerField()
    name = models.CharField(max_length=200)
    rarity = models.CharField(max_length=200)

class Bet(models.Model):
    bet_id = models.IntegerField()
    user_id = models.IntegerField()
    user_name = models.CharField(max_length=200)
    items = models.ManyToManyField(Item)

rawDescription: correct structure for django model

description: Correct structure for django model


code:
from tkinter import *

class Run:
    def __init__(self):
        self.root = Tk()
        self.root.overrideredirect(True)
    def put_back(self):
        # this method will put the window to the background
        self.root.lower()
        # recursive calling of put_back method
        self.root.after(100, self.put_back)

app = Run()
# Start the recursion
app.put_back()
app.root.mainloop()

rawDescription: Make Tkinter window not always on top

description: Make Tkinter window not always on top


code:
def view_unique_assessments(request):
    all_assessments = api.retrieve_assessments()
    assessments_by_microseries = {}

    for x in all_assessments:
        if x.microseries in assessments_by_microseries:
            print("Already seen this microseries: %s" % x.microseries)
        else:
            assessments_by_miniseries[x.microseries] = x

    unique_assessments = sorted(assessments_by_microseries.values())
    return {'logged_in': logged_in_userid, 'unique_assessments': unique_assessments}

rawDescription: Looping through a list of object/values, remove duplicates, and return unique value in View (python)


code:
common_elements = set(a) & set(b)
for item in a:
    if item in common_elements:
        pass # do something
    else:
        pass # do something else instead

rawDescription: Comparing two lists item by item

description: Comparing two lists item by item


code:
from pyspark.sql.functions import coalesce

df1 = df1.alias("df1")
df2 = df2.alias("df2")

(df1.join(df2, df1.name == df2.name, 'outer')
  .withColumn("name_", coalesce("df1.name", "df2.name"))
  .drop("name")
  .withColumnRenamed("name_", "name"))

rawDescription: Outer join Spark dataframe with non-identical join column and then merge join column


code:
import warnings

def fxn():
    warnings.warn("deprecated", DeprecationWarning)

with warnings.catch_warnings(record=True) as w:
    # Cause all warnings to always be triggered.
    warnings.simplefilter("always")
    # Trigger a warning.
    fxn()
    # Verify some things
    assert len(w) == 1
    assert issubclass(w[-1].category, DeprecationWarning)
    assert "deprecated" in str(w[-1].message)

rawDescription: In python, how does one catch warnings as if they were exceptions?


code: print(df[ np.abs(df.Data - df.Data.mean()) > 1.5*df.Data.std() ])

rawDescription: Get outliers in a DataFrame with date

description: Get outliers in a DataFrame with date


code:
import xlrd
import numpy as np
from os import listdir, chdir
import calendar
import re

direction = {'N':0,'S':1,'E':2,'W':3}
rend = [0, 40, 37, 40, 39, 40, 39, 40, 40, 39, 40, 39, 40]

# Initialize the matrix to store final result
aData = np.matrix(np.zeros((0,7)))

# get all the xlsx files from the directory.
filenames = [ f for f in listdir('.') if f.endswith('.xlsx') ]

# for each .xlsx in the current directory
for file in filenames:
    # The file names are in the format gdot_39446_yyyy_mm.xlsx
    # yyyy is the year and mm is the month number with 0 -Jan and 11 - Dec
    # I extracted the month and year info from the file name

    ms = re.search('.+_.+_.+_([0-9]+)\.',file,re.M).group(1)
    month = int(ms) + 1
    year = int(file[11:15])

    # open the workbook
    workbook = xlrd.open_workbook(file)

    # the workbook has three sheets. I want information from
    # sheet2 and sheet3 (indexed by 1 adn 2 resp.)
    for i in range(1,3):
        sheet = workbook.sheet_by_index(i)
        di =  sheet.name[-1]
        data = [[sheet.cell_value(r,c) for c in range(2,26)] for r in range(9,rend[month])]

        mData = np.matrix(data)
        mData[np.where(mData=='')] = 0 # some cells are blank. Insert 0 in those cells
        n,d = mData.shape
        rows = n * d

        rData = np.matrix(np.zeros((rows,7)))
        rData[:,0].fill(direction[di])
        rData[:,1].fill(year)
        rData[:,2].fill(month)
        for i in range(rows):
            rData[i,3] = (i/24) + 1
            rData[i,4] = calendar.weekday(year,month,(i/24) + 1)
            rData[i,5] = i%24

        for i in range(n):
            rData[i*24:((i+1)*24),6] = mData[i,:].T

        aData = np.vstack((aData,rData))

    np.savetxt("alldata.csv",aData, delimiter=',', fmt='%s')

rawDescription: Converting table to list in Excel

description: Converting table to list in Excel


code:
logger2 = logging.getLogger('extensive')
logfile = logging.FileHandler("test.log")
logger2.handlers = []
logger2.addHandler(logfile)

rawDescription: using dictConfig in python logging, need to create a logger with a different file than defined in dict.

description: Using dictConfig in python logging, need to create a logger with a different file than defined in dict.


code:
from rae import Drae

drae = Drae()

if text.startswith('/'):
  if text.startswith('/define'):
    try:
      [command, data] = text.split(' ',1)
    except:
      send('Write: /define <word>')
    meanings = drae.search(data)
    reply(str(meanings))
    setEnabled(chat_id, True)

rawDescription: Telegram BOT -- Implementing the search in a dictionary


code:
df = pd.concat([DataFrame({'M': [1, 2], 'F': [2, 5]}), \
                DataFrame({'M': [1, 5], 'F': [2, 7]})], \
                axis=1, keys=['Completed', 'Not Completed'])

df.index = ['A', 'B']

df.index.name = 'Name'

rawDescription: Pandas Data Frame Column structure

description: Pandas Data Frame Column structure


code:
from fabric.api import settings

with settings(remote_interrupt=True):
    sudo(...)

rawDescription: How to stop remote script in Fabric

description: Stop remote script in Fabric


code:
import timeit
a = (timeit.timeit("l.append('Cheese')", setup="l=['Meat', 'Milk']"))
b = (timeit.timeit("l+=['Cheese']", setup="l=['Meat', 'Milk']"))
c = (timeit.timeit("append('Cheese')", setup="l=['Meat', 'Milk'];append = l.append"))
print ('a', a)
print ('b', b)
print ('c', c)
print ("==> " , (c < a < b))

rawDescription: In Python 3, what is the most efficient way to change the values in a list?


code:
import os
import sys

directory = os.path.dirname(os.path.realpath(sys.argv[0])) #get the directory of your script
for subdir, dirs, files in os.walk(directory):
 for filename in files:
  if filename.find('.jpg') > 0:
   subdirectoryPath = os.path.relpath(subdir, directory) #get the path to your subdirectory
   filePath = os.path.join(subdirectoryPath, filename) #get the path to your file
   newFilePath = filePath.replace(".jpg",".jpeg") #create the new name
   os.rename(filePath, newFilePath) #rename your file

rawDescription: Recursively rename file extensions

description: Recursively rename file extensions


code:
entity = Model(**kwargs)
for name in entity._properties:
    val = getattr(enitity, name)

rawDescription: How to get rid of _BaseValue

description: Get rid of _BaseValue


code:
import pickle

class MyClass:
    def __init__(self,name):
        self.name = name
    def display(self):
        print(self.name)

my = MyClass("someone")
pickle.dump(my, open("myobject", "wb"))
me = pickle.load(open("myobject", "rb"))
me.display()

rawDescription: Save a class into a binary file - Python


code:
fun = lambda x: x**2 # Example function
N = 10 # Number of data points
x = np.linspace(0., 200., N) # Creates an array of N points
bins = fun(x) # Applies fun to all values in array x

rawDescription: bin width according to custom function

description: Bin width according to custom function


code:
from datetime import datetime
val = '2013-01-09 06:13:51,464'.split(',')[0]  # Remove milliseconds
date_object = datetime.strptime(val, '%Y-%m-%d %H:%M:%S')

rawDescription: Extracting time from a line in Python

description: Extracting time from a line in Python


code: func = getattr(_tmp, func_name)

rawDescription: Importing using string in Python

description: Importing using string in Python


code:
SORT_ORDER = {"DINT": 0, "INT": 1, "BOOL": 2}

mylist.sort(key=lambda val: SORT_ORDER[val[1]])

rawDescription: Sort a list with a custom order in Python


code:
def test_update_result(self):
    obj = MyModel.objects.create(val=1)
    MyModel.objects.filter(pk=obj.pk).update(val=F('val') + 1)
    # At this point obj.val is still 1, but the value in the database
    # was updated to 2. The object's updated value needs to be reloaded
    # from the database.
    obj.refresh_from_db()
    self.assertEqual(obj.val, 2)

rawDescription: Reload django object from database

description: Reload django object from database


code:
from SocketServer import ThreadingMixIn
from SimpleXMLRPCServer import SimpleXMLRPCServer

class MyXMLRPCServer(ThreadingMixIn, SimpleXMLRPCServer):
    """..."""

rawDescription: Is SimpleXMLRPCServer single threaded?

description: Is SimpleXMLRPCServer single threaded


code:
import re
pattern = re.compile(r"\d*")
string = "hello 123"
pattern.match(string)
pattern.search(string)
pattern = re.compile(r"\d+") # + is one or more, not zero or more
pattern.match(string) # no match at start of string
pattern.search(string)

rawDescription: Python: re module beginner

description: Python: re module beginner


code: cursor.execute("INSERT INTO song (title, artist) VALUES (?, ?)", (tit, art))

rawDescription: SQLite3 python doesn't work?

description: SQLite3 python doesn't work


code: myMethod(myVariable, *myTuple)

rawDescription: How can I explode a tuple so that it can be passed as a parameter list?

description: Explode a tuple so that it can be passed as a parameter list


rawDescription: python regex two words

description: Python regex two words


code: reduce(lambda x, y: x + len(y), s, 0)

rawDescription: Reduce set with lambda

description: Reduce set with lambda


code:
import struct
value = struct.unpack('B', data[0])[0]

rawDescription: Convert Python byte to "unsigned 8 bit integer"


code:
category = Category.objects.get(title=title)
post_list = category.post_set.all()

rawDescription: many to many problem django

description: Many to many problem django


code:
import numpy as nump
from Bio import AlignIO
filename = "opuntia.aln"
format = "clustal"
alignment = AlignIO.read(filename, format)
align_array = numpy.array([list(rec) for rec in alignment], numpy.character)

rawDescription: Numpy and Biopython must be integrated?

description: Numpy and Biopython must be integrated


code: [[tup for tup in sub_list if tup[1] != ""] for sub_list in lst]

rawDescription: Filter tuples inside a list of lists

description: Filter tuples inside a list of lists


code:
amount = int(input("Enter the amount of numbers that you have: "))

numbers = []
for i in range(amount):
    new = input('Enter number {}: '.format(i+1))
    numbers.append(new)

print(numbers)

rawDescription: Python take a variable number of inputs?

description: Python take a variable number of inputs


code:
import re
s = "a.sdf $asdf.asdf.$. . .$..asdf$"
r = re.compile(r'\$([^$]*)\$')
print(r.sub(lambda m: m.group().replace('.',''), s))
# => a.sdf $asdfasdf$. . .$asdf$

rawDescription: Regex to match all occurences of dots within enclosing dollar signs


code:
from webapp2_extras.routes import RedirectRoute

route = RedirectRoute('/feed', handler=feed, strict_slash=True)

rawDescription: How do I make a trailing slash optional with webapp2?

description: Make a trailing slash optional with webapp2


code:
class TutorialIndex(indexes.SearchIndex, indexes.Indexable):
    """
    Index the tutorials
    """
    text = indexes.CharField(document=True, use_template=True)
    tut_id = indexes.IntegerField(model_attr='tut_id')
    cnt_body = indexes.CharField(model_attr='cnt_body')
    mta_title = indexes.CharField()
    mta_views = indexes.CharField()

    def get_model(self):
        """
        Return the current model
        """
        return TutorialContents

    def get_updated_field(self):
        """
        Return the update date tracking field
        """
        return "cnt_date"

    def index_queryset(self, using=None):
        """
        Used when the entire index for model is updated.
        """
        return self.get_model().objects.all()

    def prepare(self, object):
        """
        Prepare the search data
        """
        self.prepared_data = super(TutorialIndex, self).prepare(object)

        # Retrieve the tutorial metas and return the prepared data
        meta = get_tutorial_meta(id=object.tut_id)
        self.prepared_data['mta_title'] = meta.mta_title
        self.prepared_data['mta_views'] = meta.mta_views

        return self.prepared_data

rawDescription: Django Haystack - A SearchIndex Based on Multiple Models


code:
import numpy as np, numpy.random,scipy,scipy.stats,scipy.signal,matplotlib.pyplot as plt
N = 1e5
minx = -10
maxx = 10
bins = 10000
w = 0.1 # kernel sigma

xs1 = np.random.normal(0, 1, size=N)
xs2 = np.random.normal(1.9, 0.01, size=N)
xs = np.r_[xs1, xs2]
hh,loc = scipy.histogram(xs, range=(minx, maxx), bins=bins)
kernel = scipy.stats.norm.pdf((loc[1:]+loc[:-1]) * .5, 0, w)
kde = scipy.signal.fftconvolve(hh, kernel, 'same')
plt.plot((loc[1:] + loc[:-1])*.5, kde)

rawDescription: Density estimate with large array

description: Density estimate with large array


code:
import vte
import os
v = vte.Terminal()
vPid = v.fork_command()
workingDir = os.readlink('/proc/%s/cwd' % vPid)

rawDescription: Get current working directory from Vte (GTK Terminal Widget) in Python


code:
from unittest import mock
with mock.patch.object(Foo, 'foo', new_callable=mock.PropertyMock) as m:
    m.return_value = 'nAME'
    assert Foo.foo == 'nAME'

rawDescription: python stubbing framework for properties

description: Python stubbing framework for properties


code:
for name in self.attributes:
    setattr(self, "_" + name, row[name])

rawDescription: What is the most efficient way to populate class attributes with a row from a database query?


rawDescription: Is there a way to download a file using the Dropbox API without using web server bandwidth?


code:
class DetailViewMixin(object):
    details_model = None
    context_detail_object_name = None

    def get_context_data(self, **kwargs):
        context = super(DetailViewMixin, self).get_context_data(**kwargs)
        context[self.context_detail_object_name] = self.get_detail_object()
        return context

    def get_detail_object(self):
        return self.details_model._default_manager.get(pk=self.kwargs['pk'])

class CommentCreate(DetailViewMixin, CreateView):
    details_model = Post
    context_detail_object_name = 'post'
    model = Comment
    template_name = "blog/test.html"
    fields = ['author', 'email', 'comment']

rawDescription: How to access multiple generic views from one template?

description: Access multiple generic views from one template


code:
if 'POST' not in data.columns:
    data['POST'] = 0

datasum = data.sum()

rawDescription: Sum columns in pandas only if exists else 0