code:
# coding=utf-8

from __future__ import unicode_literals
from mimetools import choose_boundary
from requests.packages.urllib3.filepost import iter_fields, get_content_type
from io import BytesIO
import codecs

writer = codecs.lookup('utf-8')[3]

class MultipartUploadWrapper(object):

    def __init__(self, files):
        """
        Initializer

        :param files:
            A dictionary of files to upload, of the form {'file': ('filename', <file object>)}
        :type network_down_callback:
            Dict
        """
        super(MultipartUploadWrapper, self).__init__()
        self._cursor = 0
        self._body_parts = None
        self.content_type_header = None
        self.content_length_header = None
        self.create_request_parts(files)

    def create_request_parts(self, files):
        request_list = []
        boundary = choose_boundary()
        content_length = 0

        boundary_string = b'--%s\r\n' % (boundary)
        for fieldname, value in iter_fields(files):
            content_length += len(boundary_string)

            if isinstance(value, tuple):
                filename, data = value
                content_disposition_string = (('Content-Disposition: form-data; name="%s"; ''filename="%s"\r\n' % (fieldname, filename))
                                            + ('Content-Type: %s\r\n\r\n' % (get_content_type(filename))))

            else:
                data = value
                content_disposition_string =  (('Content-Disposition: form-data; name="%s"\r\n' % (fieldname))
                                            + 'Content-Type: text/plain\r\n\r\n')
            request_list.append(BytesIO(str(boundary_string + content_disposition_string)))
            content_length += len(content_disposition_string)
            if hasattr(data, 'read'):
                data_stream = data
            else:
                data_stream = BytesIO(str(data))

            data_stream.seek(0,2)
            data_size = data_stream.tell()
            data_stream.seek(0)

            request_list.append(data_stream)
            content_length += data_size

            end_string = b'\r\n'
            request_list.append(BytesIO(end_string))
            content_length += len(end_string)

        request_list.append(BytesIO(b'--%s--\r\n' % (boundary)))
        content_length += len(boundary_string)

        # There's a bug in httplib.py that generates a UnicodeDecodeError on binary uploads if
        # there are *any* unicode strings passed into headers as part of the requests call.
        # For this reason all strings are explicitly converted to non-unicode at this point.
        self.content_type_header = {b'Content-Type': b'multipart/form-data; boundary=%s' % boundary}
        self.content_length_header = {b'Content-Length': str(content_length)}
        self._body_parts = request_list

    def read(self, chunk_size=0):
        remaining_to_read = chunk_size
        output_array = []
        while remaining_to_read > 0: # TODO(afallou) change into a 'while' loop
            body_part = self._body_parts[self._cursor]
            current_piece = body_part.read(remaining_to_read)
            length_read = len(current_piece)
            output_array.append(current_piece)
            if length_read < remaining_to_read:
                # we finished this piece but haven't read enough, moving on to the next one
                remaining_to_read -= length_read
                if self._cursor == len(self._body_parts) - 1:
                    break
                else:
                    self._cursor += 1
            else:
                break
        return b''.join(output_array)

rawDescription: Using Python Requests to 'bridge' a file without loading into memory?


code:
def getTickets():
    A = int(input("Please enter the number of tickets sold in section A: "))
    B = int(input("Please enter the number of tickets sold in section B: "))
    C = int(input("Please enter the number of tickets sold in section C: "))
    return (A, B, C)

def ticketsValid(A, B, C):
    while A > 300 or A < 0:
        print("ERROR: Section A has a limit of 300 seats")
        A = int(input("Please enter the number of tickets sold in section A: "))
    while B > 500 or B < 0:
        print("ERROR: Section B has a limit of 500 seats")
        B = int(input("Please enter the number of tickets sold in section B: "))
    while C > 200 or C < 0:
        print("ERROR: Section C has a limit of 200 seats")
        C = int(input("Please enter the number of tickets sold in section C: "))
    return (A, B, C)

def calcIncome(A, B, C):
    incomeGenerated = A * secA + B * secB + C * secC
    print("The income generated is $%d" % (incomeGenerated))

def main():
    A, B, C = getTickets()
    A, B, C = ticketsValid(A, B, C)
    calcIncome(A, B, C)

rawDescription: Python 3.x - How to get my program to not calculate a section when it is invalidated?


code:
#! /usr/bin/python3.2

#here you should actually use the csv module for parsing your data
#make sure that there are actually tabs between the columns
a = '''Row Box Description
17\t3\tC. trach clone
14\t6\tOMP A E Coli
1\t6\tR 19 15
2\t5\t11 Black Ring
1\t1\tL. Pneumo'''
data = [x.split('\t') for x in a.split('\n')[1:]]

data = sorted(data, key = lambda x: (int(x[0]), int(x[1])))
print('\n'.join('\t'.join(row) for row in data))

rawDescription: Vertically Sorting in Python

description: Vertically Sorting in Python


rawDescription: Set the colour of text in a QPushButton in PyQt4 using Python


code:
import subprocess
import sys
import time

while True:
    time.sleep(2 - time.time() % 2) # lock with the timer, to avoid drift
    output = subprocess.check_output(["/opt/vc/bin/vcgencmd", "measure_temp"])
    t = output.rpartition('=')[2] # extract the part after the last '='
    sys.stderr.write("\r%6s" % t.strip())

rawDescription: Simple updating string on single line / dynamic


code:
def mostWantedLetter(text):
    # count how many times each letter occurs
    mwl = {}
    for ch in text.lower():
        if ch.isalpha():
            mwl[ch] = mwl.get(ch, 0) + 1

    # ordered descending by count (highest first) then ascending by letter
    least = min(mwl.items(), key=lambda x:(-x[1], x[0]))

    # return the letter from the least item
    return least[0]

rawDescription: How do I return the earliest letter in the alphabet from a choice of letters?

description: Return the earliest letter in the alphabet from a choice of letters


code:
sort_ids = np.argsort(data,axis=2)

s1 = data.shape
s2 = data2.shape
d1 = data[np.arange(s1[0])[:,None,None,None],np.arange(s1[1])[None,:,None,None],sort_ids,np.arange(s1[3])[None,None,None,:]]
d2 = data2[np.arange(s2[0])[:,None,None,None],np.arange(s2[1])[None,:,None,None],sort_ids,np.arange(s2[3])[None,None,None,:]]

rawDescription: Numpy - Sorting two ndarrays by single axis of first array


code:
a = np.arange(1, 17).reshape(4,4)
a

rawDescription: How do I create a custom 4x4 array using NumPy?

description: Create a custom 4x4 array using NumPy


code:
import matplotlib.pyplot as plt
x = [1,2,3,4]
y = [1,4,9,16]

plt.ion()
h = plt.plot(x,y)
plt.show()
var = raw_input("type enter to change")
#update data some where here?
h[0].set_data(y,x)
plt.show()
var = raw_input("type enter to end")

rawDescription: Update image in PyPlot

description: Update image in PyPlot


code:
businesses = Business.objects.extra(
  select={
    "lat": "SELECT latitude FROM property_table WHERE  business_table.address = property_table.address",
    "lon": "SELECT longitude FROM property_table WHERE business_table.address = property_table.address"
  }
)

rawDescription: Django ORM join without explicit Foriegn Key


code:
import Image, cv
pi = Image.open('building.jpg')       # PIL image
cv_im = cv.CreateImageHeader(pi.size, cv.IPL_DEPTH_8U, 3)
cv.SetData(cv_im, pi.tostring())

rawDescription: Python PIL Image.tostring('raw') and IplImage->imageData of OpenCV


code:
html = """\
<html>
  Message
  Hi {0:}, (Need to be updated from Array[1])
     starting on {1:} (Should ready from date = time.strftime("%m-%d-%y"))

  {2:} (Should be replaced with Array[2]) is the 3LS lead for this week.\n

  Let me know if you have any questions,

""".format(Array[1], time.strftime("%m-%d-%y"), Array[2])

rawDescription: substitute values in email via python

description: Substitute values in email via python


code:
response = requests.get(infoFromJson['Poster'])
# Create a string buffer then set it raw data in redis.
output = StringIO(response.content)
r.setex(key, (60*60*5), output.getvalue())
output.close()

rawDescription: How to retrieve an image from redis in python flask

description: Retrieve an image from redis in python flask


code:
class BaseTask:
    def __init__(self, settings):
        self.settings = settings[self.__class__]

class SomeTask(BaseTask):
    pass

class SomeOtherTask(BaseTask):
    pass

rawDescription: Access child class instance in parent

description: Access child class instance in parent


code:
from itertools import permutations

def is_solution(seq):
    return all(int(seq[:i]) % i == 0 for i in range(2, 9))

for p in permutations('123456789'):
    seq = ''.join(p)
    if is_solution(seq):
        print(seq)

rawDescription: Help me finish this Python 3.x self-challenge


code:
x = arange(20.)
y_old = x**2
y_new = 1.3*y_old

markerline, stemlines, baseline = stem(x,y_old)
markerline.set_ydata(y_new)
for line, y in zip(stemlines, y_new):
    line.set_ydata([0, y])

rawDescription: Can't use set_ydata for a "stem"-plot in matlibplot


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

x = np.linspace(0,1,11)
y = np.linspace(0,1,11)

p1, = plt.plot(x, y, c='r')
plt.fill_between(x, y-0.2, y+0.2, color='r', alpha=0.5)
p2 = mpatches.Patch(color='r', alpha=0.5, linewidth=0)

plt.legend(((p1,p2),), ('Entry',))

rawDescription: Combine two Pyplot patches for legend

description: Combine two Pyplot patches for legend


code:
def BuySword(event):
    if 'sword' in StoreItems:
        x,y,_,_ = canvas.bbox("sword")
        relative_position = (x+420,y)
        sword = canvas.create_text(relative_position, text="test", fill="White", font=('Anarchistic',40),
                                   anchor=N+W) #the anchor is needed to line up with the north west corner of the original text

rawDescription: How do I match text location to randomly placed text on my Canvas?

description: Match text location to randomly placed text on my Canvas


rawDescription: Why is BeautifulSoup not finding a specific table class?


code:
import operator, collections
number = operator.itemgetter('number')
item_one = operator.itemgetter(1)
def f(foo):
    return number(item_one(foo))
d = {'PROJ-UX-HLR-0005': {'category': 'UX',
                          'file': 'rm/app/parse/example_reqs.txt',
                          'level': 'HLR',
                          'number': '0005',
                          'prefix': 'PROJ',
                          'repo': 'repo',
                          'text': 'This SHALL be the 5th requirement.'},
     'PROJ-UX-HLR-0003': {'category': 'UX',
                          'file': 'rm/app/parse/example_reqs.txt',
                          'level': 'HLR',
                          'number': '0003',
                          'prefix': 'PROJ',
                          'repo': 'repo',
                          'text': 'This SHALL be the 3rd requirement.'},
     'PROJ-UX-HLR-0004': {'category': 'UX',
                          'file': 'rm/app/parse/example_reqs.txt',
                          'level': 'HLR',
                          'number': '0004',
                          'prefix': 'PROJ',
                          'repo': 'repo',
                          'text': 'This SHALL be the 4th requirement.'}
     }
ds = sorted(d.items(), key = f)
od = collections.OrderedDict(ds)

rawDescription: Printing a dictionary after using sorted(dict.values(), ...)


code: IS_DEV_APPSERVER = 'development' in os.environ.get('SERVER_SOFTWARE', '').lower()

rawDescription: Python App Engine debug/dev mode

description: Python App Engine debug/dev mode


code:
from fnmatch import fnmatch, filter
from os.path import isdir, join
from shutil import copytree

def include_patterns(*patterns):
    """Factory function that can be used with copytree() ignore parameter.

    Arguments define a sequence of glob-style patterns
    that are used to specify what files to NOT ignore.
    Creates and returns a function that determines this for each directory
    in the file hierarchy rooted at the source directory when used with
    shutil.copytree().
    """
    def _ignore_patterns(path, names):
        keep = set(name for pattern in patterns
                            for name in filter(names, pattern))
        ignore = set(name for name in names
                        if name not in keep and not isdir(join(path, name)))
        return ignore
    return _ignore_patterns

# sample usage

copytree(src_directory, dst_directory,
         ignore=include_patterns('*.sldasm', '*.sldprt'))

rawDescription: Copying specific files to a new folder, while maintaining the original subdirectory tree


code:
d = {'department': ['DepartmentName'],
     'memberOf': ['CN=example,OU=of,DC=domain,DC=com',
                  'CN=example,OU=of,DC=domain,DC=com']}
dept = d['department']  # access by key
mem = d['memberOf']
print("dept = {}\nmem = {}".format(dept, mem))

rawDescription: Pulling elements from dict embedded in a list in Python 3


rawDescription: Passing escape characters to grep -e command via Python subprocess.Popen()


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

x=[1,2,10,100,1000]
y=[5,10,6,7,9]

N = len(x)
x2 = np.arange(N)

plt.plot(x2, y)

plt.xticks(x2, x)

plt.show()

rawDescription: matplotlib.pyplot plot x-axis ticks in equal range

description: Matplotlib.pyplot plot x-axis ticks in equal range


code:
try:
    from tkinter import * #v3
except ImportError:
    from Tkinter import * #v2

rawDescription: How to install Tkinter to Aptana Studio 35-32 (Non-Eclipse)

description: Install Tkinter to Aptana Studio 35-32 (Non-Eclipse)


code:
def fileSelected(self, filename):
    print(filename)

def showDialog(self):
    filedialog = QtGui.QFileDialog()
    filedialog.fileSelected.connect(self.fileSelected)
    filedialog.setFixedSize(320,240)
    filedialog.show()

rawDescription: How to adjust the QFileDialog's size in pyQt?

description: Adjust the QFileDialog's size in pyQt


code:
class CategoryLocationsView(DetailView):
    model = Category
    context_object_name = 'category'

    def get_context_data(self, **kwargs):
        context = super(CategoryLocationsView, self).get_context_data(**kwargs)
        context['location_list'] = self.get_object().location_set.all()
        return context

rawDescription: Django Generic Views: How to assign a new property?


rawDescription: Size of widget in Gtk.Grid

description: Size of widget in Gtk.Grid


code:
request.path # the url (excluding domain)
request.method # eg GET or POST
request.cookies
request.user # A django.contrib.auth.models.User object representing the currently logged-in user
request.META # A standard Python dictionary containing all available HTTP headers

rawDescription: What is the HttpRequest metadata that's passed to a django view function


code:
from heapq import nsmallest
s = [1,2,3,4,5,6,7]
nsmallest(3, s, key=lambda x: abs(x-6.5))

rawDescription: Finding k closest numbers to a given number


code:
class Derived(Base):
    def __init__(self):
        super(Derived, self).__init__()

rawDescription: Passing a derived class to a function taking a base class in SWIG Python


code:
limit = input('Maximum number to factorise: ')
for i in range(1,int(limit)):
    line = '{:2}:'.format(i)
    for j in range (1,11):
        if i % j == 0:
            line += "{:4}".format('0')
        else:
            line += "{:4}".format('-')
    print(line)

rawDescription: Looped nesting -- Factorising

description: Looped nesting -- Factorising


rawDescription: Python Regex instantly replace groups

description: Python Regex instantly replace groups


code:
from ply.lex import TOKEN
data = data.split() #make data a list of keywords

@TOKEN('|'.join(data))
def t_KEYWORD(t):
    return t

rawDescription: RegEx with variable data in it - ply.lex


code:
datadict = {}
for item in datalist.split(','):
    key, value = item.split(':', 1)
    datadict[key.strip()] = value.strip()

rawDescription: How to convert string to dict

description: Convert string to dict


code:
def last_inner_append(x, y):
    try:
        if isinstance(x[-1], list):
            last_inner_append(x[-1], y)
            return x
    except IndexError:
        pass
    x.append(y)
    return x

rawDescription: Python: add a value to the end of the inner-most right nested list


code:
inp = open("filelocation").readlines()
with open("filelocation", "w") as out:
    for line in inp:
        t = line[12:14]
        p = int(t)
        if p>12:
            line = '{}{:02}{}'.format(line[:12], p-12, line[14:])
        out.write(line)

rawDescription: python: checking then updating the value in a text file

description: Python: checking then updating the value in a text file


code:
def build_schema(self):
    base_schema = super(SomeModelResource, self).build_schema()
    for f in self._meta.object_class._meta.fields:
        if f.name in base_schema['fields'] and f.choices:
            base_schema['fields'][f.name].update({
                'choices': f.choices,
            })
    return base_schema

rawDescription: In django-tastypie, can choices be displayed in schema?


rawDescription: Turning nested curly braces into a dict python


code:
import csv
from bs4 import BeautifulSoup
import requests

html = requests.get("http://www.gbgb.org.uk/resultsMeeting.aspx?id=135754").text
soup = BeautifulSoup(html,'lxml')

rows = []
for header in soup.find_all("div", class_="resultsBlockHeader"):
    track = header.find("div",    class_="track").get_text(strip=True).encode('ascii', 'ignore').strip("|")
    date = header.find("div",   class_="date").get_text(strip=True).encode('ascii', 'ignore').strip("|")
    datetime = header.find("div", class_="datetime").get_text(strip=True).encode('ascii', 'ignore').strip("|")
    grade = header.find("div", class_="grade").get_text(strip=True).encode('ascii', 'ignore').strip("|")
    distance = header.find("div", class_="distance").get_text(strip=True).encode('ascii', 'ignore').strip("|")
    prizes = header.find("div", class_="prizes").get_text(strip=True).encode('ascii', 'ignore').strip("|")

    results = header.find_next_sibling("div",  class_="resultsBlock").find_all("ul", class_="line1")
    details = []
    for result in results:
        fin = result.find("li", class_="fin").get_text(strip=True)
        greyhound = result.find("li", class_="greyhound").get_text(strip=True)
        trap = result.find("li", class_="trap").get_text(strip=True)
        sp = result.find("li", class_="sp").get_text(strip=True)
        timeSec = result.find("li", class_="timeSec").get_text(strip=True)
        timeDistance = result.find("li", class_="timeDistance").get_text(strip=True)
        details.append({"greyhound": greyhound, "sp": sp, "fin": fin, "timeSec": timeSec, "timeDistance": timeDistance, "trap": trap, })

    results = header.find_next_sibling("div",  class_="resultsBlock").find_all("ul", class_="line2")
    for index, result in enumerate(results):
        trainer = result.find("li",  class_="trainer").get_text(strip=True)
        details[index]["trainer"] = trainer

    for detail in details:
        detail.update({"track": track, "date": date, "datetime": datetime, "grade": grade, "prizes": prizes})
        rows.append(detail)

with open("greyfile.csv", "w") as f:
    writer = csv.DictWriter(f,      ["track","date","trap","fin","greyhound","datetime","sp","grade","distance","prizes","timeSec","timeDistance","trainer"])

    for row in rows:
      writer.writerow(row)

rawDescription: rows append not working with loops

description: Rows append not working with loops


code:
from collections import Counter
mylist = [20, 30, 25, 20, 30]
max(k for k,v in Counter(mylist).items() if v>1)

rawDescription: get max duplicate item in list

description: Get max duplicate item in list


code:
def numberOfNeighbors(rows, columns, row, column):
    topBottom = row in (0, rows-1)
    leftRight = column in (0, columns-1)
    if topBottom and leftRight:
       return 3
    if topBottom or leftRight:
       return 5
    return 8

rawDescription: Best way to compute amount of neighbours in matrix?

description: Compute amount of neighbours in matrix


code: someString = '{0:<16}{1}'.format(someList[someIndex], someList[someOtherIndex])

rawDescription: Python str.format() method not working as expected


code:
def start_game(self, obj):
    num = 0
    self.remove_widget(self.start)
    self.add_widget(self.count)
    def count_it(num):
        if num == 4:
            return
        num += 1
        self.count.text = str(num)
        Clock.schedule_once(lambda dt: count_it(num), 1)

    Clock.schedule_once(lambda dt: count_it(0), 0)

rawDescription: Kivy countdown Label

description: Kivy countdown Label


rawDescription: Mapping a list of tuples using a dictionary


code:
p = Popen(['/vol/thchem/x86_64-linux/bin/molpro'], shell = False, stdout = None, stderr = STDOUT, stdin = PIPE)
p.communicate(input = StdinCommand)

rawDescription: Python string as file argument to subprocess


rawDescription: Pad python floats

description: Pad python floats


code:
class CreateArticle(CreateView):
    model = Article

    def form_valid(self, form):
        article = form.save(commit=False)
        article.author = self.request.user
        #article.save()  # This is redundant, see comments.
        return super(CreateArticle, self).form_valid(form)

rawDescription: How to set ForeignKey in CreateView?

description: Set ForeignKey in CreateView


code:
string_list = []
for col, series in df.items(): # iterating over all columns - perhaps only select `object` types
    string_list += [s for s in series.unique() if isinstance(s, str)]

rawDescription: Return unknown string in dataframe (extract unkown string from


code:
for contact_edge in body.contacts:
    if contact_edge.contact.touching:
        print('ONE collision!')

rawDescription: pyBox2D contact edge too many contacts?

description: PyBox2D contact edge too many contacts


code:
#no of tweets you want to request
max_tweets = 500
#make initial request for most recent tweets (200 is the maximum allowed count)
new_tweets = api.GetUserTimeline(screen_name = screen_name,count=max_tweets)

#save most recent tweets
alltweets.extend(new_tweets)

#save the id of the oldest tweet less one
oldest = alltweets[-1].id - 1
#loop for remaining tweets
while(len(alltweets)<max_tweets):
    alltweets.extend(api.GetUserTimeline(screen_name = screen_name,count=(max_tweets-len(alltweets)),max_id=oldest))
    oldest = alltweets[-1].id - 1

rawDescription: How to install twitter4j package(java) alternative in python?

description: Install twitter4j package(java) alternative in python


code:
from tkinter import *
from math import *

finestra=Tk()
finestra.geometry('800x800+300+300')
finestra.title('Dimensionamento Trasformatore')

def calcola(Vn,Vn2,Sn,Vcc,V_spira,f,Bmax,mu,J,w,Snf,N1,N2,If1,If2,kv,ki,fi,fi_c,S_colonna,S_conduttore1,S_conduttore2,Sezione_netta_cu1,Sezione_netta_cu2,Vf1,Vf2):

    try:

       #lettura caselle di testo/ read entry
                Vn=float(Vn_s.get())
                Vn2=float(Vn2_s.get())
                Vcc=float(Vcc_s.get())
                V_spira=float(Vspira_s.get())
                Sn=float(Sn_s.get())
                J=float(J_s.get())
                mu=float(mu_s.get())
                Bmax=float(Bmax_s.get())
                f=float(f_s.get())

    except ValueError:
                print('inserito valore sbagliato')
    else:

        #calcoli / calculate
                if (var_1.get()==1):
                      collegamento1='triangolo'
                else:
                      collegamento1='stella'
                if (var_2.get()==1):
                      collegamento2='triangolo'
                else:
                      collegamento2='stella'

                Snf=(Sn/3.0)
                w=(2*pi*f)
                if (collegamento1=='triangolo'):
                            Vf1=Vn
                else:
                            Vf1=(Vn/sqrt(3))
                if (collegamento2=='triangolo'):
                            Vf2=(Vn2)
                else:
                            Vf2=(Vn2/sqrt(3))
                N1=Vf1/V_spira
                N2=Vf2/V_spira
                If1=Snf/Vf1
                If2=(Snf/Vf2)
                kv=Vf1/Vf2
                ki=If2/If1
                fi=Vf1/(w*N1)
                fi_c=(N1*fi)
                S_colonna=(fi_c/(Bmax*sqrt(2)))
                S_conduttore1=(If1/J)
                S_conduttore2=(If2/J)
        #        Sezione_netta_cu1.set(S_conduttore1*N1/k_stip_cu)
        #        Sezione_netta_cu2.set(S_conduttore2*N2/k_stip_cu)

                testo_23=Label(finestra,text=str(N1)).grid(sticky=W,row=4,column=5)
                testo_24=Label(finestra,text=str(N2)).grid(sticky=W,row=6,column=5)
                testo_25=Label(finestra,text=str(kv)).grid(sticky=W,row=11,column=5)
                testo_26=Label(finestra,text=str(ki)).grid(sticky=W,row=13,column=5)
                testo_27=Label(finestra,text=str(fi_c)).grid(sticky=W,row=21,column=5)
                testo_28=Label(finestra,text=str(S_colonna)).grid(sticky=W,row=25,column=5)
                testo_29=Label(finestra,text=str(S_conduttore1)).grid(sticky=W,row=19,column=5)
                testo_30=Label(finestra,text=str(S_conduttore2)).grid(sticky=W,row=17,column=5)
##                testo_31=Label(finestra,text=str(Sezione_netta_cu1)).grid(sticky=W,row=16,column=5)
##                testo_32=Label(finestra,text=str(Sezione_netta_cu2)).grid(sticky=W,row=8,column=5)
##                testo_33=Label(finestra,text=str(N1)).grid(sticky=W,row=14,column=5)
##                testo_34=Label(finestra,text=str(N1)).grid(sticky=W,row=22,column=5)

                return;

#Testi / label
testo_0=Label(finestra,text="Parametri di ingresso:").grid(sticky=W,row=0,column=0)
testo_1=Label(finestra,text="Collegamento primario:").grid(sticky=W,row=3,column=0)
testo_2=Label(finestra,text="Collegamento secondario:").grid(sticky=W,row=5,column=0)
testo_3=Label(finestra,text="Tensione nominale concatenata primaria:").grid(sticky=W,row=10,column=0)
testo_4=Label(finestra,text="Tensione nominale concatenata secondaria:").grid(sticky=W,row=12,column=0)
testo_5=Label(finestra,text="Induzione massima:").grid(sticky=W,row=20,column=0)
testo_6=Label(finestra,text="Densita di corrente:").grid(sticky=W,row=24,column=0)
testo_7=Label(finestra,text="Frequenza:").grid(sticky=W,row=18,column=0)
testo_8=Label(finestra,text="Tensione di corto circuito:").grid(sticky=W,row=16,column=0)
testo_9=Label(finestra,text="Potenza apparente nominale:").grid(sticky=W,row=8,column=0)
testo_10=Label(finestra,text="Volt-spira:").grid(sticky=W,row=14,column=0)
testo_11=Label(finestra,text="Permeabilita del ferro:").grid(sticky=W,row=22,column=0)
testo_12=Label(finestra,text="Valori calcolati:").grid(sticky=W,row=0,column=5)
testo_13=Label(finestra,text="Numero spire primario:").grid(sticky=W,row=3,column=5)
testo_14=Label(finestra,text="Numero spire secondario:").grid(sticky=W,row=5,column=5)
testo_15=Label(finestra,text="Rapporto trasformazione tensione:").grid(sticky=W,row=10,column=5)
testo_16=Label(finestra,text="Rapporto trasformazione corrente:").grid(sticky=W,row=12,column=5)
testo_17=Label(finestra,text="Flusso concatenato efficace:").grid(sticky=W,row=20,column=5)
testo_18=Label(finestra,text="Sezione colonna:").grid(sticky=W,row=24,column=5)
testo_19=Label(finestra,text="Sezione conduttore primario:").grid(sticky=W,row=18,column=5)
testo_20=Label(finestra,text="Sezione conduttore secondario:").grid(sticky=W,row=16,column=5)
testo_21=Label(finestra,text="Sezione avvolgimento primario netta:").grid(sticky=W,row=8,column=5)
testo_22=Label(finestra,text="Sezione avvolgimento secondario netta:").grid(sticky=W,row=14,column=5)

#variabili
If1=DoubleVar()
If2=DoubleVar()
N1=DoubleVar()
N2=DoubleVar()
var_1=IntVar()
var_2=IntVar()
Vn=DoubleVar()
Vf1=DoubleVar()
Vf2=DoubleVar()
Vn2=DoubleVar()
Vcc=DoubleVar()
V_spira=DoubleVar()
Sn=DoubleVar()
Snf=DoubleVar()
J=DoubleVar()
mu=DoubleVar()
Bmax=DoubleVar()
f=DoubleVar()
Vn_s=StringVar()
Vn2_s=StringVar()
Vcc_s=StringVar()
Vspira_s=StringVar()
Sn_s=StringVar()
J_s=StringVar()
mu_s=StringVar()
Bmax_s=StringVar()
f_s=StringVar()
collegamento1=StringVar()
collegamento2=StringVar()
w=DoubleVar()
kv=DoubleVar()
ki=DoubleVar()
fi=DoubleVar()
fi_c=DoubleVar()
S_colonna=DoubleVar()
S_conduttore1=DoubleVar()
S_conduttore2=DoubleVar()
Sezione_netta_cu1=DoubleVar()
Sezione_netta_cu2=DoubleVar()

#Radiobutton
#collegamento primario/ first winding
collegamentoI_1=Radiobutton(finestra,text='triangolo',value=1,variable=var_1)
collegamentoI_1.grid(row=4,column=0)
collegamentoI_2=Radiobutton(finestra,text='stella',value=2,variable=var_1)
collegamentoI_2.grid(row=4,column=1)
#collegamento secondario/ second winding
collegamentoII_1=Radiobutton(finestra,text='triangolo',value=1,variable=var_2)
collegamentoII_1.grid(row=6,column=0)
collegamentoII_2=Radiobutton(finestra,text='stella',value=2,variable=var_2)
collegamentoII_2.grid(row=6,column=1)

#caselle di testo / entry
Vn_=Entry(finestra,textvariable=Vn_s)
Vn_.grid(row=11,column=0)
Vspira_=Entry(finestra,textvariable=Vspira_s)
Vspira_.grid(row=15,column=0)
Vn2_=Entry(finestra,textvariable=Vn2_s)
Vn2_.grid(row=13,column=0)
Sn_=Entry(finestra,textvariable=Sn_s)
Sn_.grid(row=9,column=0)
Bmax_=Entry(finestra,textvariable=Bmax_s)
Bmax_.grid(row=21,column=0)
mu_=Entry(finestra,textvariable=mu_s)
mu_.grid(row=23,column=0)
Vcc_=Entry(finestra,textvariable=Vcc_s)
Vcc_.grid(row=17,column=0)
f_=Entry(finestra,textvariable=f_s)
f_.grid(row=19,column=0)
J_=Entry(finestra,textvariable=J_s)
J_.grid(row=25,column=0)

#Calculatebutton
gobutton=Button(finestra,text='Calcola',command=lambda: calcola(Vn,Vn2,Sn,Vcc,V_spira,f,Bmax,mu,J,w,Snf,N1,N2,If1,If2,kv,ki,fi,fi_c,S_colonna,S_conduttore1,S_conduttore2,Sezione_netta_cu1,Sezione_netta_cu2,Vf1,Vf2))
gobutton.grid(row=28, column=3)

finestra.mainloop()

rawDescription: Tkinter error type variable

description: Tkinter error type variable


code: vars['list%s' % toreplacetype][5] = ...

rawDescription: Python, string (consisting of variable and strings, concatenated) used as new variable name?


code:
def __setitem__(self, key, value):
    if isinstance(key, tuple):
        node = self
        for i in key[:-1]:
            try:
                node = dict.__getitem__(node, i)
            except KeyError:
                node = node[i] = type(self)()
        return dict.__setitem__(node, i, value)
    return dict.__setitem__(self, key, value)

rawDescription: How can I access a deeply nested dictionary using tuples?

description: Access a deeply nested dictionary using tuples


code:
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.font_manager as fm
from datetime import datetime
import matplotlib.dates as mdates

fig,ax = plt.subplots(1, 1) #width height inches
data=np.genfromtxt('data',
     dtype='M8[us],S5,float,float,float',delimiter=',',usecols= [0,1,11,12,13])

my_dates =  np.array([d[0] for d in data]).astype('datetime64[D]')
dates = np.unique(my_dates)
print(dates)
x_list = []
x_list[:] = dates.astype(datetime)
y_list  = [10,11,12,13]
plt.plot(x_list,y_list)
plt.title('hv 20 to 10 ranks',fontsize=20)
plt.xlabel('dates',fontsize=16)
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
plt.ylabel('symbol ranks',fontsize=30)
plt.show()

rawDescription: python 3.5 matplotlib reading date from csv but can't represent as date on X axis

description: Python 3.5 matplotlib reading date from csv but can't represent as date on X axis


code:
for i,j in zip(numbers[:-1],numbers[1:]):
    compare(i,j)

rawDescription: Compare 2 elements in single list

description: Compare 2 elements in single list


code:
import pickle
import os

high_scores_filename = 'high_scores.dat'

scores = []

# first time you run this, "high_scores.dat" won't exist
#   so we need to check for its existence before we load
#   our "database"
if os.path.exists(high_scores_filename):
    # "with" statements are very handy for opening files.
    with open(high_scores_filename,'rb') as rfp:
        scores = pickle.load(rfp)
    # Notice that there's no "rfp.close()"
    #   ... the "with" clause calls close() automatically!

first_name = input("Please enter your name:")
score = input("Please enter your score:")

high_scores = first_name, score
scores.append(high_scores)

# Now we "sync" our database
with open(high_scores_filename,'wb') as wfp:
    pickle.dump(scores, wfp)

# Re-load our database
with open(high_scores_filename,'rb') as rfp:
    scores = pickle.load(rfp)

print(scores)

rawDescription: Python - appending to a pickled list

description: Python - appending to a pickled list


code:
def is_mail_start(line):
    return line.startswith("From ")

def build_index(fname):
    with open(fname, "rb") as f:
        i = 0
        b = 0
        # find start of first message
        for line in f:
            b += len(line)
            if is_mail_start(line):
                break
        # find start of each message, and yield up (index, length) of previous message
        for line in f:
            if is_mail_start(line):
                yield (i, b)
                i += b
                b = 0
            b += len(line)
        yield (i, b) # yield up (index, length) of last message

# get index as a list
mbox_index = list(build_index(fname))

rawDescription: Parsing mbox files in Python

description: Parsing mbox files in Python


rawDescription: collapsing several rows in a pandas dataframe into one array

description: Collapsing several rows in a pandas dataframe into one array


code:
import vispy.plot as vp
import vispy.io as io

# Create a canvas showing plot data
canvas = vp.plot([1, 6, 2, 4, 3, 8, 5, 7, 6, 3])

# Use render to generate an image object
img=canvas.render()

# Use write_png to export your wonderful plot as png !
io.write_png("wonderful.png",img)

rawDescription: How to export VisPy result as png image

description: Export VisPy result as png image


code:
from __future__ import division
from future.modified_builtins import round

rawDescription: Implement Python 3's round function in Python 2.7


code:
import os
path="C:/Users/UserName/Desktop/New_folder/export/"
w = os.listdir(path)
#since there is only one file in directory it will be first in list
#split the filename to separate the ext from the rest of the filename
splitfilename=w[0].split('.')
s = '[Movie1]' + '.'.join(splitfilename[:-1]) + '[720p].'+splitfilename[-1]
os.rename(path+w[0],path+s)

rawDescription: how to rename file in a directory using python

description: Rename file in a directory using python


code:
import gtk
import dbus
import dbus.service
from dbus.mainloop.glib import DBusGMainLoop

class MyDBUSObject(dbus.service.Object):
    def __init__(self, path):
        bus_name = dbus.service.BusName('org.fusegui', bus=dbus.SessionBus())
        dbus.service.Object.__init__(self, bus_name, path)

    @dbus.service.method('org.fusegui.site')
    def hello(self):
        return "Hello,World!"

DBusGMainLoop(set_as_default=True)
for i in range(0, 50):
    MyDBUSObject('/org/fusegui/sites/%i' % i)
gtk.main()

rawDescription: how to expose list of objects with dbus

description: Expose list of objects with dbus


code:
ax.spines['left'].set_bounds(20, 80)
ax.spines['bottom'].set_bounds(20, 80)

for i in [0, -1]:
    ax.get_yticklabels()[i].set_visible(False)
    ax.get_xticklabels()[i].set_visible(False)

for i in [0, -2]:
    ax.get_yticklines()[i].set_visible(False)
    ax.get_xticklines()[i].set_visible(False)

rawDescription: Changing the length of axis lines in matplotlib


code:
if num < 0:
    lst = list(chained)
    lst.reverse()
    return lst
else:
    return chained

rawDescription: How do I reverse an itertools.chain object?

description: Reverse an itertools.chain object


code:
class Ban(models.Model):
    # id is not redundant, django would define it for you
    # id = models.IntegerField(null=False, primary_key=True)
    user = models.ForeignKey(User)

rawDescription: Issues with figuring out Django ORM, what would be the correct way to query an inner join?


code:
from PyQt4.QtGui import QWidget, QApplication, QTreeView, QListView, QTextEdit, \
                        QSplitter, QHBoxLayout

import sys

class MainWindow(QWidget):
    def __init__(self):
        QWidget.__init__(self)

        treeView = QTreeView()
        listView = QListView()
        textEdit = QTextEdit()
        splitter = QSplitter(self)

        splitter.addWidget(treeView)
        splitter.addWidget(listView)
        splitter.addWidget(textEdit)

        layout = QHBoxLayout()
        layout.addWidget(splitter)
        self.setLayout(layout)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    mainWindow = MainWindow()
    mainWindow.show()
    sys.exit(app.exec_())

rawDescription: User resizing PyQt widgets

description: User resizing PyQt widgets


code:
import numpy as np
import numpy.linalg as LA
A = np.array([[1, 0, 0], [0, 1, 0], [1, 1, 0]])
e_vals, e_vecs = LA.eig(A)

print(e_vals)
# [ 0.  1.  1.]
print(e_vecs)
# [[ 0.          0.          1.        ]
#  [ 0.70710678  0.          0.70710678]
#  [ 0.          0.70710678  0.70710678]]

for val, vec in zip(e_vals, e_vecs.T):
    assert np.allclose(np.dot(A, vec), val * vec)

rawDescription: Incorrect EigenValues/Vectors with Numpy


code:
# faster lookup on users
cur.execute ("select ref from users")
users = set(row[0] for row in cur.fetchall())

with open("your/file.CSV") as f:
    r = reader(f)
    for row in r:
        if row[0] in users:
            do_something_with(row)

rawDescription: parsing huge csv file into mysql [python]

description: Parsing huge csv file into mysql [python]


code:
from mpl_toolkits.mplot3d import axes3d
from mpl_toolkits.mplot3d import art3d
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)
wire = ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10)

# Retrive data from internal storage of plot_wireframe, then delete it
nx, ny, _  = np.shape(wire._segments3d)
wire_x = np.array(wire._segments3d)[:, :, 0].ravel()
wire_y = np.array(wire._segments3d)[:, :, 1].ravel()
wire_z = np.array(wire._segments3d)[:, :, 2].ravel()
wire.remove()

# create data for a LineCollection
wire_x1 = np.vstack([wire_x, np.roll(wire_x, 1)])
wire_y1 = np.vstack([wire_y, np.roll(wire_y, 1)])
wire_z1 = np.vstack([wire_z, np.roll(wire_z, 1)])
to_delete = np.arange(0, nx*ny, ny)
wire_x1 = np.delete(wire_x1, to_delete, axis=1)
wire_y1 = np.delete(wire_y1, to_delete, axis=1)
wire_z1 = np.delete(wire_z1, to_delete, axis=1)
scalars = np.delete(wire_z, to_delete)

segs = [list(zip(xl, yl, zl)) for xl, yl, zl in \
                 zip(wire_x1.T, wire_y1.T, wire_z1.T)]

# Plots the wireframe by a  a line3DCollection
my_wire = art3d.Line3DCollection(segs, cmap="hsv")
my_wire.set_array(scalars)
ax.add_collection(my_wire)

plt.colorbar(my_wire)
plt.show()

rawDescription: How to obtain 3D colored surface via Python?

description: Obtain 3D colored surface via Python


code:
import collections
a = {"A": 1, "B": 1, "C": 2}
collections.Counter(a.values())

rawDescription: Python dictionary counting

description: Python dictionary counting


code:
def __init__(self, *args, **kwargs):
    super(SecondForm, self).__init__(*args, **kwargs)
    self.fields['first'].query = db.Query(First).fetch(10)

rawDescription: Filtering the drop down list of ReferenceModels created by appengine using django


code:
import xmpp

ipaddress='<server-ip>'
user='<new-user>' #without @<server-ip>
passwd='<password>'

c = xmpp.Client(ipaddress)
c.connect((ipaddress,5222), secure=0)
c.auth(user,passwd,sasl=1)
c.sendInitPresence()
c.isConnected()
c.send(xmpp.protocol.Message('<jid of receiver user with @<domain> >',"hello world"))

rawDescription: XMPPPY unable to connect to the server

description: XMPPPY unable to connect to the server


code:
def __init__(self, stats):
    self.stats = stats

@classmethod
def from_crawler(cls, crawler):
    return cls(crawler.stats)

rawDescription: How to access scrapy stats from a pipeline

description: Access scrapy stats from a pipeline


code:
my_session = boto3.session.Session()
my_region = my_session.region_name

rawDescription: How to get the region of the current user from boto?

description: Get the region of the current user from boto


code:
import re
original_string = "text text words Hi there, I need help using regular expressions ,Best Chris more words Hi This is not what I want ,Best"
desired_string = re.search("(?s)(?<=Hi).+?(?=Best)", original_string).group()
desired_string

rawDescription: How to use regular expressions in python to capture the characters between two words?

description: Use regular expressions in python to capture the characters between two words


rawDescription: Create a select list in half-hour increments in python


code:
from functools import partial

fromdate = fields.DateField('From Date', default=partial(myfunc, offset=-10), validators=[validators.required()])

rawDescription: Python - Pass named arguments to function object


code:
def label_not_nan(arr, label):
    if np.isnan(arr).any():
        return None
    return label

plt.plot(x,y, label=label_not_nan(x, 'x data'))
plt.plot(x,z, label=label_not_nan(z, 'z data'))

rawDescription: How to exclude series from displaying in the matplotlib legend?

description: Exclude series from displaying in the matplotlib legend


code:
import sys
sys.version_info
sys.version_info[0]

rawDescription: How to detect Python Compiler Version 2 or 3 in python script

description: Detect Python Compiler Version 2 or 3 in python script


rawDescription: Get numpy array with only certain indices


code:
import subprocess
subprocess.Popen('service --status-all', stdout=subprocess.PIPE).stdout.read()

rawDescription: Python - how to get the services that run on my computer


code:
import tarfile

fp1 = open("hello.txt", "w")

tar = tarfile.open("myArchive.tar", "w")
tar.add("hello.txt")

fp1.write("Test String")
fp1.close()

tar.close()

rawDescription: does pythons tar file finalize a file added, or wait till its closed?

description: Does pythons tar file finalize a file added, or wait till its closed


code:
user_homes = UserHome.objects.filter(user=request.user)
ids = [h.home.id for h in user_homes]
other_homes = Home.objects.exclude(id__in=ids)

rawDescription: Getting objects from model which aren't in M2M relation in Django


code:
from Tkinter import *

def foo(event):
    global m

    key = event.char
    if key.upper() == 'P':
        c.move(a1,0,5)
        c.itemconfig(a1, fill='yellow')
    elif key.upper() == 'H':
        c.move(a1,0,-5)
        c.itemconfig(a1, fill='blue')
    elif key.upper() == 'K':
        c.move(a1,-5,0)
        c.itemconfig(a1, fill='white')
    elif key.upper() == 'M':
        c.move(a1,5,0)
        c.itemconfig(a1, fill='green')
    elif key == '\x1b':
        root.destroy()
    c.after_cancel(m)
    m = c.after(1000, move)

def move():
    c.move(a1, 0, 2)
    m = c.after(1000, move)

root = Tk()
c = Canvas(root,height=900,width=700)
c.pack()
p0 = (450,450)
p1 = (460,460)
a1 = c.create_oval(p0,p1,fill='red')
m = root.after(1000, move)
root.bind('<Key>', foo)
root.mainloop()

rawDescription: python-fail to get keypress in Tkinter

description: Python-fail to get keypress in Tkinter


code:
import linecache

final_lines = []
with open("file.txt") as f:
    for i, line in enumerate(f, 1):
        if "B" in line:
            if "A" in linecache.getline("file.txt", i-1):
                linestart = i - 2  ##2 lines before
            if "C" in linecache.getline("file.txt", i+1):
                lineend = i + 2  ##2 lines after
                for j in range(linestart, lineend+1):
                    final_lines.append(linecache.getline("file.txt", j))
print(final_lines)

rawDescription: How to identify consecutive lines with specific features using for loop in Python?

description: Identify consecutive lines with specific features using for loop in Python


rawDescription: How do I quantize data in pandas?

description: Quantize data in pandas


code:
import numpy as np
import matplotlib.pyplot as plt
import skimage.morphology, skimage.data

img = skimage.data.imread('j1ESv.png', 1)
labels = skimage.morphology.label(img)
labelCount = np.bincount(labels.ravel())
background = np.argmax(labelCount)
img[labels != background] = 255
plt.imshow(img, cmap=plt.cm.gray)
plt.show()

rawDescription: Filling holes in objects that touch the border of an image


code:
class CounterNode(template.Node):

  def __init__(self):
    self.count = 0

  def render(self, context):
    self.count += 1
    return self.count

@register.tag
def counter(parser, token):
  return CounterNode()

rawDescription: Django Template System: How do I solve this looping / grouping / counting?


code:
mapping = dict()
result = set()

with open(filename1, 'r') as f1, open(filename2, 'r') as f2:
    for line in f1:
        line = line.split()
        if line:
            key, val = line
            mapping[key] = float(val)  #1

    for line in f2:
        line = line.split()
        if line:
            key1, key2 = line
            if key1 in mapping:   #4
                result.add(min(line, key=lambda x: mapping.get(x, float('inf'))))  #2

for key in result:
    print('{k} {v}'.format(k=key, v=mapping[key]))   #3

rawDescription: Python data manipulation

description: Python data manipulation


code:
max_value = max(foo.value for foo in foos)
# instead of:
# max_value = max([foo.value for foo in foos])

rawDescription: max-Function for attributes of objects

description: Max-Function for attributes of objects


code:
import win32com.client as win32
word = win32.Dispatch("Word.Application")
word.Visible = 0
word.Documents.Open(file)
try:
    csp= doc.CustomDocumentProperties('property_you_want_to_know').value
    print('property is %s' % csp)

except exception as e:
    print ('\n\n', e)

doc.Saved= False
doc.Save()
doc.Close()

word.Quit()

rawDescription: Reading Custom Document properties in MS Word File using python


rawDescription: Matching optional numbers in regex

description: Matching optional numbers in regex


rawDescription: Django __iregex Returns Empty Response

description: Django __iregex Returns Empty Response


code:
split_list = []
for item in alist:
    if len(item) == 1:
        split_list.append([])
    split_list[-1].append(item)

rawDescription: Slicing a list conditionally

description: Slicing a list conditionally


code:
class ProcessorSelector(object):
    def __init__(self):
        self._processor_map = {}

    def register(self, type, processor):
        # type checking goes here if you're worried about it...
        # e.g. `if not isinstance(processor, Processor): raise TypeError`
        self._processor_map[type] = processor

    def select(self, type):
        return self._processor_pam[type]

selector = ProcessorSelector()
selector.register('jpg', JpgProcessor)
cls = selector.select('jpg')
processor = cls()
processor.process(file)

rawDescription: Selecting implementation (class) depending on variable


rawDescription: Python: How do i use itertools?

description: Python: How do i use itertools


code:
def __init__(self, *args, **kwargs):
    super(SchemeForm, self).__init__(*args, **kwargs)

    #...
    self.fields['domain'].widget.attrs['http-prefix'] = ''

rawDescription: Django forms how to add form field attribute


code:
command = toolpath + " " + query + " " + number + " > " + output;
process = subprocess.Popen(command.split(), stdout=subprocess.PIPE,Shell=True);
output = process.communicate()[0];

rawDescription: Python subprocess.Popen: redirection with ">" does not work


code:
import zipfile
XLSname = "/Users/user/myfile.xlsx"

EmbeddedFiles = zipfile.ZipFile(XLSname).namelist()
ImageFiles = [F for F in EmbeddedFiles if F.count('.jpg') or F.count('.jpeg') ]

for Image in ImageFiles:
    zipfile.ZipFile(XLSname).extract(Image)

rawDescription: Python script to save image from xlsx file to disk


rawDescription: Infer nearest, smaller value in numpy array


code:
results = list_from_your_regex
invalids = ['info', 'server', 'noreply', ...]
valid_emails = [good for good in results if good.split('@')[0] not in invalids]

rawDescription: Exclude specific email address with regex


code:
import os
import pandas as pd
directory = os.path.expanduser('~/home')
files = os.path.listdir(directory)
dfs = []
for filename in files:
    if '.tsv' in file:
        df = pd.read_table(os.path.join(directory,filename),sep='\t').set_index('bird')
        dfs.append(df)
master_df = pd.concat(dfs,axis=1)

rawDescription: Best strategy for merging a lot of data frames using pandas


code: OPTIONS = {'argv_emulation': True, 'includes': ['EXTERNAL LIBRARY'],}

rawDescription: How to bundle files together in a program?

description: Bundle files together in a program


code:
def multiply(p1, p2):
    final_coeffs = [0] * (len(p2.coeffs)+len(p1.coeffs)-1)
    for ind1, coef1 in enumerate(p1.coeffs):
        for ind2, coef2 in enumerate(p2.coeffs):
            final_coeffs[ind1 + ind2] += coef1 * coef2
    return Polynomial(final_coeffs)

rawDescription: How can I multiply two polynomials in Python using a loop and by calling another function?

description: Multiply two polynomials in Python using a loop and by calling another function


code:
salaryGrades = [list(range(s, s + 10000, 1000)) for s in range(10000, 100000, 10000)]
salaryGrades

rawDescription: Python: Populate Multidimensional Array

description: Python: Populate Multidimensional Array


code:
#tappos = [0 for x in range(7)]
self.tappos = [0 for x in range(7)]
...
#tappos[a] = DropDown(root)
self.tappos[a] = DropDown(root)    # And so on. You get the picture.
...

rawDescription: Python3 tkinter combobox default value

description: Python3 tkinter combobox default value


code:
BASE_URL='http://google.com'
HEADERS = {"accept-language":"klingon"}
import urllib, urllib2
def get_response(self, url, params):
    r"""
    >>> from minimock import Mock
    >>> urllib2.Request = Mock('urllib2.Request')
    >>> urllib2.urlopen = Mock('urllib2.urlopen')
    >>> get_response(None, 'http://google.com', {'foo':'bar'})
    Called urllib2.Request(
        'http://google.com',
        headers={'accept-language': 'klingon'})
    Called urllib2.urlopen(None, 'foo=bar')
    >>>
    """
    encoded_params = urllib.urlencode(params)
    request = urllib2.Request(BASE_URL, headers=HEADERS)
    response = urllib2.urlopen(request, encoded_params)
    return response

rawDescription: How do you test a function using which retrieves data by urllib2?

description: Test a function using which retrieves data by urllib2


code:
def eventFilter(self, obj, event):
    if obj is self.p1 and event.type() == event.GraphicsSceneMousePress:
        if event.button() == Qt.LeftButton:
            pos = event.scenePos()
            x = QtGui.QTableWidgetItem(
                '%0.01f' % ((pos.x() * 2.486 / 96) - 1))
            y = QtGui.QTableWidgetItem(
                '%0.01f' % (pos.y() * 10.28 / 512))
            row = self.coordinates.rowCount()
            self.coordinates.insertRow(row)
            self.coordinates.setItem(row, 0, x)
            self.coordinates.setItem(row, 1, y)

rawDescription: Writing mouse location to QTableWidget

description: Writing mouse location to QTableWidget


code:
class CBViewA(View):
    def get(request, *args, **kwargs):
        if 'save_as_new' in request.GET:
            return AddView.as_view()(request, *args, **kwargs)

rawDescription: Django class-based views: Invoking (forwarding to) a different class-based view


code:
from nltk.tokenize import TweetTokenizer
tknzr = TweetTokenizer()
tknzr.tokenize("The code didn't work!")

rawDescription: Preventing splitting at apostrophies when tokenizing words using nltk


code:
col = ws.Range("A1:A100")
for cell in col:
    cell.Offset(1,2).Value = "W0000%s" % cell.Value

rawDescription: Iterate thru Excel column A , write to column B using Python win32


code:
import tkinter as tk

class TextLineNumbers(tk.Canvas):

    def __init__(self, *args, **kwargs):
        tk.Canvas.__init__(self, *args, **kwargs)
        self.textwidget = None

    def attach(self, text_widget):
        self.textwidget = text_widget

    def redraw(self, *args):
        '''redraw line numbers'''
        self.delete("all")

        i = self.textwidget.index("@0,0")

        while True :
            dline= self.textwidget.dlineinfo(i)
            if dline is None: break
            y = dline[1]
            linenum = str(i).split(".")[0]

            # changed where text is draw: it starts from 4
            self.create_text(4, y, anchor="nw", text=linenum)
            i = self.textwidget.index("%s+1line" % i)

class CustomText(tk.Text):
    def __init__(self, *args, **kwargs):
        tk.Text.__init__(self, *args, **kwargs)

        self.tk.eval('''
            proc widget_proxy {widget widget_command args} {

                # call the real tk widget command with the real args
                set result [uplevel [linsert $args 0 $widget_command]]

                # generate the event for certain types of commands
                if {([lindex $args 0] in {insert replace delete}) ||
                    ([lrange $args 0 2] == {mark set insert}) ||
                    ([lrange $args 0 1] == {xview moveto}) ||
                    ([lrange $args 0 1] == {xview scroll}) ||
                    ([lrange $args 0 1] == {yview moveto}) ||
                    ([lrange $args 0 1] == {yview scroll})} {

                    event generate  $widget <<Change>> -when tail
                }

                # return the result from the real widget command
                return $result
            }
            ''')
        self.tk.eval('''
            rename {widget} _{widget}
            interp alias {{}} ::{widget} {{}} widget_proxy {widget} _{widget}
        '''.format(widget=str(self)))

class LinedText(tk.Frame):

    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)

        self.settings = self.Settings()
        self.linenumbers = None

        self.text = CustomText(self)
        self.vsb = tk.Scrollbar(orient="vertical", command=self.text.yview)
        self.vsb.pack(side="right", fill="y")

        self.text.configure(yscrollcommand=self.vsb.set)
        self.text.tag_configure("bigfont", font=("Helvetica", "24", "bold"))
        self.text.bind("<<Change>>", self._on_change)
        self.text.bind("<Configure>", self._on_change)
        self.text.insert("end", "one\ntwo\nthree\n")
        self.text.insert("end", "four\n",("bigfont",))
        self.text.insert("end", "five\n")
        self.text.focus()
        self.text.pack(side="right", fill="both", expand=True)

    def hide(self,event=None):
        if not self.settings.hide_linenumbers:
            self.settings.hide_linenumbers = True
            self.linenumbers.pack_forget()
            self.linenumbers = None

    def show(self,event=None):
        if self.linenumbers is None:
            self.linenumbers = TextLineNumbers(self, width=30)
            self.linenumbers.attach(self.text)
            self.linenumbers.pack(side="left", fill="y")
            self.settings.hide_linenumbers = False

    def _on_change(self, event):
        if self.linenumbers:
            self.linenumbers.redraw()

    class Settings():
        def __init__(self):
            self.hide_linenumbers = True

if __name__ == "__main__":
    root = tk.Tk()

    top_frame = tk.Frame(root)
    text = LinedText(top_frame)
    text.pack(expand=1, fill="both")
    top_frame.pack(side="top", expand=1, fill="both")

    bottom_frame = tk.Frame(root)
    button = tk.Button(bottom_frame, text="Hide", command=text.hide)
    button.pack(side="right")
    button = tk.Button(bottom_frame, text="Show", command=text.show)
    button.pack(side="right")
    bottom_frame.pack(side="bottom", fill="x")

    root.mainloop()

rawDescription: Why is my widget being overlapped?

description: Why is my widget being overlapped


code:
#!/usr/bin/env python
#-*- coding:utf-8 -*-

import cStringIO, traceback

from PyQt4 import QtGui, QtCore

errorNotice = """
An unhandled exception occurred. Details will be reported
via an automatic email.
"""

class MyMessageBox(QtGui.QMessageBox):
    def __init__(self, *args, **kwargs):
        super(MyMessageBox, self).__init__(*args, **kwargs)
        self.tracebackInfoStream = cStringIO.StringIO()

        self.setIcon(QtGui.QMessageBox.Critical)
        self.finished.connect(self.on_finished)

    def getTraceback(self, exceptionTraceback):
        traceback.print_tb(
            exceptionTraceback,
            None,
            self.tracebackInfoStream
        )

        self.tracebackInfoStream.seek(0)

        return self.tracebackInfoStream.read()

    def exceptHook(self, exceptionType, exceptionValue, exceptionTraceback):
        tracebackInfo = self.getTraceback(exceptionTraceback)

        self.setDetailedText(tracebackInfo)
        self.setText(errorNotice)
        self.exec_()

    @QtCore.pyqtSlot()
    def on_finished(self):
        QtGui.QApplication.quit()

class MyWindow(QtGui.QWidget):
    def __init__(self, parent=None):
        super(MyWindow, self).__init__(parent)

        self.pushButtonError = QtGui.QPushButton(self)
        self.pushButtonError.setText("Raise an Error!")
        self.pushButtonError.clicked.connect(self.on_pushButtonError_clicked)

        self.layoutVertical = QtGui.QVBoxLayout(self)
        self.layoutVertical.addWidget(self.pushButtonError)

    @QtCore.pyqtSlot()
    def on_pushButtonError_clicked(self):
        raise UserWarning("This is an error")

if __name__ == "__main__":
    import sys

    app = QtGui.QApplication(sys.argv)
    app.setApplicationName('MyWindow')

    myMessageBox = MyMessageBox()

    sys.excepthook = myMessageBox.exceptHook

    main = MyWindow()
    main.show()

    sys.exit(app.exec_())

rawDescription: PySide program crash handler

description: PySide program crash handler


code:
with myLock:
    doSomething()

rawDescription: Nice way (for CPU) to wait for a free lock in Python


code:
pins = []
supported_modes = []

for number in numbers:
    if number == 127:
        pins.append(supported_modes)
        supported_modes = []
    else:
        supported_modes.append(number)

rawDescription: How to create a 2D List in Python Based on Certain Values in a list

description: Create a 2D List in Python Based on Certain Values in a list


code:
import datetime, re
reg = re.compile(r'//\s*Copyright\s*\(c\)\s*([0-9]{4})(?:\s*\-\s*%d)?\.' % datetime.date.today().year, re.I)
reg.match('// copyright (c) 1997 -   2015').group(1)  # 1997

rawDescription: Regexp to validate copyrights

description: Regexp to validate copyrights


code:
re.findall('\((?P<content>.*?)\)', r'(It\'s something)')
["It\\'s something"] == [r"It\'s something"]

rawDescription: How to keep backslash in the result of a regular expression, when working in Python?

description: Keep backslash in the result of a regular expression, when working in Python


code:
import string
alphabet = string.letters + string.digits
max = 11

def int_to_base62(num):
    if num == 0:
        return alphabet[0]

    arr = []
    radix = len(alphabet)
    while num:
        arr.append(alphabet[num%radix])
        num /= radix
    arr.reverse()
    return (alphabet[0] * (max - len(arr))) + ''.join(arr)

def base62_to_int(str):
    radix = len(alphabet)
    power = len(str) - 1
    num = 0
    for char in str:
        num += alphabet.index(char) * (radix ** power)
        power -= 1
    return num

rawDescription: Generate fixed length hash in python for url parameter


code:
import os

def list_files(startpath):
    for root, dirs, files in os.walk(startpath):
        level = root.replace(startpath, '').count(os.sep)
        indent = ' ' * 4 * (level)
        print('{}{}/'.format(indent, os.path.basename(root)))
        subindent = ' ' * 4 * (level + 1)
        for f in files:
            print('{}{}'.format(subindent, f))

rawDescription: List directory tree structure using Python


code:
x = xrange(3)
type(x)
i = x.__iter__()
type(i)

rawDescription: why is xrange able to go back to beginning in Python?

description: Why is xrange able to go back to beginning in Python


code:
from django.contrib.auth.decorators import user_passes_test

def email_check(user):
    return user.email.endswith('@example.com')

@user_passes_test(email_check)
def my_view(request):
    ...

rawDescription: Django applying custom user permissions

description: Django applying custom user permissions


code:
connection = cx_Oracle.connect("user/pw@tns")
cursor = connection.cursor()
cursor.execute("select to_char(some_number) from some_table")
for rawNumber, in cursor:
    number = decimal.Decimal(rawNumber)

rawDescription: formatting different kind of float numbers as original format with python

description: Formatting different kind of float numbers as original format with python


code:
@cherrypy.expose
def index(self):
   ser = serial.Serial('/dev/ttyUSB0')
   ser.write(b'hello')
   return """<html>
      <head></head>
      <body>
        <form method="get" action="generate">
          <button type="submit">Press!</button>
        </form>
      </body>
    </html>"""

rawDescription: Cherrypy server run a python script

description: Cherrypy server run a python script


code:
import random
word = raw_input("Enter a word: ")

charlst = list(word)        # convert the string into a list of characters
random.shuffle(charlst)     # shuffle the list of characters randomly
new_word = ''.join(charlst) # convert the list of characters back into a string

rawDescription: Randomize letters in a word

description: Randomize letters in a word


code:
import numpy as np
x= np.array( ((0,0,0,0), (0,0,0,2.8) ))
np.argmax(x.max(axis=1))

rawDescription: Safest way to find the row of maximum value in a numpy array


code:
james = User.objects.get(pk= 123)
james_groups = james.group_set.all()

rawDescription: Django - filter ManyToManyField?

description: Django - filter ManyToManyField


code: In [179]: df.groupby('group').filter(lambda x: len(x.drop_duplicates(subset=['age'])) == 1)

rawDescription: Removing all rows of a duplicate based on value of multiple columns


rawDescription: How to get request value if a variable appears several times?

description: Get request value if a variable appears several times


code:
observed_sequence = [5, 6, 6, 6, 6, 6, 6, 2, 2, 2, 2, 2, 2, 4, 4, 4]
states = range(20) # experiment with this number
symbols = set(observed_clusters)
trainer = HiddenMarkovModelTrainer(states, symbols)
model = trainer.train_unsupervised([observed_sequence])

description: Initialize HiddenMarkovModelTrainer object


rawDescription: Rectangle Scatter Plot with axis type datetime in Bokeh


code: doc = open("C:/...").read().split()

rawDescription: Python for loop returns zero after first iteration


code:
dosnames=['CON', 'PRN', 'AUX', 'NUL', 'COM1', 'COM2', 'COM3', 'COM4', 'COM5', 'COM6', 'COM7', 'COM8', 'COM9', 'LPT1', 'LPT2', 'LPT3', 'LPT4', 'LPT5', 'LPT6', 'LPT7', 'LPT8', 'LPT9']
final=''
string='th\xe8is i\xaas \xb2a te><s\x0b\xe6t\xb0.\xb4'
for char in string:
  if not (char in '<>:"/\|?*'):
    if ord(char)>31:
      final+=char
if final in dosnames:
  #oh dear...
  raise SystemError('final string is a DOS name!')
elif final.replace('.', '')=='':
  raise SystemError('final string is all periods!')

rawDescription: How to remove invalid character in filename under windows using Python

description: Remove invalid character in filename under windows using Python


code:
import csv
import os
import datetime

inFilePath = "C:\\Temp\\SO\\test.csv"
outFilePath = "C:\\Temp\\SO\\temp.csv"

inFile = open(inFilePath, "r")
outFile = open(outFilePath, "wb")

reader = csv.reader(inFile, delimiter='|')
writer = csv.writer(outFile, delimiter='|', quotechar='"', quoting=csv.QUOTE_MINIMAL)

for row in reader:
    if "Date     " in row:
        writer.writerow(row)
        continue
    newDate = datetime.datetime.strptime(row[0], '%d/%m/%Y').strftime('%Y-%m-%d')
    newCell = newDate + " " + row[1]
    row.append(newCell)
    writer.writerow(row)

inFile.close()
outFile.close()

os.remove(inFilePath)
os.rename(outFilePath, inFilePath)

rawDescription: How to update value and combine columns in csv file using Python

description: Update value and combine columns in csv file using Python


code:
import re

f = open('script.py','rb')
script = f.read()
f.close()

newscript = re.sub("(print\(.*)\)", "\g<1>.decode('utf-8'))", script)

f = open('script.py', 'wb')
f.write(newscript)
f.close()

rawDescription: Appending print commands with .decode() method


code: a = Array.CreateInstance(Double, 3, 3)

rawDescription: howto create a multidimensional Array of floats with Pythonnet

description: Howto create a multidimensional Array of floats with Pythonnet


code:
import lib601.sm as sm

class FollowFigure(sm.SM):
    def __init__(self, waypointsList):
        self.waypoints = waypointsList
        self.next_to_visit = 0  # The next waypoint to be visited

    def getNextValues(self, state, inp):
        sensors = inp
        current_point = sensors.odometry.point()
        if self.waypoints[self.next_to_visit].isNear(current_point, 0.01):
            # We reached the next waypoint, go for next waypoint
            self.next_to_visit += 1
        # Return the next waypoint to be visited
        return (state, self.waypoints[self.next_to_visit])

rawDescription: Conditional for loop which remembers the iteration number


code:
# Names of nodes to start
#   most people will only start one node:
CELERYD_NODES="worker"
#   but you can also start multiple and configure settings
#   for each in CELERYD_OPTS (see `celery multi --help` for examples):
#CELERYD_NODES="worker1 worker2 worker3"
#   alternatively, you can specify the number of nodes to start:
#CELERYD_NODES=10

# Absolute or relative path to the 'celery' command:
CELERY_BIN="/usr/local/bin/celery"
#CELERY_BIN="/virtualenvs/def/bin/celery"

# App instance to use
# comment out this line if you don't use an app
CELERY_APP="fb_archive.celery:app"
# or fully qualified:
#CELERY_APP="proj.tasks:app"

# Where to chdir at start.
CELERYD_CHDIR="/home/ubuntu/workspace/ward/www"

# Extra command-line arguments to the worker
CELERYD_OPTS="--time-limit=300 --concurrency=8 --loglevel=info"

# %N will be replaced with the first part of the nodename.
CELERYD_LOG_FILE="/var/log/celery/%N.log"
CELERYD_PID_FILE="/var/run/celery/%N.pid"

# Workers should run as an unprivileged user.
#   You need to create this user manually (or you can choose
#   a user/group combination that already exists, e.g. nobody).
CELERYD_USER="root"
CELERYD_GROUP="root"

# If enabled pid and log directories will be created if missing,
# and owned by the userid/group configured.
CELERY_CREATE_DIRS=1

rawDescription: How to create Daemon for celery?

description: Create Daemon for celery


code:
def start_work(self):
    thread = threading.Thread(target=self.do_work, args=(args, go, here))
    thread.setDaemon(True)
    thread.start()
def do_work(self, args, go, here):
    # do work here
    # wx.CallAfter will call the specified function on the GUI thread
    # and it's safe to call from a separate thread
    wx.CallAfter(self.work_completed, result, args, here)
def work_completed(self, result, args, here):
    # use result args to update GUI controls here
    self.text.SetLabel(result)

description: WxPython Application.DoEvents() equivalent


code:
import wx

class panel_class(wx.Panel):
    def __init__(self, *args, **kwds):
        """Trying to implement your magic ``panel```"""
        wx.Panel.__init__(self, *args, **kwds)
        pnl = self
        szmain = wx.BoxSizer(wx.HORIZONTAL)
        szmain.Add(wx.TextCtrl(pnl, -1, 'Database path'), 1, wx.EXPAND)
        szmain.Add(wx.Button(pnl, -1, 'Database path'), 0, wx.EXPAND)
        pnl.SetSizer(szmain)

class myframe(wx.Frame):
    def __init__(self, *args, **kwds):
        """Constructor"""

        wx.Frame.__init__(self, *args, **kwds)#None, title="Title Options", size=(520, 390))

        prefPanel = wx.Panel(self)

        """This makes no sense: according to the wx.Frame.__init__ above self is a wx.Frame."""
#         prefPanel = self

        # SET THE SIZER OBJECT UP
        prefSizer = wx.GridBagSizer(13, 9)

        # SET BASELINE INDEX VARIABLES
        xIndex = 0
        yIndex = 0

        # DEFAULT DATABSE EXTENSIONS
        self.tc_DBExt = wx.TextCtrl(prefPanel, -1, "", (0,0), (150,21))
        self.label_DBExt = wx.StaticText(prefPanel, label="Default Database Extensions:")
        help_tc_DBExt= "Enter this as: *.<extension>"
        self.tc_DBExt.SetToolTip(wx.ToolTip(help_tc_DBExt))
        """Replaced with something static."""
        self.tc_DBExt.Value = 'conftxt'#guiFunctions.configMe("general", "database_extensions")

        prefSizer.Add(self.label_DBExt, pos=(xIndex, 0), flag=wx.LEFT|wx.ALIGN_CENTER_VERTICAL|wx.TOP, border=10)
        prefSizer.Add(self.tc_DBExt, pos=(xIndex, 1), span=(1,5), flag=wx.EXPAND|wx.LEFT|wx.ALIGN_CENTER_VERTICAL|wx.TOP, border=10).SetMinSize((200,22))

        """Assuming panel definition from outside.

        It has to be created here. If it is to be created **before**
        the parent is created, it is very complicated to create it with a
        dummy parent and ``Reparent`` it to this Frame/Panel. Don't do that."""

        panel = panel_class(prefPanel, -1)

        """Attach ``panel`` to a sizer in **this** hierarchy
        It looks disconnected, because it has brought already it's own
        sizer, which is child to the GridBagSizer."""
        xindex = 1
        prefSizer.Add(panel, pos=(xindex, 0), span=(1,5), flag=wx.EXPAND|wx.LEFT|wx.ALIGN_CENTER_VERTICAL|wx.TOP, border=10).SetMinSize((200,22))

        """You have to tell wxPython somehow to what element the sizer is coupled (in this case to the main pane)l"""
        prefPanel.SetSizer(prefSizer)

        """I have no idea """
        #panel.SetSizer(sizer2)
        #sizer2.Fit(panel)

        """Normally not needed/happening automagically on standard controls"""
        #panel.Refresh()
        #panel.Update()
        #panel.Layout()

    def add_panel_to_layout(self):
        pass

if __name__ == '__main__':
    app = wx.App(0)

    frm = myframe(None, -1,  title="Title Options", size=(520, 390))

    frm.Show()

    """Call it here **after** all elements have been created"""
    import wx.lib.inspection
    wx.lib.inspection.InspectionTool().Show()
    app.MainLoop()

rawDescription: wxPython Panel is two shades of gray?

description: WxPython Panel is two shades of gray


code:
def unshared_copy(inList):
    if isinstance(inList, list):
        return list( map(unshared_copy, inList) )
    return inList

alist = unshared_copy(your_function_returning_lists())

rawDescription: How to make a completely unshared copy of a complicated list? (Deep copy is not enough)

description: Make a completely unshared copy of a complicated list? (Deep copy is not enough)


code:
df = pd.DataFrame(np.random.randn(6),index=dates,columns=list('A'))
df.index = df.index + pd.DateOffset(days=15)
df

rawDescription: Offset date for a Pandas DataFrame date index


code:
from consumers.a import A
from consumers.b import B
from consumers.C import C

a = A()
b = B()
c = C()

rawDescription: Best way to instantiate classes which is in imported modules

description: Instantiate classes which is in imported modules


rawDescription: Generate Random maps data in google maps like format using Python


code:
import subprocess

def launchWithoutConsole(command, args):
    """Launches 'command' windowless and waits until finished"""
    startupinfo = subprocess.STARTUPINFO()
    startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
    return subprocess.Popen([command] + args, startupinfo=startupinfo).wait()

if __name__ == "__main__":
    # test with "pythonw.exe"
    launchWithoutConsole("d:\\bin\\gzip.exe", ["-d", "myfile.gz"])

rawDescription: How do I eliminate Windows consoles from spawned processes in Python (2.7)?

description: Eliminate Windows consoles from spawned processes in Python (2.7)


code:
d1 = datetime.strptime('08:10:32', '%H:%M:%S')
d2 = datetime.strptime('12:34:45', '%H:%M:%S')
time_delta = d2 - d1
float('.'.join(str(time_delta).split(":")[0:2]))

rawDescription: Calculate time to fraction by using python


code:
def get_name(line):
    return line[1:].rsplit('|', 1)[-1].strip()

with open('input.txt') as f, open('output.txt', 'w') as fout:
    name = ''

    # Phase 1: Find unavailable sequence
    unavailable = set()
    for line in f:
        if line.startswith('>'):
            name = get_name(line)
        else:
            if 'Sequence unavailable' in line:
                unavailable.add(name)

    # Phase 2: Filter avilable sequence
    f.seek(0)
    keep = False
    for line in f:
        if line.startswith('>'):
            name = get_name(line)
            keep = name not in unavailable
        if keep:
            fout.write(line)

rawDescription: Deleting specific lines from text file

description: Deleting specific lines from text file


code:
class A():
    def __init__(self, attr1, attr2):
        self.attr1 = attr1
        self.b = B(attr2)

class B():
    def __init__(self, attr2):
        self.attr2 = attr2

rawDescription: Create class instance within a class

description: Create class instance within a class


code:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import BooleanProperty
from kivy.lang import Builder

Builder.load_string('''
<MyWidget>:
    orientation: 'vertical'
    Label:
        size_hint: 1, 0.25
        text: 'Label1'
    GridLayout:
        size_hint: 1, 0.25
        cols: 2
        Button
            text: 'Button1'
        Button
            text: 'Button2'
        Button
            text: 'Button3'
        Button
            text: 'Button4'
    Label:
        size_hint: 1, 0.5
        text: 'Label2'
''')

class MyWidget(BoxLayout):
    pass

class MyApp(App):
    def build(self):
        return MyWidget()

if __name__ == '__main__':
    MyApp().run()

rawDescription: How can I organise kivy layout?

description: Organise kivy layout


rawDescription: Problem with search operation

description: Problem with search operation


code:
from re import findall
name = 'Kalvo'
info = 'PC1:\nKalvo (Read)(Write)\nKL27 (Read)(Write)'
findall("{}.*".format(name), info)[0]

rawDescription: python find string after linebreak

description: Python find string after linebreak


code:
import dis
dis.dis(Foo.bar)

rawDescription: Python class variable int vs array

description: Python class variable int vs array


code:
def URLRequest(url, params, method="POST"):
    res, content = Http().request(url, method, urllib.urlencode(params))
    return {'res':res, 'content':content}

rawDescription: Is this the right way to write a POST function in Python?


code:
import csv

infilename = r'C:\Users\Sulabh Kumra\Desktop\input.csv'
outfilename = r'C:\Users\Sulabh Kumra\Desktop\output.csv'

with open(infilename, 'rb') as fp_in, open(outfilename, 'wb') as fp_out:
    reader = csv.reader(fp_in, delimiter=",")
    writer = csv.writer(fp_out, delimiter=",")

    blank_line = next(reader)
    writer.writerow(blank_line)

    headers = next(reader)  # read title row

    headers[26:26] = ['New Label']

    writer.writerow(headers)

    for row in reader:
        row[26:26] = [0]
        writer.writerow(row)

rawDescription: Adding a column in csv using python

description: Adding a column in csv using python


code:
def server_update(request, pk, template_name='servers/server_form.html'):
    server = get_object_or_404(Server, pk=pk)
    form = ServerForm(request.POST or None, request.FILES or None,  instance=server)
    if form.is_valid():
        edit = form.save(commit=False)
        edit.save()
        return redirect('server_list')
    return render(request, template_name, {'form':form})

rawDescription: Updating Records with image field in Django?


code: [filename for path in dirs for filename in os.listdir(path)]

rawDescription: python list comprehensions; compressing a list of lists?

description: Python list comprehensions; compressing a list of lists


code:
import heapq

a = [("a", 6), ("b", 4), ("c", 3), ("d", 1)]
b = [("e", 5), ("f", 5), ("g", 4), ("h", 2)]

class Pair:
    def __init__(self, i, j, value):
        self.i = i
        self.j = j
        self.value = value
    def __cmp__(self, other):
        return other.value - self.value

def solution(a, b):
    heap = []
    for i in range(len(a)):
        heapq.heappush(heap, Pair(i, 0, a[i][1] + b[0][1]))
    while len(heap) > 0:
        pair = heapq.heappop(heap)
        yield (a[pair.i], b[pair.j], pair.value)
        if pair.j + 1 < len(b):
            heapq.heappush(heap, Pair(pair.i, pair.j + 1, a[pair.i][1] + b[pair.j + 1][1]))

for (a, b, value) in solution(a, b):
    print ("%s %s -> %d" % (a, b, value))

rawDescription: Generate All Permutations of Several Lists in Permutation-Value Order


rawDescription: How to sub the file path to get just the file name?

description: Sub the file path to get just the file name


code:
class Foo(object):
    def __init__(self, apple=None, orange=None):
        super(Foo, self).__init__()
        if None is apple and None is orange:
            raise ValueError('apple and orange cannot both be None')
        if None is not apple and None is not orange:
            raise ValueError('apple and orange cannot both be set')

        self._apple = apple
        self._orange = orange

    @property
    def apple(self):
        return self._apple

    @property
    def orange(self):
        return self._orange

    def setAppleClearOrange(self, value):
        if (value is None):
            raise ValueError('Cannot set both to None')
        self._orange = None
        self._apple = value

    def setOrangeClearApple(self, value):
        if (value is None):
            raise ValueError('Cannot set both to None')
        self._apple = None
        self._orange = value

rawDescription: Force one of two python class attributes to be always be assigned a value?


code:
import pytz
import re
from datetime import datetime

def find_timezone_name(input):
    match = re.match(r'.*([+-]\d+) (\d+)', input)
    if match:
        offset = int(match.group(1))+int(match.group(2))/10.0
    else:
        raise ValueError('Unexpected input format')

    refdate = datetime.now()
    for tzname in pytz.common_timezones:
        tzinfo = pytz.timezone(tzname)
        tzoffset = tzinfo.utcoffset(refdate)
        if offset == tzoffset.total_seconds()/3600:
            return tzname
    return "Unknown"

print(find_timezone_name('PST -8 0'))

rawDescription: timezone conversion from PST -8 0 to its alphabetic name

description: Timezone conversion from PST -8 0 to its alphabetic name


code:
def search_file(filename, target, start_at = 0):
    with open(filename) as infile:
        for line_no, line in enumerate(infile):
            if line_no < start_at:
                continue
            if line.find(target) >= 0:
                return line_no
    return None

rawDescription: Optimizing python file search?

description: Optimizing python file search


code:
d = {'foo': 'bar'}
for key in d.viewkeys():
    d['spam'] = 'eggs'

d = {'foo': 'bar', 'spam': 'eggs'}
for key in d.viewkeys():
   del d['spam']

rawDescription: Do Python 2.7 views, for/in, and modification work well together?


code:
from guppy import hpy; h=hpy()
h.heap()
h.iso(1,[],{})
x=[]
h.iso(x).sp

rawDescription: How do I profile memory usage in Python?

description: Profile memory usage in Python


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

a = np.arange(10)

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(a-5,a)
ax.set_xlim(xmin = -1.)
plt.show()

rawDescription: matplotlib optionally autoscale axis range on the left or right

description: Matplotlib optionally autoscale axis range on the left or right


code:
from mpl_toolkits.mplot3d import Axes3D
plt.clf()
fig = pylab.figure()
ax = Axes3D(fig)
ax.set_xlim3d(0, 1000)
ax.set_ylim3d(0,1000)
ax.set_zlim3d(0,1000)

rawDescription: How to scale axes in mplot3d

description: Scale axes in mplot3d


rawDescription: find where a numpy array is equal to any value of a list of values

description: Find where a numpy array is equal to any value of a list of values


code:
import json

pre = driver.find_element_by_tag_name("pre").text
data = json.loads(pre)
print(data)

rawDescription: How to get a JSON response from a Google Chrome Selenium Webdriver client?

description: Get a JSON response from a Google Chrome Selenium Webdriver client


code:
import boto
access_key = boto.config.get_value('Credentials', 'aws_access_key_id')
secret_key = boto.config.get_value('Credentials', 'aws_secret_access_key')

rawDescription: Boto: Dynamically get aws_access_key_id and aws_secret_access_key in Python code from config?


rawDescription: How to add or replace some string at a particular column position in a text file

description: Add or replace some string at a particular column position in a text file


code:
import wx
import wx.webkit

source = """\

Hello world

"""

class Try_Webkit(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title)
        panel = wx.Panel(self)
        sizer = wx.BoxSizer(wx.VERTICAL)

        webkit = wx.webkit.WebKitCtrl(panel, -1, size=(200,200))
        webkit.SetPageSource(source)
        sizer.Add(webkit, 1, wx.EXPAND)
        panel.SetSizer(sizer)

app = wx.App()
frm = Try_Webkit(None, -1, "Try Webkit")
frm.Show()
app.MainLoop()

rawDescription: WxPython: Not able to load the html with WebKitCtrl.SetPageSource in MAC


code:
# Hits the database
foo = Foo.objects.prefetch_related('bars').latest()

# Doesn't hit the database
[x.value for x in foo.bars.all()]

rawDescription: Django - performance of using related model fields


code:
from xml.etree import ElementTree

with open('test.xml', 'rt') as f:
    tree = ElementTree.parse(f)

for node in tree.iter('sequence'):
    sequenceid = node.attrib.get('id')
    name = node.findtext('name')

rawDescription: Trying to extract xml element using python 2.7


code:
import scipy.stats
scipy.stats.norm(0, 1)
scipy.stats.norm(0, 1).pdf(0)
scipy.stats.norm(0, 1).cdf(0)
scipy.stats.norm(100, 12)
scipy.stats.norm(100, 12).pdf(98)
scipy.stats.norm(100, 12).cdf(98)
scipy.stats.norm(100, 12).cdf(100)

rawDescription: Calculate probability in normal distribution given mean, std in Python


code:
# mockup of lines read from two documents
doc_lines_1 = ["today is a beautiful day", "tomorrow is rainy day"]
doc_lines_2 = ["tomorrow is rainy day is the second document"]

# a list containing your documents
doc_list = [doc_lines_1, doc_lines_2]

from collections import defaultdict

d = defaultdict(set)

for doc_no, doc in enumerate(doc_list):
    for line in doc:
        for word in line.strip().split():
            d[word].update([doc_no])

print(d['day'])     # {0, 1} "day" in both document 0 and 1
print(d['rainy'])   # {0, 1} "rainy" in both document 0 and 1
print(d['second'])  # {1}    "second" only in document 1

rawDescription: How to place every word in a list as an entry in the dictionary

description: Place every word in a list as an entry in the dictionary


code:
class YourDictModel(ndb.Model):
    data = ndb.BlobKeyProperty()

huge_dict = dict(...)

file_name = files.blobstore.create(mime_type='application/octet-stream')
with files.open(file_name, 'a') as f:
    f.write(marshal.dumps(huge_dict))

    # Finalize the file. Do this before attempting to read it.
    files.finalize(file_name)

    # Get the file's blob key
    blob_key = files.blobstore.get_blob_key(file_name)
    entity = YourDictModel(data = blob_key)

    entity.put()

rawDescription: Print a dictionary and save it to a file, then copy it to a py file to use?


code:
def callback(fn):
    def inner(self, *args):
        return _do_callback(fn.__get__(self, type(self)), self.log, *args)
    return inner

class Foo(object):
    def __init__(self):
        self.log = Log('Foo')

    @callback
    def cb1_wrapped(self, x):
        pass

rawDescription: Decorator to convert an instance method into a class function


code:
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cm as cm
import matplotlib.colors as mcolors

def colorbar_index(ncolors, cmap):
    cmap = cmap_discretize(cmap, ncolors)
    mappable = cm.ScalarMappable(cmap=cmap)
    mappable.set_array([])
    mappable.set_clim(-0.5, ncolors+0.5)
    colorbar = plt.colorbar(mappable)
    colorbar.set_ticks(np.linspace(0, ncolors, ncolors))
    colorbar.set_ticklabels(range(ncolors))

def cmap_discretize(cmap, N):
    """Return a discrete colormap from the continuous colormap cmap.

        cmap: colormap instance, eg. cm.jet.
        N: number of colors.

    Example
        x = resize(arange(100), (5,100))
        djet = cmap_discretize(cm.jet, 5)
        imshow(x, cmap=djet)
    """

    if type(cmap) == str:
        cmap = plt.get_cmap(cmap)
    colors_i = np.concatenate((np.linspace(0, 1., N), (0.,0.,0.,0.)))
    colors_rgba = cmap(colors_i)
    indices = np.linspace(0, 1., N+1)
    cdict = {}
    for ki,key in enumerate(('red','green','blue')):
        cdict[key] = [ (indices[i], colors_rgba[i-1,ki], colors_rgba[i,ki])
                       for i in xrange(N+1) ]
    # Return colormap object.
    return mcolors.LinearSegmentedColormap(cmap.name + "_%d"%N, cdict, 1024)

fig, ax = plt.subplots()
A = np.random.random((10,10))*10
cmap = plt.get_cmap('YlGnBu')
ax.imshow(A, interpolation='nearest', cmap=cmap)
colorbar_index(ncolors=11, cmap=cmap)
plt.show()

rawDescription: Correcting matplotlib colorbar ticks

description: Correcting matplotlib colorbar ticks


code:
from PyQt4 import QtCore, QtGui, uic

class MainWindow(QtGui.QMainWindow):

    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        uic.loadUi('MainWindow.ui', self)
        # Buttons
        self.QStartButton.clicked.connect(self.start_timer)
        self.QStopButton.clicked.connect(self.stop_timer)

    def start_timer(self):
        # Initialize timer
        self.timer = QtCore.QTimer()
        self.now = 0
        # Update display and start timer
        self.update_timer()
        self.timer.timeout.connect(self.tick_timer)
        self.timer.start(1000) # Duration of one second = 1000 msec

    def update_timer(self):
        self.runtime = "%d:%02d" % (self.now/60,self.now % 60)
        self.lcdNumber.display(self.runtime)

    def tick_timer(self):
        self.now += 1
        self.update_timer()

    def stop_timer(self):
        self.timer.stop

rawDescription: QTimer/Python: Count seconds from start to stop


code:
def Game(x):
    # x, str(x), position
    stack = [(x,str(x),0)]
    # return value
    res = None

    while stack:
        if res is not None:
            # we have a return value
            if not res:
                stack.pop()
                res = True
                continue
            # res is True, continue to search
            res = None
        x, s, pos = stack.pop()
        if x == 0:
            res = True
            continue
        if pos == len(s):
            # end of loop, return False
            res = False
            continue
        stack.append((x,s,pos+1))
        digit = s[pos]
        if digit == '0':
            continue
        x -= int(digit)
        # recurse, starting with position 0
        stack.append((x,str(x),0))

    return res

rawDescription: How to make this method non-recursive?

description: Make this method non-recursive


code:
def myfunction (symbols) :
    symbolList = []
    counter = 0
    while counter < len(symbols) :
        for i in range(100) : # assumes that you will never have more than 100 categories
            symbolList[i] = [s for s in symbols if s.name == i]
            counter += len(symbolList[i])
    outputList = []
    for k in symbolList :
        if len(k) == 0 :
            return None
        else :
            outputList.append(k[0].metrics['% InclusiveTotal'])
    finalOutput = ''
    for o in outputList :
        if finalOutput == '' :
            finalOutput = o
        else :
            finalOutput = finalOutput - o
    return finalOutput

rawDescription: How would I edit the following Python function so that I can easily append an array with additional tokens?


code:
import wx

class MyPanel(wx.Panel):
    """ class MyPanel creates a panel to draw on, inherits wx.Panel """
    def __init__(self, parent, id):
        # create a panel
        wx.Panel.__init__(self, parent, id)
        self.SetBackgroundColour("white")
        self.Bind(wx.EVT_PAINT, self.OnPaint)

    def OnPaint(self, evt):
        """set up the device context (DC) for painting"""
        self.dc = wx.PaintDC(self)
        self.dc.BeginDrawing()
        self.dc.SetPen(wx.Pen("grey",style=wx.TRANSPARENT))
        self.dc.SetBrush(wx.Brush("grey", wx.SOLID))
        # set x, y, w, h for rectangle
        self.dc.DrawRectangle(250,250,50, 50)
        self.dc.EndDrawing()
        del self.dc

app = wx.PySimpleApp()
# create a window/frame, no parent, -1 is default ID
frame = wx.Frame(None, -1, "Drawing A Rectangle...", size = (500, 500))
# call the derived class, -1 is default ID
MyPanel(frame,-1)
# show the frame
frame.Show(True)
# start the event loop
app.MainLoop()

rawDescription: wxPython - Drawing an unfilled rectangle with the DC

description: WxPython - Drawing an unfilled rectangle with the DC


code:
def autocomplete(self, category):
    '''
    If possible, autocomplete a word according to its category.
    '''
    root = ''.join(self.chars).split()[-1]  #The bit after the last space
    pool = self._get_list_of_existing(category)
    matches = [i for i in pool if i.find(root) == 0]
    if len(matches) == 1:
        match = matches[0]+' '
    elif len(matches) > 1:
        match = self._get_common_beginning(matches)
    else:
        return
    self.chars.extend(list(match[len(root):]))

def _get_common_beginning(self, strings):
    '''
    Return the strings that is common to the beginning of each string in
    the strings list.
    '''
    result = []
    limit = min([len(s) for s in strings])
    for i in range(limit):
        chs = set([s[i] for s in strings])
        if len(chs) == 1:
            result.append(chs.pop())
        else:
            break
    return ''.join(result)

rawDescription: Is there a python library for custom autocompletion?


code:
from django.utils.html import format_html

class MyModelAdmin(admin.ModelAdmin):

    readonly_fields = ['avg_difficulty']

    def avg_difficulty(self, obj):
        return format_html(
            (''), obj.avg_difficulty)
    avg_difficulty.short_description = "Average difficulty"

rawDescription: Using a widget for aggregate value in Django Admin


code:
from dis import dis
dis(lambda: t.m())
dis(lambda: getattr(t, 'm')())

rawDescription: Is there anything static about python function / method invocations?


code:
testmodules = [
    'cogapp.test_makefiles',
    'cogapp.test_whiteutils',
    'cogapp.test_cogapp',
    ]

suite = unittest.TestSuite()

for t in testmodules:
    try:
        # If the module defines a suite() function, call it to get the suite.
        mod = __import__(t, globals(), locals(), ['suite'])
        suitefn = getattr(mod, 'suite')
        suite.addTest(suitefn())
    except (ImportError, AttributeError):
        # else, just load all the test cases from the module.
        suite.addTest(unittest.defaultTestLoader.loadTestsFromName(t))

unittest.TextTestRunner().run(suite)

rawDescription: how to run all Python unit tests in a directory

description: Run all Python unit tests in a directory


code:
from twisted.internet.task import cooperate

def generate_update_deferreds(collection, many_docs):
    for doc in update_docs:
        d = collection.update({'_id': doc['_id']}, doc, upsert=True)
        yield d

work = generate_update_deferreds(...)
worker_tasks = []
for i in range(count):
    task = cooperate(work)
    worker_tasks.append(task)

all_done_deferred = DeferredList([task.whenDone() for task in worker_tasks])

rawDescription: Lazy Deferred List reaching maximum recursion depth


code:
from lxml import etree
import urllib

web = urllib.urlopen("http://www.ffiec.gov/census/report.aspx?year=2011&state=01&report=demographic&msa=11500")
s = web.read()

html = etree.HTML(s)

## Get all 'tr'
tr_nodes = html.xpath('//table[@id="Report1_dgReportDemographic"]/tr')

## 'th' is inside first 'tr'
header = [i[0].text for i in tr_nodes[0].xpath("th")]

## Get text from rest all 'tr'
td_content = [[td.text for td in tr.xpath('td')] for tr in tr_nodes[1:]]

rawDescription: How to extract tables from websites in Python

description: Extract tables from websites in Python


code:
class Interpolator:
    def __init__(self,x,y):
        if len(x)!=len(y):
            raise BaseException("Lists must have the same length")
        self.xlist=x
        self.ylist=y
        self.len=len(x)
    def find_x_index(self,x0): # find index i such that xlist[i]<=x0<xlist[i+1]
        a,b=0,self.len-1
        while b-a>1:
            m=int((b+a)/2)
            if x0<self.xlist[m]:
                b=m
            else:
                a=m
        return a
    def add_point(self,x,y): # add a new point
        if x<self.xlist[0]:
            self.xlist.insert(0,x)
            self.ylist.insert(0,y)
        elif x>self.xlist[-1]:
            self.xlist.append(x)
            self.ylist.append(y)
        else:
            i=self.find_x_index(x)
            self.xlist.insert(i+1,x)
            self.ylist.insert(i+1,y)
        self.len+=1
    def interpolate(self,x0): # interpolates y value for x0
        if x0<self.xlist[0] or x0>self.xlist[-1]:
            raise BaseException("Value out of range")
        a=self.find_x_index(x0)
        eps=(x0-self.xlist[a])/(self.xlist[a+1]-self.xlist[a]) # interpolation
        return (eps*self.ylist[a+1]+(1-eps)*self.ylist[a])

itp=Interpolator([1,2,3],[1,3,4])
print(itp.interpolate(1.6))
itp.add_point(1.5,3)
print(itp.interpolate(1.6))

rawDescription: interp1d with streaming data?

description: Interp1d with streaming data


code:
import matplotlib.pyplot as plt
from matplotlib.transforms import TransformedBbox
fig, ax = plt.subplots()
t = ax.text(0.5, 5, r'$x_n = (2.1, 4.4) \in R^2$', fontsize=18)
#draw the plot so it's possible to get the bounding box
plt.draw()

#either plot everything or set the axes to their final size
ax.set_xlim((0, 10))
ax.set_ylim(0, 10)
#get the bbox of the text
bbox = t.get_window_extent()
#get bbox in data coordinates
tbbox = TransformedBbox(bbox, ax.transData.inverted())
coords = tbbox.get_points()
#get center of bbox
x = (coords[1][0] + coords[0][0]) / 2
#get bottom of bbox
y = coords[0][1]
ax.arrow(x, y, 0, -2, fc='k', ec='k', head_width=0.5, head_length=1)

plt.show()

rawDescription: MatPlotLib -- size of object

description: MatPlotLib -- size of object


code:
from django.core import serializers
from django.http import JsonResponse

def get_chat(request):
    usuario = request.GET.get('usuario_consultor', None)
    usuario_chat = request.GET.get('usuario_chat', None)

    mensajes = MensajeDirecto.objects.filter(Q(usuario_remitente = usuario, usuario_destinatario = usuario_chat) | Q(usuario_remitente = usuario_chat, usuario_destinatario = usuario))

    return JsonResponse(serializers.serialize('json', mensajes), safe=False)

rawDescription: Use JSONResponse to serialize a QuerySet in Django 1.7?


code:
import datetime
DATE = datetime.datetime.now().strftime('%Y-%m-%d')

rawDescription: Python join date and filename

description: Python join date and filename


code:
def translate(translation_map):
    #use raw input and split the sentence into a list of words
    input_list = raw_input('Enter a phrase: ').split()
    output_list = []

    #iterate the input words and append translation
    #(or word if no translation) to the output
    for word in input_list:
        translation = translation_map.get(word)
        output_list.append(translation if translation else word)

    #convert output list back to string
    return ' '.join(output_list)

rawDescription: Translating a phrase using a dictionary

description: Translating a phrase using a dictionary


code:
from progressBar import progressBar
from time import sleep
import sys

progress = progressBar(color='green',width=30)

for i in range(21):
    p=int(i/21.0)*100.
    message="Finished with %s percent"%(p)
    progress.render(p,message)
    sleep(0.25)

rawDescription: progress bar on linux

description: Progress bar on linux


code:
parent = None
md = gtk.MessageDialog(parent,
    gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_INFO,
    gtk.BUTTONS_CLOSE, "Download completed")
md.run()

rawDescription: How to show MessageBox with pygtk?

description: Show MessageBox with pygtk


code:
from collections import Counter

a = [1936, 2401, 2916, 4761, 9216, 9216, 9604, 9801]

c = Counter(a)

print(c.most_common(1)) # the one most common element... 2 would mean the 2 most common
[(9216, 2)] # a set containing the element, and it's count in 'a'

rawDescription: How to get the most common element from a list in python

description: Get the most common element from a list in python


code:
import theano
v = theano.tensor.scalar("variable")
factorial = theano.tensor.gamma(v)
# Calculate factorial of v , like numpy.math.factorial(v), but it didn't work,
# Actually it should be a integer as a parameter of numpy.math.factorial function
result = theano.function([v], factorial)

rawDescription: How to calculate factorial in Theano

description: Calculate factorial in Theano


rawDescription: How do I retrieve the output of a previous command and save it in a variable inside the Python interactive shell?

description: Retrieve the output of a previous command and save it in a variable inside the Python interactive shell


code:
import struct

f = open("filename","wb")
for i in range(25000):
    f.write(struct.pack('>I', i))
f.close()

rawDescription: How to write int array [0,1,2,...] in binary to a file using Python script

description: Write int array [0,1,2,...] in binary to a file using Python script


code:
words = ( 'one', 'two', 'three' )
whereClause=""

i = 1
for word in words:
    if i == 1:
        whereClause = " item LIKE '%" +word + "%'"
    else:
        whereClause += " OR item LIKE '%" +word + "%'"
    i += 1

sql= """select name
from table
where {0} """.format(whereClause)

cursor.execute(sql)
rows=cursor.fetchall()

rawDescription: Multiple words in Where field LIKE

description: Multiple words in Where field LIKE