content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: Python - Linux - Connecting to MS SQL with Windows Credentials - FreeTDS+UnixODBC + pyodbc or pymssql There doesn't seem to be any great instructions for setting this up. Does anyone have any good instructions? I am a linux noob so be gentle. I did see another post that is similar, but no real answer. I have ...
Python - Linux - Connecting to MS SQL with Windows Credentials - FreeTDS+UnixODBC + pyodbc or pymssql
There doesn't seem to be any great instructions for setting this up. Does anyone have any good instructions? I am a linux noob so be gentle. I did see another post that is similar, but no real answer. I have a couple of problems. FreeTDS doesn't "seem" to be working. I am trying to connect and I get the followin...
[ "The following works if you configure the MS SQL server to allow remote TCP/IP connections and have an appropriate user to connect as.\nYou also need to be careful to set up the correct hostname for the db as reported by MS SQL.\nimport pymssql\nconnection = pymssql.connect(\n user = 'username', \n ...
[ 2, 1, 0 ]
[]
[]
[ "freetds", "pymssql", "pyodbc", "python", "unixodbc" ]
stackoverflow_0002899732_freetds_pymssql_pyodbc_python_unixodbc.txt
Q: How to initialize a series of lists with strings in python? How do I loop over a range of integers, concatenating a string, such as "array" with the iterate of the loop, and initialize a list with the resulting string? The following single line shows what I want to do, where I get a "can't assign to function call...
How to initialize a series of lists with strings in python?
How do I loop over a range of integers, concatenating a string, such as "array" with the iterate of the loop, and initialize a list with the resulting string? The following single line shows what I want to do, where I get a "can't assign to function call" error. for i in range(int(nmat)): eval('array'+str(i)) = [] ...
[ "You shouldn't do that.\nInstead of having numerous variables arrayi, use just one: array, of type list. For example, if every element of the list should be an empty list:\narray = [[] for i in range(int(nmat))]\n\nYou can then access the first element with array[0], the second with array[1], and the number of elem...
[ 5, 4 ]
[]
[]
[ "python" ]
stackoverflow_0006378596_python.txt
Q: How to get numer of objects/elements (Foreign Key) in template how to get number of answers for question class Answers(models.Model): ... question = models.ForeignKey(Question, related_name='Question') when I return render_to_response('profile.xhtml', {'questions': Question.objects.f...
How to get numer of objects/elements (Foreign Key) in template
how to get number of answers for question class Answers(models.Model): ... question = models.ForeignKey(Question, related_name='Question') when I return render_to_response('profile.xhtml', {'questions': Question.objects.filter(author=details_profile),}, context_insta...
[ "If you hadn't set related_name='Question', you'd be able to get the count in the template like this:\n{{ q.answer_set.count }}\n\n...because \"answer_set\" is the default related_name. As is, you should be able to use:\n{{ q.Question.count }}\n\nBut that's ugly! Hopefully you've figured out by now that the related...
[ 1, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0006378115_django_django_models_python.txt
Q: How to convert a string list into an integer in python In my python Script I have: user = nuke.getInput("Frames Turned On") userLst = [user] print userLst Result: ['12,33,223'] I was wondering How I would remove the ' in the list, or somehow convert it into int? A: Use split() to split at the commas, use int(...
How to convert a string list into an integer in python
In my python Script I have: user = nuke.getInput("Frames Turned On") userLst = [user] print userLst Result: ['12,33,223'] I was wondering How I would remove the ' in the list, or somehow convert it into int?
[ "Use split() to split at the commas, use int() to convert to integer:\nuser_lst = map(int, user.split(\",\"))\n\n", "There's no ' to remove in the list. When you print a list, since it has no direct string representation, Python shows you its repr—a string that shows its structure. You have a list with one item...
[ 20, 9, 1, 1 ]
[ ">>> result = ['12,33,223']\n>>> int(result[0].replace(\",\", \"\"))\n1233233\n>>> [int(i) for i in result[0].split(',')]\n[12, 33, 233]\n\n", "You could use the join method and convert that to an integer:\nint(''.join(userLst)) \n\n\n1233223\n\n" ]
[ -1, -2 ]
[ "int", "list", "python", "string" ]
stackoverflow_0006378889_int_list_python_string.txt
Q: How to sort a structured list of stock data for later access in Python? I am very new to Python and want to build a black box stock trading program that finds various correlations between stock's rates of return and gives me a response such as buy, sell, hold, etc. I found a neat little easy to use Python module f...
How to sort a structured list of stock data for later access in Python?
I am very new to Python and want to build a black box stock trading program that finds various correlations between stock's rates of return and gives me a response such as buy, sell, hold, etc. I found a neat little easy to use Python module for retrieving stock data called ystockquote that pulls information from Yahoo...
[ "You might be looking for a dictionary structure rather than a list:\n>>> prices = dict()\n>>> prices['2011-01-02'] = {'Open':20.00, 'High':30.00, 'Low':10.00, 'Close':21.00, 'Volume':14.00, 'Adj Clos':120}\n>>> prices['2010-11-09'] = {'Open':22.00, 'High':50.00, 'Low':20.00, 'Close':42.00, 'Volume':10.00, 'Adj Clo...
[ 5, 1 ]
[]
[]
[ "dictionary", "list", "python", "stocks", "yahoo_api" ]
stackoverflow_0006378945_dictionary_list_python_stocks_yahoo_api.txt
Q: Does twisted.web.http.HTTPClient implement a callback when ALL response content is received? Documentation states that 'handleResponseEnd' is called when the response has been completely received. http://twistedmatrix.com/documents/11.0.0/api/twisted.web.http.HTTPClient.html#handleResponseEnd However, debugging a...
Does twisted.web.http.HTTPClient implement a callback when ALL response content is received?
Documentation states that 'handleResponseEnd' is called when the response has been completely received. http://twistedmatrix.com/documents/11.0.0/api/twisted.web.http.HTTPClient.html#handleResponseEnd However, debugging appears to show that is not always true. When making multiple requests to the same URI, it appears ...
[ "Usually you'd instantiate a new HTTPClient for each request by calling buildProtocol() on your factory. This is what HTTPPageGetter and Agent do.\nOne exception to this is when using HTTP persistent connections.\nWhat are you doing such that you need to use the same protocol instance for multiple requests?\n", "...
[ 0, 0 ]
[]
[]
[ "httpclient", "python", "twisted", "twisted.web" ]
stackoverflow_0006351507_httpclient_python_twisted_twisted.web.txt
Q: Django Query Filter The following line in my view selects all records that have a delay of 0 t = Times.objects.filter(delay = 0) How do i write it such that it selects everything but with delay 0? A: Can you try doing? t = Times.objects.exclude(delay=0) I think that will work for you. Hope that helps, Joe A: ...
Django Query Filter
The following line in my view selects all records that have a delay of 0 t = Times.objects.filter(delay = 0) How do i write it such that it selects everything but with delay 0?
[ "Can you try doing?\nt = Times.objects.exclude(delay=0)\n\nI think that will work for you.\nHope that helps,\nJoe\n", "With exclude() instead.\n", "Use the exclude() method instead of the filter() method\nhttps://docs.djangoproject.com/en/1.3/topics/db/queries/#retrieving-specific-objects-with-filters\n", "It...
[ 3, 2, 2, 0 ]
[]
[]
[ "django", "django_views", "python" ]
stackoverflow_0006379659_django_django_views_python.txt
Q: How do you render the front page of a plone site in python? The following browser view should return the content of the front page of the first Plone Site in it's context. However, I can not seem to obtain an object which is able to render html content. from Products.Five import BrowserView from zope.component imp...
How do you render the front page of a plone site in python?
The following browser view should return the content of the front page of the first Plone Site in it's context. However, I can not seem to obtain an object which is able to render html content. from Products.Five import BrowserView from zope.component import getMultiAdapter class RenderFirst (BrowserView): def __c...
[ "When I try this in a pdb a simple plones[0]() works fine.\n", "Take a look at http://pypi.python.org/pypi/plone.subrequest.\n" ]
[ 3, 1 ]
[]
[]
[ "plone", "python", "zope" ]
stackoverflow_0006368452_plone_python_zope.txt
Q: Python Subprocess adds extra quotes to my shell arguments Expected Behavior Under normal circumstances, I can issue tshark -E separator='@' under linuxSee Note A and force it to display fields separated by @, as shown below... [mpenning@hotcoffee ~]$ tshark -r scp_test.pcap -e frame.number -e ip.src_host -e tcp.sr...
Python Subprocess adds extra quotes to my shell arguments
Expected Behavior Under normal circumstances, I can issue tshark -E separator='@' under linuxSee Note A and force it to display fields separated by @, as shown below... [mpenning@hotcoffee ~]$ tshark -r scp_test.pcap -e frame.number -e ip.src_host -e tcp.srcport -E separator='@' -T fields tcp | less 1@192.168.12.236@33...
[ "tshark is taking the ' from '%s'. don't use the single-quotes:\ncmd = r\"tshark -r %s -e frame.number -e ip.src_host -e tcp.srcport -E separator=%s -T fields tcp\" % (filename, sep)\n\nwhen you ran it from the command line, Bash stripped the single-quotes off and tshark didn't see them.\n" ]
[ 6 ]
[]
[]
[ "linux", "python", "subprocess", "tcp", "wireshark" ]
stackoverflow_0006379794_linux_python_subprocess_tcp_wireshark.txt
Q: Python & Redis: Manager/Worker application best practices I have a few general questions about using Python and Redis to create a job queue application for running asynchronous commands. Here is the code I have generated so far: def queueCmd(cmd): r_server.rpush("cmds", cmd) def printCmdQueue(): print r_s...
Python & Redis: Manager/Worker application best practices
I have a few general questions about using Python and Redis to create a job queue application for running asynchronous commands. Here is the code I have generated so far: def queueCmd(cmd): r_server.rpush("cmds", cmd) def printCmdQueue(): print r_server.lrange("cmds", 0 , -1) def work(): print "command be...
[ "Your problem is that you are trying to run multiple commands concurrently with a single redis connection. \nYou are expecting something like\nThread 1 Thread 2\nLLEN test \n1 \nLPOP test \ncommand \n LLEN test\n 0\n\nbut you are getting \nThread 1 ...
[ 2 ]
[]
[]
[ "multiprocessing", "pool", "python", "redis" ]
stackoverflow_0006378628_multiprocessing_pool_python_redis.txt
Q: Problem installing neo4j.py I have followed the instructions here and for some reason I am getting the following traceback: root@ubuntu:~/Downloads/neo4j-python# python setup.py install Traceback (most recent call last): File "setup.py", line 146, in <module> main() File "setup.py", line 134, in main ...
Problem installing neo4j.py
I have followed the instructions here and for some reason I am getting the following traceback: root@ubuntu:~/Downloads/neo4j-python# python setup.py install Traceback (most recent call last): File "setup.py", line 146, in <module> main() File "setup.py", line 134, in main args[attr] = pom[attr] File "...
[ "Found the answer on serverfualt.\nSee the issue here.\n" ]
[ 0 ]
[]
[]
[ "neo4j", "neo4j.py", "python", "python_install" ]
stackoverflow_0006380187_neo4j_neo4j.py_python_python_install.txt
Q: Objects vs instance in python In C++ there are just objects and classes, where objects are instances of classes. In Python, a class definition (i.e., the body of a class) is called an object. And, the object in C++ is called instance in python. Check this Am I wrong? EDIT : Actually can someone explain with exam...
Objects vs instance in python
In C++ there are just objects and classes, where objects are instances of classes. In Python, a class definition (i.e., the body of a class) is called an object. And, the object in C++ is called instance in python. Check this Am I wrong? EDIT : Actually can someone explain with example difference of object vs instanc...
[ "\nIn Python, a class definition (i.e., the body of a class) is called an object\n\nActually, this is still called a class in Python. That's why you define it like this:\nclass Foo(object):\n pass\n\nThe class keyword is used because the result is still called a class.\nThe word object is in parentheses to show...
[ 27, 8, 5, 4, 2 ]
[]
[]
[ "c++", "object", "python" ]
stackoverflow_0006368432_c++_object_python.txt
Q: Serialize long number in python What would be the best way to serialize a long number in python ? I'm thinking pickle, but it`s still returning the "shortened" version. I'd obviously to write all the digits .. longNum = math.pow(2,1000) f = open("file", "w") pickle.dump(str(longNum), f) f.close() f = open("file"...
Serialize long number in python
What would be the best way to serialize a long number in python ? I'm thinking pickle, but it`s still returning the "shortened" version. I'd obviously to write all the digits .. longNum = math.pow(2,1000) f = open("file", "w") pickle.dump(str(longNum), f) f.close() f = open("file","r") longNum = pickle.load(f) f.clo...
[ "You can quickly see the problem if you fire up the interpreter.\n>>> math.pow(2,1000)\n1.0715086071862673e+301\n\n>>> 2**1000\n10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062...
[ 7, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006380526_python.txt
Q: how to acurately measure the bitrate flowing through a named pipe? if i have proc1 | proc2 is there a way to accurately measure the bitrate flowing through the pipe , without altering the behaviour as if the measuring device were not there? would something like tee work ok? would i want proc1 | tee proc2 > flow_m...
how to acurately measure the bitrate flowing through a named pipe?
if i have proc1 | proc2 is there a way to accurately measure the bitrate flowing through the pipe , without altering the behaviour as if the measuring device were not there? would something like tee work ok? would i want proc1 | tee proc2 > flow_measurement_thing or proc1 | tee flow_measurement_thing > proc2? if i u...
[ "As Corey Goldberg said, you should use pv. It's a very nice tool and available on most *nix systems. You could do these things:\ncapture | pv > /dev/null\ncapture | convert | pv > /dev/null\n\npv will tell you the throughput for each case.\nOr, if the output of capture is deterministic, just use a timer.\n" ]
[ 2 ]
[]
[]
[ "fifo", "named_pipes", "pipe", "python", "subprocess" ]
stackoverflow_0006380418_fifo_named_pipes_pipe_python_subprocess.txt
Q: Visual model of coordinated system in Python I have some output which reads like: (x0, y0, z0) : (x1, y1, z1) The data represents spacial transformations. I would very much appreciate any sort of method which will visually map that data to an image or animation. The idea is to help myself better understand Rieman...
Visual model of coordinated system in Python
I have some output which reads like: (x0, y0, z0) : (x1, y1, z1) The data represents spacial transformations. I would very much appreciate any sort of method which will visually map that data to an image or animation. The idea is to help myself better understand Riemann space. Ultimately I would like to show a compari...
[ "If you're looking to visualize Riemann zeta functions in 3d space, and you specifically want to do it in python, you should look at this blog post: http://pyevolve.sourceforge.net/wordpress/?p=1079\nIt uses mpmath for the math and matplotlib for visualization. It contains some sample youtube videos, and source co...
[ 2, 0 ]
[]
[]
[ "imaging", "python", "python_imaging_library" ]
stackoverflow_0006379319_imaging_python_python_imaging_library.txt
Q: Python Not Web Linking Entire variable in str.ljust I have Python code that pulls info from a sqlite database and then write to a html file. I'm trying to write as preformatted text and the code below places the text in columns like I am try to accomplish, but (obviously) the link is the entire length of the strin...
Python Not Web Linking Entire variable in str.ljust
I have Python code that pulls info from a sqlite database and then write to a html file. I'm trying to write as preformatted text and the code below places the text in columns like I am try to accomplish, but (obviously) the link is the entire length of the string, including the whitespace to the right from the .ljust....
[ "Edit\ntitle = str(item.title)\nspaces = ' '*(25-len(title)) if len(title) <= 25 else ''\n'<a href=\"/%s/\">%s</a>%s %s' % (item.slug, title, spaces, item.date.ljust(10))\n\n", "If you must do it on one line, the following should work for you:\ncontent += '<a href=\"/%s/\">%s</a> %s %s' % tuple(itertools.chain(...
[ 1, 0 ]
[]
[]
[ "python", "text" ]
stackoverflow_0006380405_python_text.txt
Q: Python get ID from XML data I am a total python newb and am trying to parse an XML document that is being returned from google as a result of a post request. The document returned looks like the one outlined in this doc http://code.google.com/apis/documents/docs/3.0/developers_guide_protocol.html#Archives where it...
Python get ID from XML data
I am a total python newb and am trying to parse an XML document that is being returned from google as a result of a post request. The document returned looks like the one outlined in this doc http://code.google.com/apis/documents/docs/3.0/developers_guide_protocol.html#Archives where it says 'The response contains info...
[ "I would highly recommend the Python package BeautifulSoup. It is awesome. Here is a simple example using their example data (assuming you've installed BeautifulSoup already):\nfrom BeautifulSoup import BeautifulSoup\n\ndata = \"\"\"<?xml version='1.0' encoding='utf-8'?>\n<entry xmlns='http://www.w3.org/2005/Atom...
[ 2, 1, 0 ]
[]
[]
[ "parsing", "python", "xml" ]
stackoverflow_0006380764_parsing_python_xml.txt
Q: finding the shortest graph within parameters def shortestPath(digraph, start, end, maxTotalDist, maxDistOutdoors, visited=[]): if not (digraph.hasNode(start) and digraph.hasNode(end)): raise ValueError('Start or end not in graph.') path = [str(start)] if start == end: return path sh...
finding the shortest graph within parameters
def shortestPath(digraph, start, end, maxTotalDist, maxDistOutdoors, visited=[]): if not (digraph.hasNode(start) and digraph.hasNode(end)): raise ValueError('Start or end not in graph.') path = [str(start)] if start == end: return path shortest = None MinimumTotalDist = 0 for nod...
[ "Your code doesn't return the shortest path possible because the algorithm you're using (DFS) does not return the shortest path. Instead, try a BFS!\nHowever, since you have some weight constraints (distance outdoors), you should check out Dijkstra's shortest path algorithm. You should find it pretty easy to integr...
[ 1 ]
[]
[]
[ "graph_algorithm", "python" ]
stackoverflow_0005918342_graph_algorithm_python.txt
Q: how to parameter-ize a query's WHERE clause within pl/python? Friends: Have been trying to parameter-ize into a query in pl/python - and am surely missing something simple here; I've tried % and $ prepends to the variable name, with no luck. (also haven't been able to pass a result variable into the python log - ...
how to parameter-ize a query's WHERE clause within pl/python?
Friends: Have been trying to parameter-ize into a query in pl/python - and am surely missing something simple here; I've tried % and $ prepends to the variable name, with no luck. (also haven't been able to pass a result variable into the python log - but this is a diff problem! I do have the log set up - can sent lit...
[ "Use the $n notation:\nst = \"SELECT name_key,address_key FROM file WHERE foreign_key = $1\"\npst = plpy.prepare(st, [ \"integer\" ])\nrv = plpy.execute(pst, [ param_key ])\n\n", "I'm not sure exactly what you're asking but if you're trying to parametrize the columns you're using to control a join on a query, par...
[ 3, 2 ]
[]
[]
[ "plpython", "python" ]
stackoverflow_0006381043_plpython_python.txt
Q: import issue with python/django I'm trying to use the calendar module in my Django views.py file. If I make the import at the top of the file, with the rest of my package imports, and call the monthrange function on the module, I get the following: 'function' has no attribute 'monthrange' If however I import the...
import issue with python/django
I'm trying to use the calendar module in my Django views.py file. If I make the import at the top of the file, with the rest of my package imports, and call the monthrange function on the module, I get the following: 'function' has no attribute 'monthrange' If however I import the module in my function, where I make ...
[ "Seems like namespace clash - maybe 'calendar' got redefined some place as a variable or function name.\nTry to import monthrange from calendar at the top of the module, 'monthrange' is much less likely to clash with a variable or function elsewhere the code.\nfrom calendar import monthrange\n\n" ]
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006381225_django_python.txt
Q: Doing QuickSort for fun, but there is something I do not understand Just want to ensure you that it is not a homework question. I am doing it just for some fun and probably to blog about. I am implementation the 'in-place' version of Quick Sort in accordance to this wiki page. Here is the code I have written: # so...
Doing QuickSort for fun, but there is something I do not understand
Just want to ensure you that it is not a homework question. I am doing it just for some fun and probably to blog about. I am implementation the 'in-place' version of Quick Sort in accordance to this wiki page. Here is the code I have written: # solution 2 def swap(arr, left, right): try: tmp = arr[left] ...
[ "you have midpoint = (right - left) / 2. I think you mean (right + left) / 2, otherwise your midpoint is outside of the given bounds.\n", "\nSelecting a pivot element is also complicated by the existence of integer overflow. If the boundary indices of the subarray being sorted are sufficiently large, the naive e...
[ 2, 2 ]
[]
[]
[ "python", "quicksort" ]
stackoverflow_0006381211_python_quicksort.txt
Q: How to get the default value set by the xml schema? I've got an xml schema which specifies a default value for an optional field... <xs:element name="expiry" type="xs:positiveInteger" default="86400"/> I'm using lxml to parse the incoming xml... root = lxml.etree.XML(xml) When I go looking for the optional eleme...
How to get the default value set by the xml schema?
I've got an xml schema which specifies a default value for an optional field... <xs:element name="expiry" type="xs:positiveInteger" default="86400"/> I'm using lxml to parse the incoming xml... root = lxml.etree.XML(xml) When I go looking for the optional element, and it's not there, I get a 'None' result... expiry =...
[ "Can't be done by 'magic'. The long way is the only way (today).\nThat is: read the xmlschema like an xml document, find the element tag with the attribute \"expiry\", look for the value of the attribute \"default\" in that tag.\n", "First, you need to include you schema, using lxml.etree.XMLSchema\nI think it on...
[ 1, 0 ]
[]
[]
[ "lxml", "python" ]
stackoverflow_0006275134_lxml_python.txt
Q: Is it better to have standalone functions in globals or group them in a class? I have inherited code in which there are standalone functions, one per country code. E.g. def validate_fr(param): pass def validate_uk(param): pass My idea is to create a class to group them together and consolidate the code i...
Is it better to have standalone functions in globals or group them in a class?
I have inherited code in which there are standalone functions, one per country code. E.g. def validate_fr(param): pass def validate_uk(param): pass My idea is to create a class to group them together and consolidate the code into one method. Unfortunately that breaks cohesion. Another option is to dispatch to...
[ "I would keep the functions at module level -- no need for a class if you don't want to instantiate it anyway. The switch statement can easily be simulated using a dicitonary:\ndef validate_fr(param):\n pass\n\ndef validate_uk(param)\n pass\n\nvalidators = {\"fr\": validate_fr,\n \"uk\": validat...
[ 4, 3, 3, 2 ]
[]
[]
[ "class_design", "python" ]
stackoverflow_0006368755_class_design_python.txt
Q: two database connection with Mysqldb in python Can any body please let me know if more than one database connection at a time is possible with Mysqldb in python script. I have a scenario where i want to query from databaseA tables (which can be from more than one table using join operation ) and store the resultse...
two database connection with Mysqldb in python
Can any body please let me know if more than one database connection at a time is possible with Mysqldb in python script. I have a scenario where i want to query from databaseA tables (which can be from more than one table using join operation ) and store the resultset into another databaseB table named 'results'. Than...
[ "Open two connections and work with them as needed.\nWhere should be the problem?\n" ]
[ 0 ]
[]
[]
[ "connection", "database", "mysql_python", "python" ]
stackoverflow_0006381557_connection_database_mysql_python_python.txt
Q: Simple python inheritance class Animal(object): def __init__(self, nlegs=4): print '__init__ Animal' self.nlegs = nlegs class Cat(Animal): def __init__(self, talk='meow'): print '__init__ Cat' self.talk = talk class Dog(Animal): def __init__(self, talk='woof'): ...
Simple python inheritance
class Animal(object): def __init__(self, nlegs=4): print '__init__ Animal' self.nlegs = nlegs class Cat(Animal): def __init__(self, talk='meow'): print '__init__ Cat' self.talk = talk class Dog(Animal): def __init__(self, talk='woof'): print '__init__ Dog' s...
[ "To build on what everyone else has said, yes, you'll need to call the parent's __init__ method. \nIt's generally best to use super. However, in certain cases (particularly when you're inheriting from multiple classes) it can be a big gotcha. I'll avoid going into detail, there are no shortage of various articles...
[ 16, 4, 2 ]
[]
[]
[ "constructor", "inheritance", "python" ]
stackoverflow_0006381590_constructor_inheritance_python.txt
Q: Meta-properties with groovy? In python ( specifically CherryPy ) I can do something like class Root(Object): def index(): #some sort of logic here index.expose = True is there something similar for Groovy? Update CherryPy use's plain objects for it's equivalent of controllers, where the developer decorat...
Meta-properties with groovy?
In python ( specifically CherryPy ) I can do something like class Root(Object): def index(): #some sort of logic here index.expose = True is there something similar for Groovy? Update CherryPy use's plain objects for it's equivalent of controllers, where the developer decorates or marks each method that shoul...
[ "Doing some more research ( Google ), I ended up checking r/Groovy on reddit and was led to this very useful blog post \nFrom my perspectives, Java annotations can be used to decorate or markup methods with extended logic. So something like\n class Root {\n @Expose\n void index() {\n #som sort of logic ...
[ 0 ]
[]
[]
[ "groovy", "metaprogramming", "python" ]
stackoverflow_0006381469_groovy_metaprogramming_python.txt
Q: python get diff from files How to compare contents of two files saying if the content in file1 is present in file2 in some other format how can we detect it Ex:file1 import datetime,os #include<stdio.h> import java.io.*; import mymodule,urllib, #include<conio.h> File2: ...
python get diff from files
How to compare contents of two files saying if the content in file1 is present in file2 in some other format how can we detect it Ex:file1 import datetime,os #include<stdio.h> import java.io.*; import mymodule,urllib, #include<conio.h> File2: #include<stdio.h> ...
[ "You can have a look at difflib - http://docs.python.org/library/difflib.html\nSnippet:\ndifflib.SequenceMatcher(None, file1.read(), file2.read())\n\n", "This is nontrivial. I was going to whip up a little script just to match comments and imports, but even that requires a lot of \"smart\" regex parsing of data. ...
[ 4, 2 ]
[]
[]
[ "python" ]
stackoverflow_0006381614_python.txt
Q: import directory containing python src files as module I've a question on importing a python directory foo as a module. The structure is: -- foo --__init__.py --- file1.py --- file2.py __init__.py contains the following line: __all__ = ["file1", "file2"] What I would want to do is to import foo and t...
import directory containing python src files as module
I've a question on importing a python directory foo as a module. The structure is: -- foo --__init__.py --- file1.py --- file2.py __init__.py contains the following line: __all__ = ["file1", "file2"] What I would want to do is to import foo and then access file1 as foo.file1 However, I can only access f...
[ "That's exactly what the documentation says that __all__ does. If you want to be able to do foo.file1, instead of using __all__, do this in __init__.py:\nimport file1\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0006381732_python.txt
Q: Where to call logging.setLoggerClass() in Django I'm using Django 1.3 with the standard Python logging. I've configured it to log errors to a file: 'loggers': { 'django': { 'handlers': ['logfile'], 'level': 'ERROR', 'propagate': False, }, I also want the username of the currently l...
Where to call logging.setLoggerClass() in Django
I'm using Django 1.3 with the standard Python logging. I've configured it to log errors to a file: 'loggers': { 'django': { 'handlers': ['logfile'], 'level': 'ERROR', 'propagate': False, }, I also want the username of the currently logged in Django user to be logged. For that I've defin...
[ "Rather than use a custom logging class, you can use a Filter on your handlers to do this. See this post, and this part of the docs. \n", "Vinay Sajip's solution of using a filter avoids this problem entirely, so I'm accepting his answer. The documentation on how to configure a filter using a dictionary is a bit ...
[ 4, 3 ]
[]
[]
[ "django", "logging", "python" ]
stackoverflow_0006380139_django_logging_python.txt
Q: Web2Py - How to use SELECT query with WHERE.. IN keyword I have a table called User and in Web2Py I would to get Users that match certain ids say (1,5,11,16). Do I have to write SQL query itself or can it be elegantly done using Web2Py style queries. A: The belongs operator
Web2Py - How to use SELECT query with WHERE.. IN keyword
I have a table called User and in Web2Py I would to get Users that match certain ids say (1,5,11,16). Do I have to write SQL query itself or can it be elegantly done using Web2Py style queries.
[ "The belongs operator\n" ]
[ 5 ]
[]
[]
[ "python", "sql", "web2py" ]
stackoverflow_0006382038_python_sql_web2py.txt
Q: Is it possible to use collection of objects inside Django classes in python I am trying to implement the Finanace application with many classes (wrt java). I have this case class User { String name; Int age; Collection<Accounts> accounts; Interface Account Then following classes implements interface Saving Acc...
Is it possible to use collection of objects inside Django classes in python
I am trying to implement the Finanace application with many classes (wrt java). I have this case class User { String name; Int age; Collection<Accounts> accounts; Interface Account Then following classes implements interface Saving Account Fixed Account Insurance Account The account will have User Object As i a...
[ "You probably want to use django.contrib.auth, which already provides a User model, so you'll want to write a model to store additional user information, instead of defining a new User model. Django models (generally) represent database tables, each attribute represents a database field. You define your models and ...
[ 1 ]
[]
[]
[ "django", "oop", "python" ]
stackoverflow_0006382065_django_oop_python.txt
Q: Return value from imported module not working I have a python file (project_root/usermodule/user_controls.py) with only the following code: class UControl(): def login(self): return 'John' And I also have a class (project_root/main_file.py) that's importing user_controls (the file above) containing on...
Return value from imported module not working
I have a python file (project_root/usermodule/user_controls.py) with only the following code: class UControl(): def login(self): return 'John' And I also have a class (project_root/main_file.py) that's importing user_controls (the file above) containing only the following code. import os from usermodule im...
[ "Is it a typo in the question or in your program: login_reponse != login_response\nIf I correct this error, the script runs flawlessly on my machine. (You may want to use class UControl(object): instead of class UControl():).\nThe fact that the error is not printed out, suggests that your code isn't even run. How a...
[ 3, 1 ]
[]
[]
[ "import", "module", "python", "return_value" ]
stackoverflow_0006379477_import_module_python_return_value.txt
Q: Type-casting of session object in python, django I would like to ask something about tyoe casting in python, Django. I have a CompanyReview object in session request.session['review_company_review'] and I would like to get this object. I have written the code below but I consider there should be a better way. cr =...
Type-casting of session object in python, django
I would like to ask something about tyoe casting in python, Django. I have a CompanyReview object in session request.session['review_company_review'] and I would like to get this object. I have written the code below but I consider there should be a better way. cr = CompanyReview() cr = request.session['review_company_...
[ "You don't need any type-casting in Python.\nIf you have saved that object to session doing like request.session['review_company_review'] = some_company_review_object, to retrieve that object you can just do:\ncr = request.session['review_company_review']\n\n" ]
[ 4 ]
[]
[]
[ "casting", "django", "python" ]
stackoverflow_0006382231_casting_django_python.txt
Q: Python Regex to match a string as a pattern and return number I have some lines that represent some data in a text file. They are all of the following format: s = 'TheBears SUCCESS Number of wins : 14' They all begin with the name then whitespace and the text 'SUCCESS Number of wins : ' and finally the numbe...
Python Regex to match a string as a pattern and return number
I have some lines that represent some data in a text file. They are all of the following format: s = 'TheBears SUCCESS Number of wins : 14' They all begin with the name then whitespace and the text 'SUCCESS Number of wins : ' and finally the number of wins, n1. There are multiple strings each with a different nam...
[ "Try this one out:\n((\\S+)\\s+SUCCESS Number of wins : (\\d+))\n\nThese are the results:\n>>> regex = re.compile(\"((\\S+)\\s+SUCCESS Number of wins : (\\d+))\")\n>>> r = regex.search(string)\n>>> r\n<_sre.SRE_Match object at 0xc827cf478a56b350>\n>>> regex.match(string)\n<_sre.SRE_Match object at 0xc827cf478a56b22...
[ 3, 2, 1 ]
[]
[]
[ "match", "python", "regex", "substring" ]
stackoverflow_0006377707_match_python_regex_substring.txt
Q: Slicing in mongoengine I have a Thread document which has within it Comments, which are EmbeddedDocuments. I don't want to have all of the comments return at once, but instead display them ten at a time. In PyMongo or with just MongoDB I know I could use the $slice operator, but I'm not sure of how to do this with...
Slicing in mongoengine
I have a Thread document which has within it Comments, which are EmbeddedDocuments. I don't want to have all of the comments return at once, but instead display them ten at a time. In PyMongo or with just MongoDB I know I could use the $slice operator, but I'm not sure of how to do this with mongoengine. If I do Thread...
[ "Support has been added in the dev branch and will make the next release!\nYou can return only 10 comments by using the fields and slice method:\nthread = Thread.objects.fields(slice__comments=10).get(id=thread_id)\n\n" ]
[ 2 ]
[]
[]
[ "mongodb", "mongoengine", "nosql", "python" ]
stackoverflow_0005818669_mongodb_mongoengine_nosql_python.txt
Q: Python: "import posix" question If I import os module, I can run the following to infer the location of os.py >>> import os >>> print os.__file__ /usr/lib/python2.6/os.pyc However, when I import posix, it does not have the __file__ attribute. Is it because it is implemented as a part of the python runtime, not as...
Python: "import posix" question
If I import os module, I can run the following to infer the location of os.py >>> import os >>> print os.__file__ /usr/lib/python2.6/os.pyc However, when I import posix, it does not have the __file__ attribute. Is it because it is implemented as a part of the python runtime, not as a standard library? How can I find o...
[ "It's a C module. It can be either built into the Python binary or compiled as a shared library. In your case it is compiled in\nThe official docs say not to import it directly, and you should use the functionality provided via os\n", "Run python interactively.\n>>> import posix\n>>> help(posix)\n\nThere's a lot ...
[ 7, 3, 1 ]
[]
[]
[ "posix", "python" ]
stackoverflow_0006382266_posix_python.txt
Q: what's wrong with my python re.sub this is my code : string =''' {% emoji 'MONEY_BAG' %}<span style="color:#7F6C41;"><a href="{% mobile_url '/inventory/view_item/?category=weapon&inventory_id=%s' inventory_id %}">{{ item.name }}</a>を入手した!</span></span> ''' a = r''' {%\s+mobile_url\s+['"]{1}(/inventory/view_item/...
what's wrong with my python re.sub
this is my code : string =''' {% emoji 'MONEY_BAG' %}<span style="color:#7F6C41;"><a href="{% mobile_url '/inventory/view_item/?category=weapon&inventory_id=%s' inventory_id %}">{{ item.name }}</a>を入手した!</span></span> ''' a = r''' {%\s+mobile_url\s+['"]{1}(/inventory/view_item/\?)[^'"]*['"]{1}\s+([^%}]+)\s+%} ''' de...
[ "It's a bad idea to use regex to extract information from HTML. It's much easier with a HMTL Parser: http://docs.python.org/library/htmlparser.html\nOr if you want to crawl a webpage for more information, you might want to use scrapy which is a truly great web crawler framework.\n", "Your extra newline characters...
[ 3, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0006382430_python_regex.txt
Q: Subquerying in MongoEngine Having the sample code: import mongoengine as mongo class User(mongo.Document): name = mongo.StringField() age = mongo.IntField() class Post(mongo.Document): title = mongo.StringField() author = mongo.ReferenceField(User) I want to get all the posts created by user...
Subquerying in MongoEngine
Having the sample code: import mongoengine as mongo class User(mongo.Document): name = mongo.StringField() age = mongo.IntField() class Post(mongo.Document): title = mongo.StringField() author = mongo.ReferenceField(User) I want to get all the posts created by users with ages below 30, one way is...
[ "\nWhat am I doing wrong?\n\nNothing you can't query across reference fields - see Embed Vs Reference\nSo even if the syntax was supported it would take two queries behind the scenes. If its something thats wanted - add a ticket to github and I'll look into adding it :)\nUpdates to MongoEngine are coming in thick ...
[ 3, 1 ]
[]
[]
[ "mongodb", "mongoengine", "nosql", "python" ]
stackoverflow_0004975760_mongodb_mongoengine_nosql_python.txt
Q: how to simply handle the request with python I'm trying to do some testing in html5 uploading files,here is the simple html codes: var fileInput=document.getElementById("the-file") fileInput.addEventListener('change',function(e){ var file=e.target.files[0] var xhr=new XMLHttpRequest() xhr.open('post','upload/...
how to simply handle the request with python
I'm trying to do some testing in html5 uploading files,here is the simple html codes: var fileInput=document.getElementById("the-file") fileInput.addEventListener('change',function(e){ var file=e.target.files[0] var xhr=new XMLHttpRequest() xhr.open('post','upload/handlecode',true) xhr.send(file) } I use python...
[ "Use bottle:\nfrom bottle import request, route, run\n\n@route('/upload', method='POST')\ndef do_upload():\n data = request.files.get('data')\n raw = data.file.read()\n filename = data.filename\n return \"You uploaded %s (%d bytes).\" % (filename, len(raw))\n\nrun(host='localhost', port=8080)\n\n" ]
[ 5 ]
[]
[]
[ "html", "httprequest", "httpresponse", "python", "testing" ]
stackoverflow_0006380564_html_httprequest_httpresponse_python_testing.txt
Q: executemany of CLOB elements on cx_Oracle I have a function that inserts a chunk of data into oracle database. I'm trying to achieve this by using executemany. My function looks like this: def InsertChunk(self): try: if len(self.list_dict_values) >= self.chunksize: self.db.cursor.executemany( ...
executemany of CLOB elements on cx_Oracle
I have a function that inserts a chunk of data into oracle database. I'm trying to achieve this by using executemany. My function looks like this: def InsertChunk(self): try: if len(self.list_dict_values) >= self.chunksize: self.db.cursor.executemany( str(self.insert_sql), self.l...
[ "I had the same problem. In my case it was caused by using the cx_Oracle variable types incorrectly. When filling out my equivalent of list_dict_values I was doing something like this:\nfor row in list_dict_values:\n for key, val in row.iteritems():\n v = cursor.var(cx_Oracle.CLOB)\n v.setvalue(0, val)\n...
[ 3 ]
[]
[]
[ "cx_oracle", "executemany", "python" ]
stackoverflow_0006131306_cx_oracle_executemany_python.txt
Q: How to use getopt/OPTARG in Python? How to shift arguments if too many arguments (9) are given? How to use getopt/optarg in Python? A: This is an example of how I do it, I usually use the same basic template: import sys import getopt try: opts, args = getopt.getopt(sys.argv[1:], 'm:p:h', ['miner=', 'params=...
How to use getopt/OPTARG in Python? How to shift arguments if too many arguments (9) are given?
How to use getopt/optarg in Python?
[ "This is an example of how I do it, I usually use the same basic template:\nimport sys\nimport getopt\n\ntry:\n opts, args = getopt.getopt(sys.argv[1:], 'm:p:h', ['miner=', 'params=', 'help'])\nexcept getopt.GetoptError:\n usage()\n sys.exit(2)\n\nfor opt, arg in opts:\n if opt in ('-h', '--help'):\n ...
[ 51, 13, 4 ]
[]
[]
[ "arguments", "command_line_interface", "getopt", "python" ]
stackoverflow_0006382804_arguments_command_line_interface_getopt_python.txt
Q: Add two matrices in python I'm trying to write a function that adds two matrices to pass the following doctests: >>> a = [[1, 2], [3, 4]] >>> b = [[2, 2], [2, 2]] >>> add_matrices(a, b) [[3, 4], [5, 6]] >>> c = [[8, 2], [3, 4], [5, 7]] >>> d = [[3, 2], [9, 2], [10, 12]] >>> add_matrices(c, d) [[11,...
Add two matrices in python
I'm trying to write a function that adds two matrices to pass the following doctests: >>> a = [[1, 2], [3, 4]] >>> b = [[2, 2], [2, 2]] >>> add_matrices(a, b) [[3, 4], [5, 6]] >>> c = [[8, 2], [3, 4], [5, 7]] >>> d = [[3, 2], [9, 2], [10, 12]] >>> add_matrices(c, d) [[11, 4], [12, 6], [15, 19]] So I wr...
[ "Matrix library\nYou can use the numpy module, which has support for this.\n>>> import numpy as np\n\n>>> a = np.matrix([[1, 2], [3, 4]])\n>>> b = np.matrix([[2, 2], [2, 2]])\n\n>>> a+b\nmatrix([[3, 4],\n [5, 6]])\n\n\nHome-grown solution: heavyweight\nAssuming you wanted to implement it yourself, you'd set ...
[ 23, 7, 4, 3 ]
[]
[]
[ "nested_lists", "python" ]
stackoverflow_0006382705_nested_lists_python.txt
Q: Mapping LDAP users to Django users with Django Auth Ldap I'm using Django 1.3 and Django Auth Ldap 1.0.6. and I'm trying to have the users who have a special status on the LDAP Server (admins) have the same status in my Django application. These are my current settings: AUTH_LDAP_SERVER_URI = 'ldap://path.to.serve...
Mapping LDAP users to Django users with Django Auth Ldap
I'm using Django 1.3 and Django Auth Ldap 1.0.6. and I'm trying to have the users who have a special status on the LDAP Server (admins) have the same status in my Django application. These are my current settings: AUTH_LDAP_SERVER_URI = 'ldap://path.to.server' AUTH_LDAP_BIND_DN = '' AUTH_LDAP_BIND_PASSWORD = '' AUTH_L...
[ "If you set AUTH_LDAP_GROUP_SEARCH, you also need to set AUTH_LDAP_GROUP_TYPE. Since you're apparently using groupOfNames for grouping, you need AUTH_LDAP_GROUP_TYPE = GroupOfNamesType().\nEverything else looks okay, although it's unlikely that you need both AUTH_LDAP_MIRROR_GROUPS and AUTH_LDAP_FIND_GROUPS_PERMS. ...
[ 3, 1 ]
[]
[]
[ "authentication", "django", "ldap", "python" ]
stackoverflow_0006356705_authentication_django_ldap_python.txt
Q: Looking for a wxpython widget that would let user's fill in data like they would in a table I want to have a table like display on one of panels where the user can fill in data into pre-made columns. I'm not sure what widget will give me this functionality. I want users to be able to edit elements they have alre...
Looking for a wxpython widget that would let user's fill in data like they would in a table
I want to have a table like display on one of panels where the user can fill in data into pre-made columns. I'm not sure what widget will give me this functionality. I want users to be able to edit elements they have already added, and to easily add another element. Any suggestions?
[ "Look at Grid or ListCtrl to create the columns. I think Grid is a better choice for editing as you can add TextCtrls or the like to the columns.\n", "Try out CSheet, it is much better and customizable than the standard wxGrid and has similar interface.\n", "Try ListCtrl with TextEditMixin - it's pretty neat a...
[ 3, 1, 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0006362228_python_wxpython.txt
Q: Python SMTP server that can receive MIME attachment I want to implement a simple email server just like amazon kindle mail server does for ebook convert. User mail me doc as attachment. Mail server will retrieve and store those doc. Maybe response back to sender about the convert result, simply success or failure....
Python SMTP server that can receive MIME attachment
I want to implement a simple email server just like amazon kindle mail server does for ebook convert. User mail me doc as attachment. Mail server will retrieve and store those doc. Maybe response back to sender about the convert result, simply success or failure. I want to implement this in Python. Looking into the bu...
[ "\"it only be able to handle RFC2822 formatted message body. \" - thats enough for what you are trying to achieve. MIME attachments are covered in RFC 2822 extensions. the python email library contains various functions to walk through the message payload and extract attachments\n", "You could checkout Lamson, wh...
[ 1, 1 ]
[]
[]
[ "mime", "python", "smtp" ]
stackoverflow_0006381704_mime_python_smtp.txt
Q: Loops not working - Strings (Python) I need help in reading these textfiles, somehow when i do a recursive loop, the other loop always gets reset to the 1st line. import sys import codecs # there are actually more utf-8 char to the lines, so i needed codecs reload(sys) sys.setdefaultencoding('utf-8') reader = cod...
Loops not working - Strings (Python)
I need help in reading these textfiles, somehow when i do a recursive loop, the other loop always gets reset to the 1st line. import sys import codecs # there are actually more utf-8 char to the lines, so i needed codecs reload(sys) sys.setdefaultencoding('utf-8') reader = codecs.open("txtfile1", 'r', 'utf-8') reader2...
[ "Can't tell you why but this can be fixed by simply replacing for row in reader: with for row in reader.readlines():. If everything can't be imported at once, then you'll probably need to handle iteration manually.\nEDIT\nI just realized I did something slightly different in getting this to work:\nouter = codecs.op...
[ 1, 1, 1 ]
[]
[]
[ "for_loop", "loops", "python", "text_files" ]
stackoverflow_0006383284_for_loop_loops_python_text_files.txt
Q: Add 2 hours and 1 day onto a timestamp in django i have a model which holds data for a game, how would i add 2 hours and 1 day onto the 'starts' field? class Game(models.Model): starts = models.DateTimeField(auto_now_add=True) ends = models.DateTimeField() does anyone have a solution for this? A: from d...
Add 2 hours and 1 day onto a timestamp in django
i have a model which holds data for a game, how would i add 2 hours and 1 day onto the 'starts' field? class Game(models.Model): starts = models.DateTimeField(auto_now_add=True) ends = models.DateTimeField() does anyone have a solution for this?
[ "from datetime import timedelta\nobj.starts += timedelta(days=1, hours=2)\n\n" ]
[ 21 ]
[]
[]
[ "django", "python", "time", "timestamp" ]
stackoverflow_0006383900_django_python_time_timestamp.txt
Q: How do I temporarily disable AppStats in my Google App Engine application? I recently configured my app to use the new AppStats feature of GAE. However, while debugging it, the extremely verbose logging from AppStats is annoying & I'd like to disable it while I'm debugging and then turn it back on later. Surely th...
How do I temporarily disable AppStats in my Google App Engine application?
I recently configured my app to use the new AppStats feature of GAE. However, while debugging it, the extremely verbose logging from AppStats is annoying & I'd like to disable it while I'm debugging and then turn it back on later. Surely there is a single line I can add to or modify in a config file that will let me do...
[ "See the configuring appstats docs: configuration is performed by creating your own appengine_config.py in your app's root directory. Best documentation of what you can do in that config file is the sample one supplied with your SDK, which you can also look at here. To disable stats, if you're using Django, just ...
[ 4, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002347567_google_app_engine_python.txt
Q: Python - make class decorator work on derived classes In the app we're developing using Django, in some cases we need to automatically assign permissions to users for some models, that has owners (there is no rule for field's name, it can be "user", "owner", "coach" etc., also there can by more than one field.) My...
Python - make class decorator work on derived classes
In the app we're developing using Django, in some cases we need to automatically assign permissions to users for some models, that has owners (there is no rule for field's name, it can be "user", "owner", "coach" etc., also there can by more than one field.) My solution is to create a decorator containing those fields ...
[ "You need to set the list of owners, not update:\nclass auto_assign_perms(object):\n def __init__(self, *users):\n self.users = users\n\n def __call__(self, cls):\n cls.owners = set(self.users) # <- here\n return cls\n\n#some tests\n@auto_assign_perms('owner', 'user')\nclass Test(Base):\n...
[ 4, 1, 0 ]
[]
[]
[ "decorator", "oop", "python" ]
stackoverflow_0006383613_decorator_oop_python.txt
Q: Sockets & Inter communication Among Threads I am using Multithreaded TCP Server. Each socket is created as a separate thread for each client. I would like send data to all clients via send() method of socket. Problem I am facing here is, it sends data to current thread (from which it received) only. I could not f...
Sockets & Inter communication Among Threads
I am using Multithreaded TCP Server. Each socket is created as a separate thread for each client. I would like send data to all clients via send() method of socket. Problem I am facing here is, it sends data to current thread (from which it received) only. I could not find good documentation for inter thread communica...
[ "You could make your threads objects (if any) iterable and you make a \"broadcast\" function that just iterate through your threads and use their sockets to send the information.\nOr if you don't have an object per threads you can always just have a list of sockets and do pretty much the same thing.\nMake sure that...
[ 1, 0 ]
[]
[]
[ "multithreading", "networking", "python" ]
stackoverflow_0006381201_multithreading_networking_python.txt
Q: imposing login requirement to visit every resource in twisted web application There's a web application developed in twisted. Does anybody mind suggesting me how can i impose login requirement for visiting every page of that application? Psuedo code to do such task is highly appreciated. A: The Twisted documenta...
imposing login requirement to visit every resource in twisted web application
There's a web application developed in twisted. Does anybody mind suggesting me how can i impose login requirement for visiting every page of that application? Psuedo code to do such task is highly appreciated.
[ "The Twisted documentation includes an example demonstrating the use of twisted.web.guard to require HTTP auth before access is granted to a page.\n" ]
[ 3 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0006383599_python_twisted.txt
Q: If I change the classes attributes , will django automatically change the database structure? I am new to django so i am little bit confused with database syncing. Suppose i have 5 class attributes initially and i used site for 2 days and data is in database. Then i removed 2 attributes and added 3 more attributes...
If I change the classes attributes , will django automatically change the database structure?
I am new to django so i am little bit confused with database syncing. Suppose i have 5 class attributes initially and i used site for 2 days and data is in database. Then i removed 2 attributes and added 3 more attributes. I want to know that how will then Django handle The data which is already there for removed col...
[ "I don't know how you can be confused. The documentation for syncdb clearly states, in a big box, \"Syncdb will not alter existing tables\".\nUse something like South to change existing tables.\n", "or use manage.py reset appname if data in the tables can be truncated\n" ]
[ 2, 0 ]
[]
[]
[ "database", "django", "python" ]
stackoverflow_0006383821_database_django_python.txt
Q: Class Level Property for Django model in Python I have a Django model storing some infrequently changed but often used data. I'm looking for a pattern so that I can refer to them as kind of static class variables, eg, like SomeModel.Bar or SomeModel.Baz. At the moment I'm using a staticmethod like so: class SomeM...
Class Level Property for Django model in Python
I have a Django model storing some infrequently changed but often used data. I'm looking for a pattern so that I can refer to them as kind of static class variables, eg, like SomeModel.Bar or SomeModel.Baz. At the moment I'm using a staticmethod like so: class SomeModel(models.Model): name = models.CharField(max_l...
[ "If you want some logic for model which doesn't belong to particular row, write custom model manager.\n" ]
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006385296_django_python.txt
Q: python - open url and retrieve changed url I want to call a url for e.g. - www.xyz.com its a authentication url after clicking on which produce new url on url bar e.g. www.xyz-11.com how can retrieve this from python? to call a url and to get the newly created url? A: >>> import urllib2 >>> u = urllib2.urlop...
python - open url and retrieve changed url
I want to call a url for e.g. - www.xyz.com its a authentication url after clicking on which produce new url on url bar e.g. www.xyz-11.com how can retrieve this from python? to call a url and to get the newly created url?
[ ">>> import urllib2\n>>> u = urllib2.urlopen('http://google.com')\n>>> dir(u) # useful in seeing what's there, see also help(u)\n['__doc__', '__init__', '__iter__', '__module__', '__repr__', 'close', 'code', 'fileno', 'fp', 'getcode', 'geturl', 'headers', 'info', 'msg', 'next', 'read', 'readline', 'readlines', 'ur...
[ 6 ]
[]
[]
[ "python", "url", "urllib" ]
stackoverflow_0006385263_python_url_urllib.txt
Q: Python lost package I trying to write a client server application in Python, but I faced a problem, in the client side I'm not getting all the sent data. First I tried to send the numbers 1 to 10 and I received 1,2,5,6,10, so there are missing a lot of numbers. Server side: def __init__( self ): super( MCC...
Python lost package
I trying to write a client server application in Python, but I faced a problem, in the client side I'm not getting all the sent data. First I tried to send the numbers 1 to 10 and I received 1,2,5,6,10, so there are missing a lot of numbers. Server side: def __init__( self ): super( MCCommunication, self ).__in...
[ "The server may have sent multiple messages by the time the client attempts to read them, and if these fit within the same 4k buffer, the recv() call will obtain both of them.\nYou don't show the getMessage code, but I'd guess you're doing something like pickle.loads(msg), but this will only give you the first mess...
[ 2 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0006384900_python_sockets.txt
Q: Is there a native templating system for plain text files in Python? I am looking for either technique or templating system for Python for formatting output to simple text. What I require is that it will be able to iterate through multiple lists or dicts. It would be nice if I would be able to define template into ...
Is there a native templating system for plain text files in Python?
I am looking for either technique or templating system for Python for formatting output to simple text. What I require is that it will be able to iterate through multiple lists or dicts. It would be nice if I would be able to define template into separate file (like output.templ) instead of hardcoding it into source co...
[ "You can use the standard library string an its Template class.\nHaving a file foo.txt:\n$title\n$subtitle\n$list\n\nAnd the processing of the file (example.py):\nfrom string import Template\n\nd = {\n 'title': 'This is the title',\n 'subtitle': 'And this is the subtitle',\n 'list': '\\n'.join(['first', 's...
[ 257, 18, 18, 0 ]
[]
[]
[ "python", "string", "templates" ]
stackoverflow_0006385686_python_string_templates.txt
Q: using urllib to import formatted text file with lines out of column I'm trying to use urllib to parse a text file from the website and pull in data. There are other files that I have been able to do, they're text formatted in columns, but this one is kind of throwing me because of the line for Southern Illinois-Ed...
using urllib to import formatted text file with lines out of column
I'm trying to use urllib to parse a text file from the website and pull in data. There are other files that I have been able to do, they're text formatted in columns, but this one is kind of throwing me because of the line for Southern Illinois-Edwardsville pushes the second score and location out of the column. file =...
[ "Wanna see the best solution? http://www.boydsworld.com/cgi/scores.pl?team1=all&team2=all&firstyear=2011&lastyear=2011&format=CSV&submit=Fetch will give you nice CSV file, no dark magic needed.\n", "Say that s contains one row of your table. Then you could use the split() method of the re (regular expressions) li...
[ 2, 0, 0, 0 ]
[]
[]
[ "python", "urllib" ]
stackoverflow_0006385477_python_urllib.txt
Q: 'from X import a' versus 'import X; X.a' I've seen some Python programmers use the following style fairly consistently (we'll call it style 1): import some_module # Use some_module.some_identifier in various places. For support of this style, you can cite the "explicit is better than implicit" maxim. I've seen ot...
'from X import a' versus 'import X; X.a'
I've seen some Python programmers use the following style fairly consistently (we'll call it style 1): import some_module # Use some_module.some_identifier in various places. For support of this style, you can cite the "explicit is better than implicit" maxim. I've seen other programmers use this style (style 2): from...
[ "With the existence of the following syntax:\nimport some_other_module as some_module\n\nthe maintainability argument of style 2 is no longer relevant.\nI tend to use style 1. Normally, I find that I explicitly reference the imported package name only a few times in a typical Python program. Everything else is meth...
[ 5, 5, 2, 2, 1, 0, 0, 0, 0 ]
[]
[]
[ "duck_typing", "maintainability", "python", "python_import" ]
stackoverflow_0000186472_duck_typing_maintainability_python_python_import.txt
Q: Polar plot without grid in matplotlib Is there a way to turn of the grid for polar plots in matplotlib? I tried matplotlib.pyplot.rgrids([], []), but it doesn't work. A: From your axes instance, call grid(False). import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax = fig.add_subplot(111, pol...
Polar plot without grid in matplotlib
Is there a way to turn of the grid for polar plots in matplotlib? I tried matplotlib.pyplot.rgrids([], []), but it doesn't work.
[ "From your axes instance, call grid(False).\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfig = plt.figure()\nax = fig.add_subplot(111, polar=True)\nax.grid(False)\n\nr = np.arange(0,1,0.001)\ntheta = 2*2*np.pi*r\n\nax.plot(theta,r)\nplt.show()\n\n" ]
[ 23 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0006385458_matplotlib_python.txt
Q: Why does 'import x;x.y' behave different from 'from x import y', and the first one fails when package x.__init__ is not completed? Why is there a difference between 'import ...' and 'from ... import ...' and why do I get an exception using the first one? Here is my layout: /tmp/zero/ |~two/ | |-__init__.py | |-fou...
Why does 'import x;x.y' behave different from 'from x import y', and the first one fails when package x.__init__ is not completed?
Why is there a difference between 'import ...' and 'from ... import ...' and why do I get an exception using the first one? Here is my layout: /tmp/zero/ |~two/ | |-__init__.py | |-four.py | `-three.py |-__init__.py `-one.py /tmp/zero/one.py ================= import zero.two /tmp/zero/two/__init__.py =======...
[ "zero.two is a module there, zero/two/__init__.py. It's a concrete thing, not a magic thing. If you put into zero/two/__init__.py a line from . import four, it'll start working. os.path is an example of this - it's a module, but it's imported in os/__init__.py so that you can import os; os.path.\n" ]
[ 3 ]
[]
[]
[ "import", "python" ]
stackoverflow_0006386061_import_python.txt
Q: Django query optimization: find a list of objects based on a many-to-one to a many-to-many I have an ugly loop that is operating as a band-aid in Django that I'd like to optimize into a join. I've broken it down to the most basic structure to help simplify the problem. I'm hoping someone else has run into somethin...
Django query optimization: find a list of objects based on a many-to-one to a many-to-many
I have an ugly loop that is operating as a band-aid in Django that I'd like to optimize into a join. I've broken it down to the most basic structure to help simplify the problem. I'm hoping someone else has run into something like this before -- if not, I'll share the answer when I finally fix it. To summarize Object ...
[ "\nGiven an ObjectB, I need a set of\n other ObjectBs that are the children\n of the ObjectAs that are associated\n with our ObjectB's parent ObjectA.\n\nIf objb is the ObjectB you are given, you could do this as follows:\nobjects = ObjectB.objects.filter(object_a_association__object_a_rules=objb.object_a_associ...
[ 2 ]
[]
[]
[ "django", "python", "sql" ]
stackoverflow_0006385964_django_python_sql.txt
Q: Creating arrays in Python without pre-populating with data enter code hereIs there a way to create (multidimensional) arrays in Python, without pre-populating these arrays with data? Specifically I'm looking for something equivalent to the Ironpython solution I found here : import clr from System import Array,Boo...
Creating arrays in Python without pre-populating with data
enter code hereIs there a way to create (multidimensional) arrays in Python, without pre-populating these arrays with data? Specifically I'm looking for something equivalent to the Ironpython solution I found here : import clr from System import Array,Boolean,Double from System.Activator import CreateInstance a=clr....
[ "The list entries have so have some value in but you could use None.\nFor a one dimension \"array\" it's as simple as:\n[None] * 3\n\nFor a two-dimensional array you have to more careful, as you don't want all your nested lists to the same list, so you can do something like:\n[[None] * 2 for _ in range(3)]\n\nAnoth...
[ 3, 1, 1 ]
[]
[]
[ "multidimensional_array", "python" ]
stackoverflow_0006386384_multidimensional_array_python.txt
Q: Python: check if object exists in scope Possible Duplicate: Python - checking variable existing Is there an efficient, simple and pythonic way to check if an object exists in the scope? In Python everything's an object (variables, functions, classes, class instances etc), so I'm looking for a generic existence t...
Python: check if object exists in scope
Possible Duplicate: Python - checking variable existing Is there an efficient, simple and pythonic way to check if an object exists in the scope? In Python everything's an object (variables, functions, classes, class instances etc), so I'm looking for a generic existence test for an object, no matter what it is. I h...
[ "you could always:\ntry:\n some_object\nexcept NameError:\n do_something()\nelse:\n do_something_else()\n\n", "You seem to be searching for hasattr(). You use it to see if, in the scope of the namespace of an object (and even imported modules are objects), a given attribute name exists.\nSo, I can do:\n...
[ 38, 29, 8, 5, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006383379_python.txt
Q: Python Ignore an Exception and Keep going from where it encountered the Exception I'm having a bit of an issue. I'm parsing a large xml file using Python. The Problem is that the xml file is unpredictable and sometimes certain elements may not be present in the xml, and because of this Python throws an Exception w...
Python Ignore an Exception and Keep going from where it encountered the Exception
I'm having a bit of an issue. I'm parsing a large xml file using Python. The Problem is that the xml file is unpredictable and sometimes certain elements may not be present in the xml, and because of this Python throws an Exception when it looks for it. I want Python to simply ignore this Exception and move on looking ...
[ "What I would do is iterate through a dictionary, (i really like dictionaries) and do everything you were doing before, but differently. Like so (untested):\nfor key in dicto:\n try: user[key] = response.getElementsByTagName(dicto[key])\n except: print \"mumble mumble\"; continue\n\nIt shouldn't take much modific...
[ 3, 2, 1 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0006384808_python_xml.txt
Q: Sharing variables acoss several python files I have tasked to modify a wx python gui based program which has several .py files. I would like to share some variables defined in a.py and use them in b.py The 10 -15 variables are of this form: Amode = [SINGLE] Format = [A] etc... I would like to use them in b.py....
Sharing variables acoss several python files
I have tasked to modify a wx python gui based program which has several .py files. I would like to share some variables defined in a.py and use them in b.py The 10 -15 variables are of this form: Amode = [SINGLE] Format = [A] etc... I would like to use them in b.py. How do I go about it? I read about Pickle but sti...
[ "import a\n\n// do something with a.Amode\n\n// do something with a.Format\n\n", "Generally, the best idea, in this case, is to either place the variables on the module directly or use some shared dataStore. I like the Borg pattern for this.\nBasically do this:\n#in borg.py\nclass Borg:\n __shared_state = {}\n...
[ 3, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006381798_python.txt
Q: griddata runtime error -- Python / SciPy (Interpolation) I use scipy's griddate-function for interpolation. What does the following error message means which appears when python is executing the griddata-function? File "C:\Python25\lib\site-packages\scipy\interpolate\ndgriddata.py", line 182, in griddata ip = Line...
griddata runtime error -- Python / SciPy (Interpolation)
I use scipy's griddate-function for interpolation. What does the following error message means which appears when python is executing the griddata-function? File "C:\Python25\lib\site-packages\scipy\interpolate\ndgriddata.py", line 182, in griddata ip = LinearNDInterpolator(points, values, fill_value=fill_value) File "...
[ "This typically means that the point set you passed in cannot be triangulated. Some common cases when this might occur:\n\nYou have 2D data, but all the points lie along a line. In this case there is no triangulation of the data to non-degenerate triangles.\nYou have 3D data, but all the points lie on a plane, so n...
[ 7, 1 ]
[]
[]
[ "interpolation", "python", "scipy" ]
stackoverflow_0006385621_interpolation_python_scipy.txt
Q: Calculate percentages in Django Query I have two integer fields in seperate related models (I don't think it should matter whether they are in the same model or not, as long as they can be related?), called x and y, how could I filter() so I only get results where x > y * 90%? A: Maybe (if they are not in the sa...
Calculate percentages in Django Query
I have two integer fields in seperate related models (I don't think it should matter whether they are in the same model or not, as long as they can be related?), called x and y, how could I filter() so I only get results where x > y * 90%?
[ "Maybe (if they are not in the same model):\nclass A(models.Model)\n x = ...\n b = OneToOne... \n\nclass B(models.Model)\n y = ....\n\nA.objects.filter(x__gt=F('b.y')*0.9)\n\nreference\n" ]
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006386836_django_python.txt
Q: Pythonians: Is there a better way to code this in Python? I'm a senior PHP and Perl dude, but Python is new to me. I'm enjoying learning it! I wrote the below code, but I can't shake off the feeling that it could be better written by someone with "senior level" Python skills. Are you true Pythonians up to a fun ch...
Pythonians: Is there a better way to code this in Python?
I'm a senior PHP and Perl dude, but Python is new to me. I'm enjoying learning it! I wrote the below code, but I can't shake off the feeling that it could be better written by someone with "senior level" Python skills. Are you true Pythonians up to a fun challenge? Please note: I want the code to readable. Python is s...
[ "You can map a day string to a lambda that takes hourmin and determines whether it is bad or not. For example:\n# establish the \"rules\" \nbad_time = {\n 'Sat': lambda h: True, # always bad time!\n 'Sun': lambda h: h < 2000,\n 'Fri': lambda h: h > 1630,\n}\n\n# ... get your `weekday` and `hourmin` v...
[ 6, 3, 3, 0 ]
[]
[]
[ "datetime", "python", "readability" ]
stackoverflow_0006379112_datetime_python_readability.txt
Q: How to send email with smtplib and MIMEText? I'm looking for an answer for some days and untill now I just didn't solve my problem. All I want is to send a simple email message from my program if an error occure. I'm using the gmail server to do that, and it actually sends the email, but the message of the email d...
How to send email with smtplib and MIMEText?
I'm looking for an answer for some days and untill now I just didn't solve my problem. All I want is to send a simple email message from my program if an error occure. I'm using the gmail server to do that, and it actually sends the email, but the message of the email doesn't appear. Here's the code: def accept(self): ...
[ "Here is a working version modified from code I use when we do system maintenance.\n\n#!/usr/bin/env python\n\nimport smtplib\n\nhost = 'smtp.gmail.com'\nport = '587'\nuser = 'user@gmail.com'\npassw = 'password'\n\nserver = smtplib.SMTP()\nserver.connect(host, port)\nserver.ehlo()\nserver.starttls()\nserver.login(u...
[ 3 ]
[]
[]
[ "email", "gmail", "mime", "python", "smtplib" ]
stackoverflow_0006387567_email_gmail_mime_python_smtplib.txt
Q: Accessing content of each list of a list of list in Python It seems a bit convoluted printed like this, but what I want should be quite simple. I have a list of list in Python. Lets say list = [[A, B, C], [D, B], [E], [X, Y, Z]] I want to iterate over the elements of each inner list following a certain order I tri...
Accessing content of each list of a list of list in Python
It seems a bit convoluted printed like this, but what I want should be quite simple. I have a list of list in Python. Lets say list = [[A, B, C], [D, B], [E], [X, Y, Z]] I want to iterate over the elements of each inner list following a certain order I tried for i in range(0, 10): for item in list[i]: <do ...
[ "This is because your outer list has only 4 elements, and thus does not have an index 4 (or 5 or 6, etc). This is why you are getting an index error.\nIt's analogous to this:\n\n\n\nL = [1, 2, 3]\n L[6] # L does not have a 6th index\n Traceback (most recent call last):\n File \"\", line 1,...
[ 5, 3, 2, 2, 0, 0 ]
[]
[]
[ "list", "loops", "python" ]
stackoverflow_0006387776_list_loops_python.txt
Q: Logging from Django under UWSGI I am running my django app via uwsgi server and am starting 32 processes -args in my init script are: ARGS="--pidfile ${PIDFILE} --uid ${UID} -s /tmp/${NAME}.sock --pythonpath ${GCS_HOME}/server/src/gcs --master -w wsgi -d ${GCS_HOME}/logs/uwsgi.log -p 32 -z 30" Versions are Python...
Logging from Django under UWSGI
I am running my django app via uwsgi server and am starting 32 processes -args in my init script are: ARGS="--pidfile ${PIDFILE} --uid ${UID} -s /tmp/${NAME}.sock --pythonpath ${GCS_HOME}/server/src/gcs --master -w wsgi -d ${GCS_HOME}/logs/uwsgi.log -p 32 -z 30" Versions are Python 2.6.5 , Django 1.2.1, uWSGI 0.9.5.1 ...
[ "ANSWER HAS BEEN UPDATED -May 15, 2013 - \nsee bottom for additional logging option\nIf you want to have a single log file - use syslog, let it handle multiplexing all the inputs into a single file. Having multiple processes appending to a single file is ugly, even with multiprocessing's workarounds.\nAside from th...
[ 12 ]
[]
[]
[ "django", "python", "uwsgi" ]
stackoverflow_0004284859_django_python_uwsgi.txt
Q: django-open-id: CSRF verification failed I fallowed recommendation in this SO question: What's the best solution for OpenID with Django? and installed django-openid-auth for my application. But I just can't get it working, I always get CSRF verification failed. Request aborted. when I try to log in. I have checke...
django-open-id: CSRF verification failed
I fallowed recommendation in this SO question: What's the best solution for OpenID with Django? and installed django-openid-auth for my application. But I just can't get it working, I always get CSRF verification failed. Request aborted. when I try to log in. I have checked everything: 1. {% csrf_token %} is present i...
[ "I tried \"manage.py runserver localhost:8000\" instead of \"manage.py runserver\" and it worked\nmy guess is it has some cookie problems because of ip in hostname\nbtw. i got this error with fresh copy of django 1.3 \n", "Actually, I think it was the first bug I encountered in Django. I've updated my copy to fre...
[ 1, 0 ]
[]
[]
[ "django", "django_csrf", "django_openid_auth", "python" ]
stackoverflow_0005431010_django_django_csrf_django_openid_auth_python.txt
Q: Keep getting a global name not defined error def defineType(riskCode): if riskCode == 1: riskType = High else: if riskCode == 2: riskType = Moderate else: if riskCode == 3: riskType = Low else: if RiskCode == 4: ...
Keep getting a global name not defined error
def defineType(riskCode): if riskCode == 1: riskType = High else: if riskCode == 2: riskType = Moderate else: if riskCode == 3: riskType = Low else: if RiskCode == 4: riskType = No This is part of a ...
[ "It's None not none. Python is case sensitive.\n", "The initial problem I see is that none is not a built-in value in Python. None is though.\nAlso, the tower of nested if statements in the first function is unnecessary. Flatten that!\ndef defineType(riskCode):\n if riskCode == 1:\n riskType = High\n ...
[ 16, 8, 3, 1, 1, 1 ]
[]
[]
[ "global", "python", "variables" ]
stackoverflow_0006387839_global_python_variables.txt
Q: QtWebkit and hasPendingEvents() always True I use project webkit2png (slightly appended) to take screenshots in Linux. On the server running the latest version QtWebkit and Python 2.6 On some sites (eg 118114.cn) problem and the application hangs forever. Debug shows that the problem in this code snippet: whi...
QtWebkit and hasPendingEvents() always True
I use project webkit2png (slightly appended) to take screenshots in Linux. On the server running the latest version QtWebkit and Python 2.6 On some sites (eg 118114.cn) problem and the application hangs forever. Debug shows that the problem in this code snippet: while self.__loading:    if timeout > 0 and time.tim...
[ "I'm also using webkit2png + Linux, and encountered the issue you've described when testing locally on my MacBook Pro. The issue appears to be that QApplication.hasPendingEvents() incorrectly returns True, and the while loop hangs. I worked around this issue by removing the while loop:\nwhile self.__loading:\n if...
[ 1, 1, 0 ]
[]
[]
[ "events", "python", "qtwebkit", "webkit" ]
stackoverflow_0004350016_events_python_qtwebkit_webkit.txt
Q: Import a module, from inside another module Basically I have written two modules for my Python Program. I need one module to import the other module. Here is a sample of my file structure. test_app main.py module_1 __init__.py main.py module_2 __init__.py main.py Main...
Import a module, from inside another module
Basically I have written two modules for my Python Program. I need one module to import the other module. Here is a sample of my file structure. test_app main.py module_1 __init__.py main.py module_2 __init__.py main.py Main.py is able to import either of the two modules, ...
[ "If you started your program from test_app/main.py, you can just use from module_1 import main in test_app/module_2/main.py file.\n", "If you add an (empty) __init__.py to test_app, test_app will be a package. This means that python will search for modules/packages a bit smarter.\nHaving done that, in module1, yo...
[ 3, 2, 1, 1, 0 ]
[]
[]
[ "module", "python" ]
stackoverflow_0006384101_module_python.txt
Q: Should one use TestCase or FunctionTestCase for testing in python? While trying to get a hunch of TDD in python I encountered the FunctionTestCase class. I understand, that it defines equivalent functions to the TestCase classes. assertEqual = failUnlessEqual(self, first, second, msg=None) assertNotEqual = failIfE...
Should one use TestCase or FunctionTestCase for testing in python?
While trying to get a hunch of TDD in python I encountered the FunctionTestCase class. I understand, that it defines equivalent functions to the TestCase classes. assertEqual = failUnlessEqual(self, first, second, msg=None) assertNotEqual = failIfEqual(self, first, second, msg=None) # and so on... Is there a significa...
[ "FunctionTestCase can be used for easily reusing existing code. More often that not you will probably be using the TestCase class.\nFrom unittest documentation:\n\nSome users will find that they have\n existing test code that they would\n like to run from unittest, without\n converting every old test function t...
[ 6 ]
[]
[]
[ "python", "python_unittest", "testcase" ]
stackoverflow_0006388233_python_python_unittest_testcase.txt
Q: Search is printing results and "string not found" condition Can someone explain to me why my conditional search statement is returning both results (it finds the string and prints the results to the screen and it prints "String Not Found"). I've made changes, but I must be overlooking something. Code: if choice =...
Search is printing results and "string not found" condition
Can someone explain to me why my conditional search statement is returning both results (it finds the string and prints the results to the screen and it prints "String Not Found"). I've made changes, but I must be overlooking something. Code: if choice == '1': regex2 = re.compile(r'\s+') for root,di...
[ "You have an indentation problem i think you want:\n...\nfor i,line in enumerate(f.readlines()):\n result2 = regex.search(re.sub(regex2, '',line))\n if result2:\n ln = str(i)\n print \"\\nLine: \" + ln\n print \"File: \" + os.path.join(root,file2)\n print \"String Type: \" + result...
[ 3, 1, 1 ]
[]
[]
[ "if_statement", "python" ]
stackoverflow_0006388089_if_statement_python.txt
Q: What do you wish you'd known about when you started learning Python? I've decided to learn Python 3. For those that have gone before, what did you find most useful along the way and wish you'd known about sooner? A: I learned Python back before the 1.5.2 release, so the things that were key for me back then may...
What do you wish you'd known about when you started learning Python?
I've decided to learn Python 3. For those that have gone before, what did you find most useful along the way and wish you'd known about sooner?
[ "I learned Python back before the 1.5.2 release, so the things that were key for me back then may not be the key things today.\nThat being said, a crucial thing that took me a little bit to realize, but I now consider crucial: much functionality that other languages would make intrinsic is actually made available b...
[ 57, 33, 28, 25, 20, 17, 16, 13, 7, 5, 5, 4, 4, 4, 4, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001710363_python.txt
Q: Merge two arrays into a matrix in python and sort Ok, this is a very easy question for which I could not find the solution here; I have two lists A and B A=(0,1,2,3,...,N-1) (N elements) B=(-50,-30,-10,.....,-45) (N elements) I would like to create a new structure, kind of a 2D matrix "C" with 2xN elements so th...
Merge two arrays into a matrix in python and sort
Ok, this is a very easy question for which I could not find the solution here; I have two lists A and B A=(0,1,2,3,...,N-1) (N elements) B=(-50,-30,-10,.....,-45) (N elements) I would like to create a new structure, kind of a 2D matrix "C" with 2xN elements so that C(0)=(0,-50) C(1)=(1,-30) ... C(N)=(N-1,-45) I coul...
[ "C = zip(A, B)\nD = sorted(C, key=lambda x: x[1])\nA2, B2 = zip(*D)\n\nOr all on one line:\nA2, B2 = zip(*sorted(zip(A,B), key=lambda x: x[1]))\n\n" ]
[ 9 ]
[]
[]
[ "arrays", "matrix", "python", "sorting" ]
stackoverflow_0006389577_arrays_matrix_python_sorting.txt
Q: double valued gauge in wxpython Does anyone know of a double valued gauge in wxPython? I would like to show the range of a set of data that has been selected, I have the max and min values of the gauge and then I'd like to highlight the region of the gauge between two values. The normal wx.Gauge highlights from t...
double valued gauge in wxpython
Does anyone know of a double valued gauge in wxPython? I would like to show the range of a set of data that has been selected, I have the max and min values of the gauge and then I'd like to highlight the region of the gauge between two values. The normal wx.Gauge highlights from the gauge minimum (always the bottom o...
[ "I'm not aware of any built-in widgets with the appearance of wx.Gauge that can do what you're looking for.\nOne option with a different appearance is RulerCtrl, which can give you two value indicators on a scale with whatever range you want. It just takes a bit of extra work to adapt it since not all of its prope...
[ 1 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0006370705_python_wxpython.txt
Q: Adjusting the range of x axis for a live plot (serial data stream) in matplotlib I've been toying with this bit of code off of the matplotlib examples page. I'm trying to get the x axis to maintain a given window. For example, the canvas will plot from x = 0 to 30, 1 to 31, 2 to 32. Right now my x grows on. I have...
Adjusting the range of x axis for a live plot (serial data stream) in matplotlib
I've been toying with this bit of code off of the matplotlib examples page. I'm trying to get the x axis to maintain a given window. For example, the canvas will plot from x = 0 to 30, 1 to 31, 2 to 32. Right now my x grows on. I havent been able to define a set window size. Can anyone point me in the right direction. ...
[ "You can also change both the x and y data, then update the plot limits. I don't know how long you intend this to run, but you should probably consider dumping unneeded y-data at some point.\nimport matplotlib\nmatplotlib.use('TkAgg') # do this before importing pylab\nimport matplotlib.pyplot as plt\nimport random...
[ 1, 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0006387693_matplotlib_python.txt
Q: Generate a heatmap in MatPlotLib using a scatter data set My question is almost exactly similar to this one. However, I'm not satisfied with the answers, because I want to generate an actual heatmap, without explicitely binning the data. To be precise, I would like to display the function that is the result of a c...
Generate a heatmap in MatPlotLib using a scatter data set
My question is almost exactly similar to this one. However, I'm not satisfied with the answers, because I want to generate an actual heatmap, without explicitely binning the data. To be precise, I would like to display the function that is the result of a convolution between the scatter data and a custom kernel, such a...
[ "Convert your time series data into a numeric format with matplotlib.dats.date2num. Lay down a rectangular grid that spans your x and y ranges and do your convolution on that plot. Make a pseudo-color plot of your convolution and then reformat the x labels to be dates.\nThe label formatting is a little messy, but...
[ 13 ]
[]
[]
[ "heatmap", "matplotlib", "plot", "python", "visualization" ]
stackoverflow_0006387819_heatmap_matplotlib_plot_python_visualization.txt
Q: Given two lists in python one with strings and one with objects, how do you map them? I have a list of strings string_list = ["key_val_1", "key_val_2", "key_val_3", "key_val_4", ...] and a list with objects object_list = [object_1, object_2, object_3,...] Every object object_i has an attribute key. I want to sor...
Given two lists in python one with strings and one with objects, how do you map them?
I have a list of strings string_list = ["key_val_1", "key_val_2", "key_val_3", "key_val_4", ...] and a list with objects object_list = [object_1, object_2, object_3,...] Every object object_i has an attribute key. I want to sort the objects in object_list by the order of string_list. I could do something like new_lis...
[ "First, create a dictionary mapping object keys to objects:\nd = dict((x.key, x) for x in object_list)\n\nNext create the sorted list using a list comprehension:\nnew_list = [d[key] for key in string_list]\n\n", "Map each key to its desired precedence:\nkey_precedence = dict((x, n) for n, x in enumerate(string_li...
[ 8, 2, 0 ]
[]
[]
[ "list", "python", "sorting" ]
stackoverflow_0006244171_list_python_sorting.txt
Q: PyQt4 Vertical Layout Autospacing I am using Qt Designer to set up a simple gui for a program I am writing in which I need to display a column of radio buttons. I want to hide some of the radio buttons (not just disable them) based on whether or not their corresponding port is currently available. The radio butt...
PyQt4 Vertical Layout Autospacing
I am using Qt Designer to set up a simple gui for a program I am writing in which I need to display a column of radio buttons. I want to hide some of the radio buttons (not just disable them) based on whether or not their corresponding port is currently available. The radio buttons are in a group box with a vertical ...
[ "Insert a vertical spacer below the bottom-most radio button.\n" ]
[ 2 ]
[]
[]
[ "groupbox", "layout", "pyqt4", "python", "qt_designer" ]
stackoverflow_0006390066_groupbox_layout_pyqt4_python_qt_designer.txt
Q: Django html for, if etc I'm trying to do a simple for loop on my data in djnago-python. I want to iterate over a list and check if some element x has a specific field value. If so, i want to show a remove option, and if not to show an add option. It supposed to look like this in a normal language: flag = false for...
Django html for, if etc
I'm trying to do a simple for loop on my data in djnago-python. I want to iterate over a list and check if some element x has a specific field value. If so, i want to show a remove option, and if not to show an add option. It supposed to look like this in a normal language: flag = false for x in list: if x.game == ...
[ "Django's answer to a lot of things you can't do in the template is to do it in the view.\nGenerally speaking any complex logic should be done in the view. Django doesn't even support variable declaration in the way you use flag=True. We have the with tag but the variable it defines must be used within the definiti...
[ 5, 1, 0, 0 ]
[]
[]
[ "django", "html", "python", "tags" ]
stackoverflow_0006389907_django_html_python_tags.txt
Q: How do I see the Django debug toolbar? I have a Django webapp. I have installed the debug_toolbar middleware and module. However, my webapps don't have the debug toolbar pull-out. How do I actually see the debug toolbar? Is there something more I need to do? Do I need to use a particular template for my webapp? I ...
How do I see the Django debug toolbar?
I have a Django webapp. I have installed the debug_toolbar middleware and module. However, my webapps don't have the debug toolbar pull-out. How do I actually see the debug toolbar? Is there something more I need to do? Do I need to use a particular template for my webapp? I have followed all the steps in the README, b...
[ "\nAs I know your HTML page must contain closed body tag, meta tag with content=\"text/html\".\nI prefer the way when all debug-toolbar's settings separed from main settings. So try put in the end of settings.py something like\n#debug_toolbar settings\nif DEBUG:\n INTERNAL_IPS = ('127.0.0.1',)\n MIDDLEWARE_CL...
[ 52 ]
[]
[]
[ "django", "django_debug_toolbar", "python" ]
stackoverflow_0006390310_django_django_debug_toolbar_python.txt
Q: Ubuntu packages needed to compile Python 2.7 I've tried to compile Python 2.7 on Ubuntu 10.4, but got the following error message after running make: Python build finished, but the necessary bits to build these modules were not found: _bsddb bsddb185 sunaudiodev To find the necessary bit...
Ubuntu packages needed to compile Python 2.7
I've tried to compile Python 2.7 on Ubuntu 10.4, but got the following error message after running make: Python build finished, but the necessary bits to build these modules were not found: _bsddb bsddb185 sunaudiodev To find the necessary bits, look in setup.py in detect_modules() for the mo...
[ "Assuming that you have all the dependencies installed (on Ubuntu that would be bunch of things like sudo apt-get install libdb4.8-dev and various other -dev packages, then this is how I build Python.\ntar zxvf Python-2.7.1.tgz\ncd Python-2.7.1\n\n# 64 bit self-contained build in /opt\nexport TARG=/opt/python272\ne...
[ 16, 6, 6 ]
[]
[]
[ "package", "python", "ubuntu", "ubuntu_10.04" ]
stackoverflow_0003813092_package_python_ubuntu_ubuntu_10.04.txt
Q: How to know where warning come from in Python Is it possible to display line number along with warnings? I'm getting some warnings, possibly from numpy, but I have no idea where they come from. I don't want my code to aboard or to raise an exception, but I'd like to get more information from the origin of the warn...
How to know where warning come from in Python
Is it possible to display line number along with warnings? I'm getting some warnings, possibly from numpy, but I have no idea where they come from. I don't want my code to aboard or to raise an exception, but I'd like to get more information from the origin of the warnings. Is it something possible?
[ "Write a separate module like this.\nimport warnings\n\n# capture all warnings\nwith warnings.catch_warnings(record=True) as warns:\n warnings.simplefilter(\"always\")\n # do the stuff that triggers warnings. i.e. import your main module\n # and call whatever is necessary to get it going. This must all b...
[ 2, 2, 0 ]
[]
[]
[ "numpy", "python", "warnings" ]
stackoverflow_0006389629_numpy_python_warnings.txt
Q: How to grab numbers in the middle of a string? (Python) random string this is 34 the string 3 that, i need 234 random string random string random string random string random string this is 1 the string 34 that, i need 22 random string random string random string random string random string this is 35 the string ...
How to grab numbers in the middle of a string? (Python)
random string this is 34 the string 3 that, i need 234 random string random string random string random string random string this is 1 the string 34 that, i need 22 random string random string random string random string random string this is 35 the string 55 that, i need 12 random string random string random string ...
[ "Use regular expressions:\n>>> import re\n>>> comp_re = re.compile('this is (\\d+) the string (\\d+) that, i need (\\d+)')\n>>> s = \"\"\"random string\nthis is 34 the string 3 that, i need 234\nrandom string\nrandom string\nrandom string\nrandom string\n\nrandom string\nthis is 1 the string 34 that, i need 22\nran...
[ 7, 4, 4 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0006390651_python_regex.txt
Q: Python threads passing parameters I'm trying to passing some parameter to the server tread, but I have no idea how? this is my code: HOST, PORT = socket.gethostbyname( socket.gethostname() ), 31000 self.server = SocketServer.ThreadingTCPServer( ( HOST, PORT ), MCRequestHandler ) ip, port = self.server.server_addre...
Python threads passing parameters
I'm trying to passing some parameter to the server tread, but I have no idea how? this is my code: HOST, PORT = socket.gethostbyname( socket.gethostname() ), 31000 self.server = SocketServer.ThreadingTCPServer( ( HOST, PORT ), MCRequestHandler ) ip, port = self.server.server_address self.server_thread = threadi...
[ "I think the second parameter of ThreadingTCPServer is a factory:\n SocketServer.ThreadingTCPServer( ( HOST, PORT ), MCRequestHandler )\n\nWhat you could do is your own factory here. Class will contstuct a callable object. when the object is called it will initialize MCRequestHandler with parameters given to the f...
[ 3 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0006389892_multithreading_python.txt
Q: How to prevent decompilation or inspecting python code? let us assume that there is a big, commercial project (a.k.a Project), which uses Python under the hood to manage plugins for configuring new control surfaces which can be attached and used by Project. There was a small information leak, some part of the Proj...
How to prevent decompilation or inspecting python code?
let us assume that there is a big, commercial project (a.k.a Project), which uses Python under the hood to manage plugins for configuring new control surfaces which can be attached and used by Project. There was a small information leak, some part of the Project's Python API leaked to the public information and people ...
[ "No, this does not solve the problem. Someone could just rename the inspect module to something else and import it.\nWhat you're trying to do is not possible. The python interpreter must be able to take your bytecode and execute it. Someone will always be able to decompile the bytecode. They will always be able to ...
[ 12, 8, 4, 1 ]
[]
[]
[ "decompiling", "inspect", "python" ]
stackoverflow_0006390489_decompiling_inspect_python.txt
Q: Executing subprocess from Python without opening Windows Command Prompt Possible Duplicate: Running a process in pythonw with Popen without a console How do I eliminate Windows consoles from spawned processes in Python (2.7)? I have a Python program that calls a separate number-crunching program (written in C) a...
Executing subprocess from Python without opening Windows Command Prompt
Possible Duplicate: Running a process in pythonw with Popen without a console How do I eliminate Windows consoles from spawned processes in Python (2.7)? I have a Python program that calls a separate number-crunching program (written in C) as a subprocess several times (using subprocess.check_call). It works great o...
[ "When you build the C application, set its type to the Win32 Subsystem instead of the Console Subsystem. If this is a pre-built application, you could change the subsystem with this tool.\n", "How are you calling subprocess.check_call()? If you pass shell=True then the window should not be created as this will c...
[ 2, 2 ]
[]
[]
[ "python", "subprocess", "windows" ]
stackoverflow_0006390394_python_subprocess_windows.txt
Q: Help with how to pickle a ufunc? I'm attempting to broadcast a module to other python processes with MPI. Of course, a module itself isn't pickleable, but the __dict__ is. Currently, I'm pickling the __dict__ and making a new module in the receiving process. This worked perfectly with some simple, custom modules. ...
Help with how to pickle a ufunc?
I'm attempting to broadcast a module to other python processes with MPI. Of course, a module itself isn't pickleable, but the __dict__ is. Currently, I'm pickling the __dict__ and making a new module in the receiving process. This worked perfectly with some simple, custom modules. However, when I try to do this with Nu...
[ "Pickling a function in Python only serializes its name and the module it comes from. It does not transport code over the wire, so when unpickling you need to have the same libraries available as when pickling. On unpickling, Python simply imports the module in question, and grabs the items via getattr. (This is no...
[ 3 ]
[]
[]
[ "mpi", "numpy", "pickle", "python" ]
stackoverflow_0006389775_mpi_numpy_pickle_python.txt
Q: CheckMenuItem problem in pygtk trayicon program I have the following python (pygtk) program. When I move the mouse over the menu displayed, if clicked on the item in the tray the check boxes become checked and immediately unchecked again. I'm using Ubuntu 10.10 or 11.04. #!/usr/bin/python import gtk import glib...
CheckMenuItem problem in pygtk trayicon program
I have the following python (pygtk) program. When I move the mouse over the menu displayed, if clicked on the item in the tray the check boxes become checked and immediately unchecked again. I'm using Ubuntu 10.10 or 11.04. #!/usr/bin/python import gtk import glib import subprocess import time import sys class...
[ "The submenu is \"toggling\" the state of the checkbox when it appears. You can fight this behavior by handling the toggle signal of the checkbox menuitem.\nclass StatusIcon:\n\n...\n\n def callback(self, widget, data=None):\n widget.set_active(False)\n\n...\n\n for item in lst:\n newmenuitem = gtk.C...
[ 2 ]
[]
[]
[ "checkbox", "menu", "pygtk", "python", "trayicon" ]
stackoverflow_0006385038_checkbox_menu_pygtk_python_trayicon.txt
Q: Django admin, limiting what data is being displayed inside a ManyToManyField i have 3 models Team, Player and Fixture. Fixture class Fixture(models.Model): """(Fixture description)""" home = models.ForeignKey(Team, related_name="home_games") away = models.ForeignKey(Team, related_name="away_games") ...
Django admin, limiting what data is being displayed inside a ManyToManyField
i have 3 models Team, Player and Fixture. Fixture class Fixture(models.Model): """(Fixture description)""" home = models.ForeignKey(Team, related_name="home_games") away = models.ForeignKey(Team, related_name="away_games") home_players = models.ManyToManyField(Player, related_name="home_games") away...
[ "To have your away_players field automatically update itself as you select the home or away team you'd need to use JavasScript.\n\nListen for change event on away_team\nSend a view the selection and have it return a new list to populate your away_players field. (check get_urls for where this code might live)\n\nIt'...
[ 2 ]
[]
[]
[ "django", "many_to_many", "manytomanyfield", "python" ]
stackoverflow_0006390988_django_many_to_many_manytomanyfield_python.txt
Q: How are web apps written in Python deployed? I'm an ex-PHP developer and I'm struggling to get over the mindset that I can write an nginx config script, create the directories, fire up nginx + PHP-FPM, upload my code and let it run. I want to start playing with Python to get a feel for it and start creating web ap...
How are web apps written in Python deployed?
I'm an ex-PHP developer and I'm struggling to get over the mindset that I can write an nginx config script, create the directories, fire up nginx + PHP-FPM, upload my code and let it run. I want to start playing with Python to get a feel for it and start creating web applications, but I'm a little lost as to how to get...
[ "I am a beginner Python developer myself, so I've had the same questions. Perhaps a more advanced user can fill in the details. Here's what I've done so far:\nThe simplest way to get started is to simply make an executable python script (.py) and drop it in your cgi-bin. You can then access it via yourhost.com/c...
[ 2, 0, 0 ]
[]
[]
[ "gevent", "nginx", "python" ]
stackoverflow_0006319180_gevent_nginx_python.txt
Q: The opposite of string.Template in Python I know template can work like the following: x = Template(" Coordinates; $o1;$o2;$o3;\n") y = x.substitute(o1 = 23, o2 = 108, o3 = 655) and y will give me: " Coordinates; 23;108;655;\n" I am wondering if there is a way to do the reverse of this? something like ...
The opposite of string.Template in Python
I know template can work like the following: x = Template(" Coordinates; $o1;$o2;$o3;\n") y = x.substitute(o1 = 23, o2 = 108, o3 = 655) and y will give me: " Coordinates; 23;108;655;\n" I am wondering if there is a way to do the reverse of this? something like my made up unpack: x = Template(" Coordinates;...
[ ">>> import re\n>>> y=\" Coordinates; 23;108;655;\\n\"\n>>> re.match(\" Coordinates; (\\d+);(\\d+);(\\d+);\\n\", y).groups()\n('23', '108', '655')\n\nYou can also do this to get a dict of the values\n>>> re.match(\" Coordinates; (?P<o1>\\d+);(?P<o2>\\d+);(?P<o3>\\d+);\\n\", y).groupdict()\n{'o3': '65...
[ 5, 2, 0 ]
[]
[]
[ "python", "regex", "string", "templates" ]
stackoverflow_0006391699_python_regex_string_templates.txt
Q: Cannot extend base.html from parent directory I have this directory structure: root: +pages -base.html ... +en -index.html ... index.py ... When I render index.html from index.py, it says it cannot find base.html. This is the tag I used in index.html to extend base.html: {% extends "../base.html" %} This ...
Cannot extend base.html from parent directory
I have this directory structure: root: +pages -base.html ... +en -index.html ... index.py ... When I render index.html from index.py, it says it cannot find base.html. This is the tag I used in index.html to extend base.html: {% extends "../base.html" %} This is the code in index.py: path = os.path.join(os.pat...
[ "You can't use paths like that in the extends tag. But you don't need to - assuming your TEMPLATE_DIRS setting is root/pages, you just do extends \"base.html\".\n", "I answered a question very much like this here: TemplateDoesNotExist on python app-engine django 1.2 while template rendering relative paths\nThe te...
[ 3, 0 ]
[]
[]
[ "django_templates", "google_app_engine", "python" ]
stackoverflow_0006390924_django_templates_google_app_engine_python.txt
Q: django: why does accessing a page from web browser freeze the server? I've made a django app, running it w/ the built-in server for now (just for testing). I have programs which access urls multiple times per second on the app without any issues. However, when I view an admin page, or one of those URLs that the pr...
django: why does accessing a page from web browser freeze the server?
I've made a django app, running it w/ the built-in server for now (just for testing). I have programs which access urls multiple times per second on the app without any issues. However, when I view an admin page, or one of those URLs that the program visits, in a web browser, the server freezes for many seconds. Why mi...
[ "The Django development server only does 1 request at a time. I believe that's why you have the issue.\n", "If you are using chrome, this could be a known issue that is fixed today in trunk by jezdez:\nhttps://code.djangoproject.com/changeset/16427 \n" ]
[ 2, 1 ]
[]
[]
[ "browser", "django", "python" ]
stackoverflow_0006391388_browser_django_python.txt
Q: C# or other .NET equivalents of core python modules for IronPython? I would like to compile and distribute (on .net) some python programs that work well with IronPython, but I am new to .net and am getting errors related to particular python modules. There is a utility for compiling to low level .net and it works...
C# or other .NET equivalents of core python modules for IronPython?
I would like to compile and distribute (on .net) some python programs that work well with IronPython, but I am new to .net and am getting errors related to particular python modules. There is a utility for compiling to low level .net and it works well, but I get errors when dealing with common libraries; code that run...
[ "The os (and shutil ) replacements in .NET are in the System.IO namespace.\n\nThe System.IO namespace contains types that allow reading and writing to files and data streams, and types that provide basic file and directory support.\n\nFor most of your file file operations, try the methods of the System.IO.File clas...
[ 2, 0 ]
[]
[]
[ ".net", "c#", "ironpython", "python" ]
stackoverflow_0001699856_.net_c#_ironpython_python.txt