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: Adding extra field to UserModel Django So I finally managed to add a location field to my User model and this is the code I have: model: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save class UserProfile(models.Model): user = models.On...
Adding extra field to UserModel Django
So I finally managed to add a location field to my User model and this is the code I have: model: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save class UserProfile(models.Model): user = models.OneToOneField(User) location = models....
[ "You don't add fields to the old model this way, you're creating a new one that's associated with it. Your data will be in app_userprofile table, and you can access that instance (to save that location or whatever) via user.get_profile(). You can't use straightforward ModelForm for that, I'm afraid, you need to han...
[ 1 ]
[]
[]
[ "django", "model", "python", "sqlite" ]
stackoverflow_0006997076_django_model_python_sqlite.txt
Q: Where to store custom objects? I'm confused about where to store custom python objects (of not just basic type -- so cannot be stored as blender properties). What I'm trying to achieve is this: I want to accomplish a heavy computation that can be started by pressing a button (operator) and can be paused by pressin...
Where to store custom objects?
I'm confused about where to store custom python objects (of not just basic type -- so cannot be stored as blender properties). What I'm trying to achieve is this: I want to accomplish a heavy computation that can be started by pressing a button (operator) and can be paused by pressing the same button. The computation s...
[ "You might look into pickling. http://docs.python.org/library/pickle.html\n" ]
[ 0 ]
[]
[]
[ "blender", "python", "scripting" ]
stackoverflow_0006995773_blender_python_scripting.txt
Q: Search for a string in a line using regex I am searching for a string in the format XXXXX_XXXXX or XXXXXX_XXXXX or XXXXXX in a line, where X is alphanumeric. So the string before "_" is 5 or 6 characters long and the string after "_" is always five or may be just 6 characters long without any underscore. I am cod...
Search for a string in a line using regex
I am searching for a string in the format XXXXX_XXXXX or XXXXXX_XXXXX or XXXXXX in a line, where X is alphanumeric. So the string before "_" is 5 or 6 characters long and the string after "_" is always five or may be just 6 characters long without any underscore. I am coding in Python. Any help will be much appreciate...
[ "Howabout this?\n([a-zA-Z0-9]{5,6}_[a-zA-Z0-9]{5})|[a-zA-Z0-9]{6}\n\nFull code example:\nimport re\npat = re.compile(r'^(([a-zA-Z0-9]{5,6}_[a-zA-Z0-9]{5})|[a-zA-Z0-9]{6})$')\nprint pat.match('xxxxx_xxxxx') is not None # True, 5 chars, underscore, 5 chars\nprint pat.match('xxxxxx_xxxxx') is not None # True, 6 ...
[ 3, 1, 0, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0006946550_python_regex.txt
Q: Problem in Python with function only writing one line to file I am trying to write a function in Python 3 that will write all lines that end with the string 'halloween' to a file. When I call this function, I can only get one line to write to the output file (file_2.txt). Can anyone point out where my problem is? ...
Problem in Python with function only writing one line to file
I am trying to write a function in Python 3 that will write all lines that end with the string 'halloween' to a file. When I call this function, I can only get one line to write to the output file (file_2.txt). Can anyone point out where my problem is? Thanks in advance. def parser(reader_o, infile_object, outfile_obj...
[ "def parser(reader_o):\n for line in reader_o:\n if line.rstrip().endswith('halloween'):\n yield line\n\nwith open(\"file_1.txt\", \"r\") as file_input:\n with open(\"file_2.txt\", \"w\") as file_output:\n file_output.writelines(parser(file_input))\n\nThis is called a generator. It ca...
[ 6, 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0006997710_python_python_3.x.txt
Q: twitter authentication issue using oauth? I have written an application which using twitter authentication. Authentication process: Get the request token Authorize the token Get the access key Now I have access key, I can use the twitter API. I stored the access_key pair in the database for further use. But when...
twitter authentication issue using oauth?
I have written an application which using twitter authentication. Authentication process: Get the request token Authorize the token Get the access key Now I have access key, I can use the twitter API. I stored the access_key pair in the database for further use. But when next time user logged in via twitter, since al...
[ "You mean you're using the \"log in via twitter\" hack?\nWell, if you want a \"remember me\" option you can build one just like normal (store some session info in a cookie... all security caveats apply).\nIf the actually are logged out and there's no cookie then you have to go through the whole process again anyway...
[ 1 ]
[]
[]
[ "api", "python", "twitter" ]
stackoverflow_0006998046_api_python_twitter.txt
Q: Check time to make sure I don't go over max duration set while in a loop? (Python) What function of the time module can I use to get the time and do math on it? MAX_DURATION = 60 startTime = get the time while(True): wait random seconds curTime = get the time if curTime - startTime > MAX_DURATION: ...
Check time to make sure I don't go over max duration set while in a loop? (Python)
What function of the time module can I use to get the time and do math on it? MAX_DURATION = 60 startTime = get the time while(True): wait random seconds curTime = get the time if curTime - startTime > MAX_DURATION: break
[ "import time\n\ntime.time()\n\nThis should fit your needs.\n", "You'll want datetime and especially timedelta: http://docs.python.org/library/datetime.html\nFor example:\nimport time\nfrom datetime import datetime, timedelta\nimport random\n\nMAX_DURATION = timedelta(seconds=60)\nstart = datetime.now()\nwhile 1:\...
[ 3, 0 ]
[]
[]
[ "python", "time" ]
stackoverflow_0006998546_python_time.txt
Q: django: avoid "Unused variable" warning on get_or_create Is there a way to avoid "Unused variable" warning on get_or_create method? level,created= Level.objects.get_or_create( name='Alumnes x Classificar') because I don't need to read created variable, IDE show a warning about this. I know that a trivial solution...
django: avoid "Unused variable" warning on get_or_create
Is there a way to avoid "Unused variable" warning on get_or_create method? level,created= Level.objects.get_or_create( name='Alumnes x Classificar') because I don't need to read created variable, IDE show a warning about this. I know that a trivial solutions i to use variable, some thing like: if create: pass But I'm ...
[ "One “standard” way of doing this is to use the _ variable:\nlevel, _ = Level.objects.get_or_create(…)\n\n_ is a “real variable” (insomuch as you can read from and write to it), but it's generally understood to mean “ignored”.\n", "You could only capture the level by doing:\nlevel = Level.objects.get_or_create( n...
[ 5, 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006998586_django_python.txt
Q: How to redirect output of Python script to terminal How can I redirect my Python script output to one of the open terminal windows under Ubuntu? The script is spawned by KMail filtering rule. A: Creating a simple socket server would be one method… But I'd probably use fifos: $ mkfifo /tmp/my_fifo $ cat producer....
How to redirect output of Python script to terminal
How can I redirect my Python script output to one of the open terminal windows under Ubuntu? The script is spawned by KMail filtering rule.
[ "Creating a simple socket server would be one method… But I'd probably use fifos:\n$ mkfifo /tmp/my_fifo\n$ cat producer.py\nf = open(\"/tmp/my_fifo\", \"w\")\nf.write(\"hello, world!\\n\")\nf.close()\n\nThen you could read from it using cat /tmp/my_fifo\nOr a simple log file:\n$ cat producer.py\nf = open(\"/tmp/my...
[ 1 ]
[]
[]
[ "python", "terminal", "ubuntu" ]
stackoverflow_0006998530_python_terminal_ubuntu.txt
Q: Recognize fields from PDF,DOC and etc formats and export them to database is anybody know the solution for reading file(for example pdf format, it has some tax information), recognize fields and write them to DB? It is similiar idea that FlexiCapture has. Thank you for your attention! A: I didn't get any answer...
Recognize fields from PDF,DOC and etc formats and export them to database
is anybody know the solution for reading file(for example pdf format, it has some tax information), recognize fields and write them to DB? It is similiar idea that FlexiCapture has. Thank you for your attention!
[ "I didn't get any answers to my question. So I did a little bit research and I think the answer to my question will be - OCR.\nhttp://code.google.com/p/pytesser/\nhttp://code.google.com/p/ocropus/ \nHopefully I will start my testing soon. Thanks everybody!\n" ]
[ 0 ]
[]
[]
[ "java", "php", "python" ]
stackoverflow_0006911803_java_php_python.txt
Q: Comparing date value from DB with date literal I'm getting a date value out of a DB2 database using ADODB objects. This date is sometimes set to 1/1/0001. This is an invalid datetime in SQL Server. I need to check for this value and set it to a valid SQL Server date (1/1/1900 for example). The object coming fr...
Comparing date value from DB with date literal
I'm getting a date value out of a DB2 database using ADODB objects. This date is sometimes set to 1/1/0001. This is an invalid datetime in SQL Server. I need to check for this value and set it to a valid SQL Server date (1/1/1900 for example). The object coming from the ADODB looks to be a time.struct_time. What's...
[ "You should either be able to convert it to a string:\ntime.strftime('%d/%m/%Y', badtimeobj)\n\nand compare it that way, or \ntry:\n time.asctime(timeFromDb2)\nexcept:\n invalid = True\nelse:\n invalid = False\n\nor the equivalent, if all other dates work in asctime.\n", ">>> time.strptime('1/1/0001', '%...
[ 1, 0 ]
[]
[]
[ "adodb", "date", "python" ]
stackoverflow_0006996855_adodb_date_python.txt
Q: Python Requests Module & JSON Responses I am using the awesome Requests module to test an API I've created for one of our internal projects. I believe I have discovered what is either a flaw in the Requests module itself, or a flaw in my usage of it. Because our data is not super sensitive, our API uses simple, b...
Python Requests Module & JSON Responses
I am using the awesome Requests module to test an API I've created for one of our internal projects. I believe I have discovered what is either a flaw in the Requests module itself, or a flaw in my usage of it. Because our data is not super sensitive, our API uses simple, basic HTTP authentication to control acces. Wh...
[ "Out of curiosity, what do you get when you print r.content ?\n" ]
[ 6 ]
[]
[]
[ "http_request", "json", "python", "python_requests" ]
stackoverflow_0006998943_http_request_json_python_python_requests.txt
Q: Running external program using pipes and passing arguments in python I am running an external program using pipes in python and it works fine. However I would like to pass two arguments to this external program. Could anyone help me with that? Thanks! A: from subprocess import Popen, PIPE p = Popen(['external-p...
Running external program using pipes and passing arguments in python
I am running an external program using pipes in python and it works fine. However I would like to pass two arguments to this external program. Could anyone help me with that? Thanks!
[ "from subprocess import Popen, PIPE\n\np = Popen(['external-program', 'arg1', 'arg2'], \n stdin=PIPE, stdout=PIPE, stderr=PIPE)\n\nif you mean piping the out into or out of the Python script, or \nfrom subprocess import Popen, PIPE\n\np = Popen('external-program arg1 arg2 | external2'], shell=True)\n...
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0006998955_python.txt
Q: Using sqlite prepared statements with SELECT I'm working on a little pet project that organizes people's comic books and stores metadata about them in an SQL database. For the sake of correctness, I'm using prepared statements instead of Python's built in string operators, but I can't quite get it to work right. ...
Using sqlite prepared statements with SELECT
I'm working on a little pet project that organizes people's comic books and stores metadata about them in an SQL database. For the sake of correctness, I'm using prepared statements instead of Python's built in string operators, but I can't quite get it to work right. This is a brief snippet of code I've made to illu...
[ "You can't use placeholders for column names - they are for values only. So this would work:\ncmd = \"SELECT * from comic_collection WHERE %s LIKE ?\" % attribute\ncurs.execute(cmd, (val,))\n\n", "Your usage of attribute is wrong. Imagine that the ? already includes its surrending ''s.\nOne way would be to do it ...
[ 7, 5 ]
[ "From what I recall of prepared statements in the sqlite C api, you may have to write it like this:\ncmd = \"SELECT * from comic_collection WHERE ?1 LIKE ?2\"\n\n" ]
[ -3 ]
[ "python", "sqlite" ]
stackoverflow_0006998968_python_sqlite.txt
Q: What is the second part of the address returned by recvfrom? I'm using those 2 pieces of code from http://wiki.python.org/moin/UdpCommunication The server: import socket UDP_IP="127.0.0.1" UDP_PORT=5005 sock = socket.socket( socket.AF_INET, # Internet socket.SOCK_DGRAM ) # UDP sock.bind( (U...
What is the second part of the address returned by recvfrom?
I'm using those 2 pieces of code from http://wiki.python.org/moin/UdpCommunication The server: import socket UDP_IP="127.0.0.1" UDP_PORT=5005 sock = socket.socket( socket.AF_INET, # Internet socket.SOCK_DGRAM ) # UDP sock.bind( (UDP_IP,UDP_PORT) ) while True: data, addr = sock.recvfrom( 102...
[ "It's an ephemeral port used by the client to send data to the server.\n", "It definitely is the port. You can verify it on the sender side with print sock.getsockname().\nYou can as well set it deliberately with e. g. sock.bind(('', 54312)) before the sock.sendto() line.\nThis could be useful in context where so...
[ 3, 1 ]
[]
[]
[ "networking", "python", "sockets", "udp" ]
stackoverflow_0006999207_networking_python_sockets_udp.txt
Q: Tab-completion in iPython on Mac OS X Snow Leopard I have installed iPython and Readline on Mac OS X Snow Leopard and am having difficulty getting tab-completion to work properly. For example, when I do import sys sys.<tab> the tab key only registers as a normal tab. However, when I do import sys sys.<alt+tab> ...
Tab-completion in iPython on Mac OS X Snow Leopard
I have installed iPython and Readline on Mac OS X Snow Leopard and am having difficulty getting tab-completion to work properly. For example, when I do import sys sys.<tab> the tab key only registers as a normal tab. However, when I do import sys sys.<alt+tab> it works as it should, returning all possible completion...
[ "I had a similar problem and I fixed it by using the new stable release of iPython (0.11). According to the iPython website this release is \"a major new version and the result of over two years of work.\"\nAn iPython egg based on Python 2.6 can be found here.\n" ]
[ 2 ]
[]
[]
[ "ipython", "python", "readline", "tab_completion" ]
stackoverflow_0005593456_ipython_python_readline_tab_completion.txt
Q: Python Django RegExp error I'm designing a search for my blog. This is my stop words list:STOP_WORDS = r"""\b(a|about|above|across...)\b"""I keep getting this traceback:Cannot process flags argument with a compiled patternDoes anyone know why? How should I rewrite: stop_word_list = re.compile(STOP_WORDS_RE, re.IGN...
Python Django RegExp error
I'm designing a search for my blog. This is my stop words list:STOP_WORDS = r"""\b(a|about|above|across...)\b"""I keep getting this traceback:Cannot process flags argument with a compiled patternDoes anyone know why? How should I rewrite: stop_word_list = re.compile(STOP_WORDS_RE, re.IGNORECASE)?
[ "You don't show this code, but presumably you have\nSTOP_WORDS_RE = re.compile(STOP_WORDS)\n\nsomewhere.\nYou want to pass re.IGNORECASE to re.compile with the regex string, STOP_WORDS in your case. So:\n# *not* STOP_WORDS_RE!\nstop_word_list = re.compile(STOP_WORDS, re.IGNORECASE)\n\n", "You don't pass re.IGNORE...
[ 2, 1 ]
[]
[]
[ "django", "error_handling", "python", "regex" ]
stackoverflow_0006997204_django_error_handling_python_regex.txt
Q: Python expose to scope Let's consider we have a module called mod which has a function func. I want to import the module and run func, exposing a variable var to its scope. a.func() # and func can do stuff with var How can i do this? A: Either you import the module where var is defined into your mod module, or...
Python expose to scope
Let's consider we have a module called mod which has a function func. I want to import the module and run func, exposing a variable var to its scope. a.func() # and func can do stuff with var How can i do this?
[ "Either you import the module where var is defined into your mod module, or you pass var as an argument to func().\n", "Most likely, you should add an argument to func() through which to pass in the variable var. If you want func() to modify var, then have the function return the new value. (If necessary you ca...
[ 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006999645_python.txt
Q: Using Google App engine for python/html web posting and sending automated email Quick question, I m developing (n learning) a simple app whereby the user posts a comment to my webapp on GAE, and i will reply with an automated email (in Python).. Not sure where i got it wrong but was wondering whether anyone can he...
Using Google App engine for python/html web posting and sending automated email
Quick question, I m developing (n learning) a simple app whereby the user posts a comment to my webapp on GAE, and i will reply with an automated email (in Python).. Not sure where i got it wrong but was wondering whether anyone can help or guide me along? Done a quick code snippets with some modifications from code.go...
[ "I think ur indentation is wrong. Also give ids to ur input elements Try this \nfrom google.appengine.ext import webapp\n\nfrom google.appengine.api import mail\n\nclass MyRequestHandler(webapp.RequestHandler):\n def get(self):\n self.response.out.write('''\n <html>\n <body>\n ...
[ 1, 1 ]
[]
[]
[ "email", "google_app_engine", "post", "python" ]
stackoverflow_0006998652_email_google_app_engine_post_python.txt
Q: How do I make a standalone tool using the tripit API? I'm trying to make a simple commandline application that queries tripit to pull down data about my travel history. I seem to be getting stuck somewhere along the oauth setup, but it's not entirely clear to me what I'm doing wrong. I have registered an applicat...
How do I make a standalone tool using the tripit API?
I'm trying to make a simple commandline application that queries tripit to pull down data about my travel history. I seem to be getting stuck somewhere along the oauth setup, but it's not entirely clear to me what I'm doing wrong. I have registered an application and been assigned an API key and secret. I've stored t...
[ "Try it with \"?format=json\" instead of \"/format/json\". I've seen it work that way before (but haven't used the JSON interface).\n" ]
[ 0 ]
[]
[]
[ "authentication", "oauth", "python", "web_services" ]
stackoverflow_0006566356_authentication_oauth_python_web_services.txt
Q: How to pull specific information from an output in Python So I have a code that gives an output, and what I need to do is pull the information out in between the commas, assign them to a variable that changes dynamically when called... here is my code: import re data_directory = 'Z:/Blender_Roto/' data_file = 'di...
How to pull specific information from an output in Python
So I have a code that gives an output, and what I need to do is pull the information out in between the commas, assign them to a variable that changes dynamically when called... here is my code: import re data_directory = 'Z:/Blender_Roto/' data_file = 'diving_board.shape4ae' fullpath = data_directory + data_file pr...
[ "Instead of printing each output, you can create point objects and index them by name. For example:\n>>> class Point:\n... def __init__(self, t):\n... (self.x,self.y,self.z,self.w,self.s) = t\n... \n>>> p = Point( (3,4,5,3,1) )\n>>> p.w\n3\n\nYou can place these point objects in an array, then access c...
[ 3, 0 ]
[]
[]
[ "blender", "mocha.js", "parsing", "pyparsing", "python" ]
stackoverflow_0006999860_blender_mocha.js_parsing_pyparsing_python.txt
Q: Apply attribute class to Python class which Inherits a C# base Class I have a base class in C# which is like so Class A { public ClassA() { } ..... } In python I Inherit this base class import clr clr.AddReferenceToFile("MyClass.dll") from MyNamespace import ClassA class MySu...
Apply attribute class to Python class which Inherits a C# base Class
I have a base class in C# which is like so Class A { public ClassA() { } ..... } In python I Inherit this base class import clr clr.AddReferenceToFile("MyClass.dll") from MyNamespace import ClassA class MySubclass(ClassA): def _init_(self): print "I'm in a subclass in ...
[ "I don't think there's a simple way to do that. It's definitely easier to use a C# stub class having the necessary attributes defined and subclass that. \nBut, if you really need to define a class like that in python, you can use a workaround (as shown here )\nBasically you can compile (in memory) a piece of C# cod...
[ 0 ]
[]
[]
[ "attributes", "c#", "ironpython", "python" ]
stackoverflow_0006994383_attributes_c#_ironpython_python.txt
Q: python How to detect a new piece of media in the CD? I have a need to copy a group of files. Unfortunately these files will span multiple DVDs. What I want to do is a) copy the files of the current DVD b) when complete, eject the media and prompt the user to insert the next DVD c) Detect when media is inserted ...
python How to detect a new piece of media in the CD?
I have a need to copy a group of files. Unfortunately these files will span multiple DVDs. What I want to do is a) copy the files of the current DVD b) when complete, eject the media and prompt the user to insert the next DVD c) Detect when media is inserted d) validate that is is the desired DVD (if not do B again)...
[ "I ended up using a combination of wmi and ctypes\nimport wmi\nimport os\nimport time\nimport wx\nimport ctypes\n\napp = wx.PySimpleApp(0)\nc = wmi.WMI()\n\nfor cdrom in c.Win32_CDROMDrive():\n status = cdrom.MediaLoaded\n drive = cdrom.Drive\n\n\ncheckFile = os.path.join(drive,'IWPCpatch-2','install.zip')\np...
[ 1, 0, 0 ]
[]
[]
[ "media", "python" ]
stackoverflow_0006376596_media_python.txt
Q: Python - suggestions for filtering/sorting a large file? I have a file containing ~20 million lines (~1.5GB). Each line is of the form: entry_1 entry_2 entry_3 ......... entry_5 The file contains duplicates but of the form: entry_2 entry_1 entry_3 ......... entry_5 The contents of some lines are identical but th...
Python - suggestions for filtering/sorting a large file?
I have a file containing ~20 million lines (~1.5GB). Each line is of the form: entry_1 entry_2 entry_3 ......... entry_5 The file contains duplicates but of the form: entry_2 entry_1 entry_3 ......... entry_5 The contents of some lines are identical but the first two elements are often (possibly always) switched. Doe...
[ "A suitable solution would depend on what constraints you have and how often you need to run this operation.\nIf this is a one-time (or infrequent) operation and if memory usage is not a big issue, something like this would be sufficient:\nvisited = set() # use set for faster lookups\nwith open(out_filename, \"w\")...
[ 5, 1 ]
[]
[]
[ "filter", "python", "sorting" ]
stackoverflow_0006999641_filter_python_sorting.txt
Q: How to assign a string value to an array in numpy? When I try to assign a string to an array like this: CoverageACol[0,0] = "Hello" I get the following error Traceback (most recent call last): File "<pyshell#19>", line 1, in <module> CoverageACol[0,0] = "hello" ValueError: setting an array element with a s...
How to assign a string value to an array in numpy?
When I try to assign a string to an array like this: CoverageACol[0,0] = "Hello" I get the following error Traceback (most recent call last): File "<pyshell#19>", line 1, in <module> CoverageACol[0,0] = "hello" ValueError: setting an array element with a sequence. However, assigning an integer does not result ...
[ "You get the error because NumPy's array is homogeneous, meaning it is a multidimensional table of elements all of the same type. This is different from a multidimensional list-of-lists in \"regular\" Python, where you can have objects of different type in a list.\nRegular Python:\n>>> CoverageACol = [[0, 1, 2, 3, ...
[ 22, 7 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0006999617_numpy_python.txt
Q: How to disable specific button in Pmw.ButtonBox? I have added a button as: def addButtons(self): self.buttonBox = Pmw.ButtonBox(self.dataFrame, labelpos = 'nw', label_text = '', frame_borderwidth = 1, frame_relief = 'groove') self.buttonBox.pack() self.bu...
How to disable specific button in Pmw.ButtonBox?
I have added a button as: def addButtons(self): self.buttonBox = Pmw.ButtonBox(self.dataFrame, labelpos = 'nw', label_text = '', frame_borderwidth = 1, frame_relief = 'groove') self.buttonBox.pack() self.buttonBox.place(relx=.75, rely=.750, anchor=W) # Ad...
[ "According to the pmw.ButtonBox documentation, the add method returns a reference to the button that is created. So, just save the reference that it returns and then configure that button like you would any other button. \n" ]
[ 2 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0007000081_python_tkinter.txt
Q: Get child dict values use Mongo Map/Reduce I have a mongo collection, i want get total value of 'number_of_ad_clicks' by given sitename, timestamp and variant id. Because we have large data so it would be better use map/reduce. Could any guys give me any suggestion? Here is my collection json format { "_id" : Obje...
Get child dict values use Mongo Map/Reduce
I have a mongo collection, i want get total value of 'number_of_ad_clicks' by given sitename, timestamp and variant id. Because we have large data so it would be better use map/reduce. Could any guys give me any suggestion? Here is my collection json format { "_id" : ObjectId( "4e3c280ecacbd1333b00f5ff" ), "timestamp...
[ "The emit function emits both a key and a value. \nIf you are used to SQL think of key as your GROUP BY and value as your SUM(), AVG(), etc..\nIn your case you want to \"group by\": site_name, timestamp and variant id. It looks like you may have more than one variant, so you will need to loop through the variants, ...
[ 0 ]
[]
[]
[ "mongodb", "mongomapper", "python" ]
stackoverflow_0006997858_mongodb_mongomapper_python.txt
Q: why is python script failing to download webpages through a proxy i am new to python and am trying my luck at sockets. So i wrote a simple http client but to my surprise it is failing to access webpages that firefox can access, yet they use the same headers import socket clientsocket= socket.socket(socket.AF_INET,...
why is python script failing to download webpages through a proxy
i am new to python and am trying my luck at sockets. So i wrote a simple http client but to my surprise it is failing to access webpages that firefox can access, yet they use the same headers import socket clientsocket= socket.socket(socket.AF_INET, socket.SOCK_STREAM) clientsocket.connect(("213.229.83.205",80))#connec...
[ "The HTTP protocol requires \\r\\n at the end of each header and an extra on a blank line at the end of the HTTP headers. You aren't explicit about the line endings in your sdata buffer, and therefore your buffer ends up with just \\n line endings. \nTested on Windows, Linux and OS X, to be sure:\n>>> x = \"\"\"a...
[ 5 ]
[]
[]
[ "proxy", "python", "sockets" ]
stackoverflow_0007000730_proxy_python_sockets.txt
Q: PIL Plus/imToolkit replacements I've been trying to find if there was any continuation of the abilities that were provided for PIL Plus for Python also known as imToolkit. I know that PIL Plus (aka imToolkit) was a commercial extension to Python. And that it was available to PIL support customers. I also know that...
PIL Plus/imToolkit replacements
I've been trying to find if there was any continuation of the abilities that were provided for PIL Plus for Python also known as imToolkit. I know that PIL Plus (aka imToolkit) was a commercial extension to Python. And that it was available to PIL support customers. I also know that the PIL Plus extension is no longer ...
[ "I'm not sure how imfill works. Is it like this:\nimport numpy as np\nimport scipy.ndimage.morphology as morphology\n\nbw = np.array([[0, 0, 0, 0, 0, 0, 0, 0],\n [0, 1, 1, 1, 1, 1, 0, 0],\n [0, 1, 0, 0, 0, 1, 0, 0],\n [0, 1, 0, 0, 0, 1, 0, 0],\n [0, 1, 0, 0, 0...
[ 2 ]
[]
[]
[ "image_processing", "python", "python_imaging_library" ]
stackoverflow_0007000288_image_processing_python_python_imaging_library.txt
Q: Creating a Client-Server application using C# and Python - comments? I want to move away from the myriad of excel sheets at work and develop a small application for asset tracking. Initially I'd planned it as a web application, but have had comments from the primary users of the would-be application that they woul...
Creating a Client-Server application using C# and Python - comments?
I want to move away from the myriad of excel sheets at work and develop a small application for asset tracking. Initially I'd planned it as a web application, but have had comments from the primary users of the would-be application that they would much prefer a client application as they sometimes can't guarantee inter...
[ "WCF Web API Anyone?\nhttp://wcf.codeplex.com/wikipage?title=WCF%20HTTP\nWCF Web API satisfies your needs quite well. Not only do you get first class support for .NET clients locally but you can run this REST service locally as a windows service.\n[WebGet(UriTemplate = \"\")]\npublic List<Contact> Get()\n{\n var...
[ 0 ]
[]
[]
[ "c#", "python" ]
stackoverflow_0006998615_c#_python.txt
Q: Check python interactive mode in sitecustomize I have a MOTD-type message which prints on invocation of the interpreter. Currently this is printed up in sitecustomize. I'd like to suppress the message if the interpreter is not in interactive mode; unfortunately all of the checks in Tell if Python is in interactiv...
Check python interactive mode in sitecustomize
I have a MOTD-type message which prints on invocation of the interpreter. Currently this is printed up in sitecustomize. I'd like to suppress the message if the interpreter is not in interactive mode; unfortunately all of the checks in Tell if Python is in interactive mode do not work in sitecustomize. (sys.argv, sys....
[ "JAB got me looking at the code and I ultimately came up with this:\nimport ctypes\nimport getopt\n\nctypes.pythonapi.Py_GetArgcArgv.restype = None\nctypes.pythonapi.Py_GetArgcArgv.argtypes = [\n ctypes.POINTER(ctypes.c_int),\n ctypes.POINTER(ctypes.POINTER(ctypes.c_char_p))]\ncount = ctypes.c_int()\nargs = c...
[ 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006600541_python.txt
Q: Possible to Simplify These Python Regular Expressions? patterns = {} patterns[1] = re.compile("[A-Z]\d-[A-Z]\d") patterns[2] = re.compile("[A-Z]\d-[A-Z]\d\d") patterns[3] = re.compile("[A-Z]\d\d-[A-Z]\d\d") patterns[4] = re.compile("[A-Z]\d\d-[A-Z]\d\d\d") patterns[5] = re.compile("[A-Z]\d\...
Possible to Simplify These Python Regular Expressions?
patterns = {} patterns[1] = re.compile("[A-Z]\d-[A-Z]\d") patterns[2] = re.compile("[A-Z]\d-[A-Z]\d\d") patterns[3] = re.compile("[A-Z]\d\d-[A-Z]\d\d") patterns[4] = re.compile("[A-Z]\d\d-[A-Z]\d\d\d") patterns[5] = re.compile("[A-Z]\d\d\d-[A-Z]\d\d\d") patterns[6] = re.compile("[A-Z][A-Z]\d...
[ "Sean Bright gave you the answer you need. Here's just a general tip:\nPython has wonderful documentation. In this case, you could read it with the \"help\" command:\nimport re\nhelp(re)\n\nAnd if you read through the help, you would see:\n{m,n} Matches from m to n repetitions of the preceding RE.\n\nIt also h...
[ 4, 4, 3, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007000900_python_regex.txt
Q: Converting a program from FreeBASIC to Python: globalizing variables In a previous post, I was told I am coding in Python like you would in BASIC (I am not "thinking" in Python yet). This is probably true and this is why I need help. This being said, I have read one book about Python so far (Bytes of Python), I bo...
Converting a program from FreeBASIC to Python: globalizing variables
In a previous post, I was told I am coding in Python like you would in BASIC (I am not "thinking" in Python yet). This is probably true and this is why I need help. This being said, I have read one book about Python so far (Bytes of Python), I bought two more books online (one of which is Invent with Python, which I am...
[ "You don't need to declare a name as global unless you are going to assign to it.\na = 1\nb = 2\ndef foo():\n global b\n print a # prints 1\n b = 3\nfoo()\nprint b # prints 3\n\n", "I've reorganized your program to show you the basics of object oriented programming. You need to learn about classes and ob...
[ 3, 2, 2, 1 ]
[]
[]
[ "freebasic", "global_variables", "oop", "python" ]
stackoverflow_0007000753_freebasic_global_variables_oop_python.txt
Q: "TypeError: cannot concatenate 'str' and 'int' objects" when trying to use printf-style formatting I don't see problem in here, but Python thinks different: x = 3 y = 7 z = 2 print "I told to the Python, that the first variable is %d!" % x print "Anyway, 2nd and 3rd variables sum is %d. :)" % y + z I get TypeErr...
"TypeError: cannot concatenate 'str' and 'int' objects" when trying to use printf-style formatting
I don't see problem in here, but Python thinks different: x = 3 y = 7 z = 2 print "I told to the Python, that the first variable is %d!" % x print "Anyway, 2nd and 3rd variables sum is %d. :)" % y + z I get TypeError: cannot concatenate 'str' and 'int' objects. Why is that so? I haven't setted any variable as string....
[ "% has a higher precedence than +, so s % y + z is parsed as (s % y) + z.\nIf s is a string, then s % x is a string, and (s % y) + z attempts to add a string (the result of s % y) and an integer (the value of z).\n", "You need to put parenthesis: (y+z)\n" ]
[ 13, 8 ]
[]
[]
[ "concatenation", "integer", "python", "string", "typeerror" ]
stackoverflow_0007001664_concatenation_integer_python_string_typeerror.txt
Q: Use scipy.integrate.quad from within a cdef statement in Cython? I am trying to speed up my Python by translating it into Cython. It uses the function scipy.integrate.quad, which requires a python callable as one of its arguments. Is there any way to define and pass a function from within a cdef statement in Cytho...
Use scipy.integrate.quad from within a cdef statement in Cython?
I am trying to speed up my Python by translating it into Cython. It uses the function scipy.integrate.quad, which requires a python callable as one of its arguments. Is there any way to define and pass a function from within a cdef statement in Cython so I can use this? Thanks.
[ "Yes, you have just to wrap the function with a python function.\ndef py_callback(a):\n return c_callback(a)\n\ncdef float c_callback(float a):\n return a * a\n\n...\nscipy.integrate.quad(py_callback)\n\nThere is a bit of conversion overload of course.\nAn alternative is to look up how that function is implemen...
[ 3 ]
[]
[]
[ "cython", "function", "numerical_integration", "python", "scipy" ]
stackoverflow_0006835209_cython_function_numerical_integration_python_scipy.txt
Q: Python strings in a Cython extension type I have an extension type (cdef class) with a string field. I don't know what's the best way of declaring it. Assume the following code: cdef class Box: cdef char *_s cdef public str s1 cdef public bytes s2 property s: def __get__(self): ...
Python strings in a Cython extension type
I have an extension type (cdef class) with a string field. I don't know what's the best way of declaring it. Assume the following code: cdef class Box: cdef char *_s cdef public str s1 cdef public bytes s2 property s: def __get__(self): cdef bytes py_string = self._s ret...
[ "I am not sure why you have concerns about the garbage collection of the string.\nIf that strings comes from another C-space program then just copy its value, so that the Box object owns it.\n" ]
[ 0 ]
[]
[]
[ "cython", "python" ]
stackoverflow_0006874102_cython_python.txt
Q: Python: How to return an instance of an object along with attributes assigned with setattr I am still very new to python, but I need to interface with some software that is written as a bunch of python modules (.py files in case I incorrectly identified them as "modules.") This program has some very useful and com...
Python: How to return an instance of an object along with attributes assigned with setattr
I am still very new to python, but I need to interface with some software that is written as a bunch of python modules (.py files in case I incorrectly identified them as "modules.") This program has some very useful and complicated functions that I really cannot feasibly hack (if nothing else, because every time I upd...
[ "You're doing\ntube=io.read(str(name))\n\nif \nTYPE!='bare'\n\nSo in that case you wouldn't get the dimensions. Could this be why you're having the problem?\nAlso, have you tried just doing\ntube.dimensions = [tube.get_cell()[0, 0] / 2, tube.get_cell()[-1,-1]]\n\ninstead of setattr? It's only needed when the name o...
[ 1 ]
[]
[]
[ "python", "setattr" ]
stackoverflow_0007001676_python_setattr.txt
Q: Pause Python Generator I have a python generator that does work that produces a large amount of data, which uses up a lot of ram. Is there a way of detecting if the processed data has been "consumed" by the code which is using the generator, and if so, pause until it is consumed? def multi_grab(urls,proxy=None,ref...
Pause Python Generator
I have a python generator that does work that produces a large amount of data, which uses up a lot of ram. Is there a way of detecting if the processed data has been "consumed" by the code which is using the generator, and if so, pause until it is consumed? def multi_grab(urls,proxy=None,ref=None,xpath=False,compress=T...
[ "A generator simply yields values. There's no way for the generator to know what's being done with them.\nBut the generator also pauses constantly, as the caller does whatever it does. It doesn't execute again until the caller invokes it to get the next value. It doesn't run on a separate thread or anything. It...
[ 8, 2, 0, 0 ]
[]
[]
[ "generator", "python" ]
stackoverflow_0007001917_generator_python.txt
Q: Android SL4A (Python) Force Stop Packages fails. I'm trying to terminate task using code like this: import android droid = android.Android() running = droid.getRunningPackages()[1] for task in running: if (task.find("skype") != -1) droid.forceStopPackages(task) this works properly except killing call `droi...
Android SL4A (Python) Force Stop Packages fails.
I'm trying to terminate task using code like this: import android droid = android.Android() running = droid.getRunningPackages()[1] for task in running: if (task.find("skype") != -1) droid.forceStopPackages(task) this works properly except killing call `droid.forceStopPackages(task)` # When we get here, variabl...
[ "Since Android 2.2 (Froyo) killing apps is not really reliable. Play around with a task killer to see what I mean.\n" ]
[ 1 ]
[]
[]
[ "android", "kill", "python", "sl4a", "task" ]
stackoverflow_0004714870_android_kill_python_sl4a_task.txt
Q: expected buffer object error on string.translate - python 2.6 I´d appreciate some help for a python novice, I´m trying to delete some characters from a string, like this, for example: string1 = "100.000" deleteList = [",", "."] string1.translate(None, deleteList) print string1 but I get a TypeError: expected a ...
expected buffer object error on string.translate - python 2.6
I´d appreciate some help for a python novice, I´m trying to delete some characters from a string, like this, for example: string1 = "100.000" deleteList = [",", "."] string1.translate(None, deleteList) print string1 but I get a TypeError: expected a character buffer object Why do I get this error, which argument doe...
[ "The docs for string.translate says\nS.translate(table [,deletechars]) -> string\n\nwhich suggests that deletechars should be a string of characters, instead of a list of characters:\nstring1 = \"100.000\"\nstring1=string1.translate(None, ',.')\nprint (string1)\n# 100000\n\n", "The error you get reffers to your d...
[ 10, 1 ]
[]
[]
[ "python", "string", "translate" ]
stackoverflow_0007002206_python_string_translate.txt
Q: Loading Macros from Other Template Files in Chameleon I have a Pyramid app that uses Chameleon for its templates. I would like to create a master template page (say master.pt) that contains several macros that I user throughout the pages of my site. I am trying to load these macros in different templates across my...
Loading Macros from Other Template Files in Chameleon
I have a Pyramid app that uses Chameleon for its templates. I would like to create a master template page (say master.pt) that contains several macros that I user throughout the pages of my site. I am trying to load these macros in different templates across my application, but I can't seem to do so - Chameleon's docum...
[ "In case anyone was wondering, since I am using Pyramid, the usage is a little different:\nhttp://docs.pylonsproject.org/projects/pyramid/1.0/narr/templates.html#using-zpt-macros-in-pyramid\n" ]
[ 0 ]
[]
[]
[ "chameleon", "external", "python", "template_metal" ]
stackoverflow_0006991360_chameleon_external_python_template_metal.txt
Q: Can I extend Jenkins with Jython/Python Is it possible to write Jenkins plugins using Python (via Jython), and if so, where would I get started? I don't know Java (and don't have a real interest in learning it at the moment) so being able to use Python would be nice for me. A: There's no docs on that. Frankly yo...
Can I extend Jenkins with Jython/Python
Is it possible to write Jenkins plugins using Python (via Jython), and if so, where would I get started? I don't know Java (and don't have a real interest in learning it at the moment) so being able to use Python would be nice for me.
[ "There's no docs on that. Frankly your problem with be you must understand how the interfaces and extensions map from java to jython to write it.\nHere are links on writing Jenkins plugins\nLet's you embed either Jython or Python scripts and run them from a plugin If all you nee to do is run a simple script, that b...
[ 4, 1, 0 ]
[]
[]
[ "continuous_integration", "java", "jenkins", "jython", "python" ]
stackoverflow_0005714263_continuous_integration_java_jenkins_jython_python.txt
Q: Using current scope as kwargs in python I basically want to expand the current scope as you would a dictionary when calling a function. I remember seeing something about this somewhere but I cannot remember where or how to do it. Here is a simple example def bar(a, b, c, d, e, f): pass def foo(a, b, c, d, e, ...
Using current scope as kwargs in python
I basically want to expand the current scope as you would a dictionary when calling a function. I remember seeing something about this somewhere but I cannot remember where or how to do it. Here is a simple example def bar(a, b, c, d, e, f): pass def foo(a, b, c, d, e, f): # Instead of doing this bar(a, b,...
[ "You can use locals() (or globals() depending on what you need), which returns a dictionary mapping variable names to values.\nbar(**locals())\n\n", "if foo was written like this\ndef foo(**kwargs):\n bar(**kwargs)\n\nOther than that the other two examples you posted are better, expanding all locals is a bad i...
[ 6, 3 ]
[]
[]
[ "keyword_argument", "python" ]
stackoverflow_0007002481_keyword_argument_python.txt
Q: How to draw an ordered tree in python? I have an XML file whose underlying structure is an ordered tree. I use digraph in networks representing this tree and then I want to draw this tree. Suppose the digraph is G, then I write the following code: map = dict(zip(id,tag)) # map from id to label pos = nx.pydot_layou...
How to draw an ordered tree in python?
I have an XML file whose underlying structure is an ordered tree. I use digraph in networks representing this tree and then I want to draw this tree. Suppose the digraph is G, then I write the following code: map = dict(zip(id,tag)) # map from id to label pos = nx.pydot_layout(G,prog = 'dot') labels = nx.draw_networkx_...
[ "Don't call a variable map, there is a builtin called map.\nYou can use an OrderedDict to keep the items in order:\nfrom collections import OrderedDict\nfrom itertools import izip\nthemap = OrderedDict(izip(id,tag)) # map from id to label\n\nYou can also get it from PyPI if you have an older version of Python than ...
[ 1 ]
[]
[]
[ "graph", "python", "tree" ]
stackoverflow_0007002600_graph_python_tree.txt
Q: How do you use map(reverse, ITERABLE) with arguments to reverse? It is possible to call reverse with arguments for example: reverse('page', args=['page1']) finds the url named page that takes an argument. My question is how would I do this if I am using Python's map? I want something of this form: map(reverse,...
How do you use map(reverse, ITERABLE) with arguments to reverse?
It is possible to call reverse with arguments for example: reverse('page', args=['page1']) finds the url named page that takes an argument. My question is how would I do this if I am using Python's map? I want something of this form: map(reverse, ITERABLE) where iterable is a bunch of of named urls with args. Thu...
[ "You could just use a list comprehension:\n[reverse(page, args=args) for page, args in ITERABLE]\n\nAssuming, of course, that ITERABLE is something like [(page, args), (page1, arg1), ...]\n", "Assuming that each item in ITERABLE is a tuple (or list) consisting of the URL and the arguments, you could use a lambda ...
[ 3, 2, 2 ]
[]
[]
[ "django", "performance", "python" ]
stackoverflow_0007002636_django_performance_python.txt
Q: python filter calculated values from large lists to create multiple smaller lists I want to find an optimal method to process very large ordered lists of integers eg. biglist = [45, 34, 2, 78, 7, 9, 10, 33, 78, 51, 99, 24, 88, ... N] where N > 1m to create multiple small lists of fixed length S (~=200) by reading...
python filter calculated values from large lists to create multiple smaller lists
I want to find an optimal method to process very large ordered lists of integers eg. biglist = [45, 34, 2, 78, 7, 9, 10, 33, 78, 51, 99, 24, 88, ... N] where N > 1m to create multiple small lists of fixed length S (~=200) by reading each biglist element, apply different operations on the element, and if meets a condit...
[ "Does biglist really have to be a list? If you can create them with a generator, you can save the memory, and perhaps save some time.\n", "S = 200\nimport itertools\nbiglist = itertools.islice(itertools.ifilter(lambda x: 7 < x/5 < 69, biglist),S)\n\nor if you want multiple chunks just apply ifilter and then loop...
[ 0, 0, 0 ]
[]
[]
[ "filter", "list", "list_comprehension", "python" ]
stackoverflow_0007002350_filter_list_list_comprehension_python.txt
Q: Inter-service messaging/bus for twisted Is there an in-twisted mechanism for passing messages in-process service to another? I wrote up a prototype bus that looks like from collections import defaultdict channels = defaultdict(list) def registerSingle(name, callback): """ Similar...
Inter-service messaging/bus for twisted
Is there an in-twisted mechanism for passing messages in-process service to another? I wrote up a prototype bus that looks like from collections import defaultdict channels = defaultdict(list) def registerSingle(name, callback): """ Similar to register but ensures only one callback is...
[ "it sounds like you want a \"blackboard\" or \"tuple space\" for python (i don't see how twisted changes things?)? if so, here's one - http://pypi.python.org/pypi/linda/0.5.1\n" ]
[ 1 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0006999812_python_twisted.txt
Q: Methods of the same name and inheritance, Python I have an odd question, and seeing as the real context is fairly complex I've made a simple example. I have two classes Base and Child. Each share a method of the the same name go. What I want the Child class to be able to do is inherit the go method from Base. Howe...
Methods of the same name and inheritance, Python
I have an odd question, and seeing as the real context is fairly complex I've made a simple example. I have two classes Base and Child. Each share a method of the the same name go. What I want the Child class to be able to do is inherit the go method from Base. However, when I call the go method on Child I want it to d...
[ "This is absolutely a fine thing to do. What you're looking for is super().\nclass Child (Base):\n def __init__ (self):\n super(Child, self).__init__()\n\n def go(self):\n self.A = self.A * 2\n super(Child, self).go()\n\nIn Python 3 you can use it without arguments because it will detect ...
[ 12 ]
[]
[]
[ "class", "inheritance", "methods", "python" ]
stackoverflow_0007003125_class_inheritance_methods_python.txt
Q: How to get Gitzilla to work I have recently set up a bugzilla instance for bug tracking and would like to integrate it with git. I found Gitzilla which seemed to be awesome from its description, but I am now fed up after hours of confusion with it not working. I am running Ubuntu Natty. 1) pybugz is installed and...
How to get Gitzilla to work
I have recently set up a bugzilla instance for bug tracking and would like to integrate it with git. I found Gitzilla which seemed to be awesome from its description, but I am now fed up after hours of confusion with it not working. I am running Ubuntu Natty. 1) pybugz is installed and I can access bugs using: bugz --...
[ "GitZilla author here. \nGit is meant to be distributed where everyone has their own repository. Bugzilla integration makes sense with a single repository as opposed to integrating with everyone's repo.\nThe use case is the following:\n\neveryone has their own git repository\neveryone pushes to a \"central\"...
[ 4 ]
[]
[]
[ "bugzilla", "git", "integration", "pybugz", "python" ]
stackoverflow_0006976006_bugzilla_git_integration_pybugz_python.txt
Q: How do I extract HTML list entries into a Python list? Possible Duplicate: Parsing HTML in Python I have a long string of HTML similar to the following: <ul> <li><a href="/a/long/link">Class1</a></li> <li><a href="/another/link">Class2</a></li> <li><img src="/image/location" border="0">Class3</a></li> </ul> I...
How do I extract HTML list entries into a Python list?
Possible Duplicate: Parsing HTML in Python I have a long string of HTML similar to the following: <ul> <li><a href="/a/long/link">Class1</a></li> <li><a href="/another/link">Class2</a></li> <li><img src="/image/location" border="0">Class3</a></li> </ul> It has several list entries (Class1 to Class8). I'd like to ...
[ "Check out lxml (pip install lxml). You'll want to do a little more research, but effectively it comes down to something like this:\nfrom lxml import etree\n\ntree = etree.HTML(page_source)\ndef parse_list(xpath):\n ul = tree.xpath(xpath)\n return [child.text for child in ul.getchildren()]\n\n", "If all the...
[ 2, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007003138_python_regex.txt
Q: Python: Is there a good way to check if text is encrypted? I've been playing around with cryptocat, which is an interesting online chat service that allows you to encrypt your messages with a key, so that only people with the same key can read your message. An interesting aspect of the service (in my opinion) is t...
Python: Is there a good way to check if text is encrypted?
I've been playing around with cryptocat, which is an interesting online chat service that allows you to encrypt your messages with a key, so that only people with the same key can read your message. An interesting aspect of the service (in my opinion) is the fact that text encrypted using a key other than the one that ...
[ "there is no guaranteed way to tell, but in practice you can do two things:\n\ncheck for many non-ascii characters (if you're expecting people to be sending english text).\ncheck the distribution of values. in normal text, some letters are much more common than others. but in encrypted text, all characters are ab...
[ 16, 5, 0 ]
[]
[]
[ "chat", "encryption", "python", "stream_cipher" ]
stackoverflow_0007000885_chat_encryption_python_stream_cipher.txt
Q: How can I install Python 3x and 2x into same machine? Possible Duplicate: Can I install python 3.x and 2.x on the same computer? I am learning Python which I started with 3.2. Now I know basics and want to use some frameworks to learn web development. Here, I came to notice Django doesn't supports Python 3x yet....
How can I install Python 3x and 2x into same machine?
Possible Duplicate: Can I install python 3.x and 2.x on the same computer? I am learning Python which I started with 3.2. Now I know basics and want to use some frameworks to learn web development. Here, I came to notice Django doesn't supports Python 3x yet. So, I need to use Python 2x on same machine. How can I in...
[ "Just install them normally. By default each version of Python is installed to a different path, and won't conflict. Python 3 and Python 2 don't even use the same executable name (python vs python3), so there's not a lot to worry about.\n", "they will install into C:\\Python27, and C:\\Python32 by default.\nno co...
[ 5, 2 ]
[ "i didn't want to answer this but i have to since you might have a problem that no one is talking about lol\nfirst don't install python from the official website go to activestate and download activepython for python 2,7\nhere's a direct link\nhttp://downloads.activestate.com/ActivePython/releases/2.7.2.5/ActivePyt...
[ -1 ]
[ "django", "python" ]
stackoverflow_0007003025_django_python.txt
Q: Running external program using pipes and passing arguments in python I tried that, but when I try to print these arguments it returns no values. I submit my code below: script1 that runs external python program (script2) #(...) proc = subprocess.Popen(['export PYTHONPATH=~/:$PYTHONPATH;' + 'export environment=...
Running external program using pipes and passing arguments in python
I tried that, but when I try to print these arguments it returns no values. I submit my code below: script1 that runs external python program (script2) #(...) proc = subprocess.Popen(['export PYTHONPATH=~/:$PYTHONPATH;' + 'export environment=/path/to/environment/;' + 'python /path/to/my/program/myProgram.py', ...
[ "Try this version of script 1:\nproc = subprocess.Popen('python /path/to/my/program/myProgram.py %s %s' % (date, time),\n stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True, \n env = {'PYTHONPATH': '~/:$PYTHONPATH',\n 'environment': '/path/t...
[ 1, 1, 1 ]
[]
[]
[ "pipe", "popen", "python", "subprocess" ]
stackoverflow_0007003320_pipe_popen_python_subprocess.txt
Q: NumPy Array Indexing Simple question here about indexing an array to get a subset of its values. Say I have a recarray which holds ages in one space, and corresponding values in another. I also have an array which is my desired subset of ages. Here is what I mean: ages = np.arange(100) values = np.random.unifor...
NumPy Array Indexing
Simple question here about indexing an array to get a subset of its values. Say I have a recarray which holds ages in one space, and corresponding values in another. I also have an array which is my desired subset of ages. Here is what I mean: ages = np.arange(100) values = np.random.uniform(low=0, high= 1, size = a...
[ "You want to create an subarray containing only the values whose indexes are in desired_ages.\nPython doesn't have any syntax that directly corresponds to this, but list comprehensions can do a pretty nice job:\nresult = [value for index, value in enumerate(data.values) if index in desired_ages]\n\nHowever, doing i...
[ 4, 2, 2 ]
[]
[]
[ "arrays", "indexing", "numpy", "python" ]
stackoverflow_0007002895_arrays_indexing_numpy_python.txt
Q: using Oauth to access app engine pull queue from non app engine server I am trying to access my app engine applications pull queue from a separate python application. Here's what I know: I need to use oauth to authenticate I need to use Google's rest api I need to define a pull queue in my app engine project that...
using Oauth to access app engine pull queue from non app engine server
I am trying to access my app engine applications pull queue from a separate python application. Here's what I know: I need to use oauth to authenticate I need to use Google's rest api I need to define a pull queue in my app engine project that has an acl list which specifies which account is granted access to the queu...
[ "Use the google-api-python-client library.\nIt has a sample to access the TaskQueue APIs through Oauth2 authentication.\n", "Have you read the OAuth for Python overview for AppEngine? It goes over how to do the OAuth login for App Engine.\n" ]
[ 2, 0 ]
[]
[]
[ "google_app_engine", "oauth", "oauth_2.0", "python" ]
stackoverflow_0006999458_google_app_engine_oauth_oauth_2.0_python.txt
Q: Need help installing python-cdb on windows Hello wise people of stack overflow, I require your assistance. I'm trying to install a python module called python-cdb on a computer running Windows XP. I've installed MinGW and have been attempting to use it as my compiler, but I get the following error messages: > pyth...
Need help installing python-cdb on windows
Hello wise people of stack overflow, I require your assistance. I'm trying to install a python module called python-cdb on a computer running Windows XP. I've installed MinGW and have been attempting to use it as my compiler, but I get the following error messages: > python setup.py build --compiler=mingw32 running bu...
[ "I believe that your compiler cannot find the necessary files to execute your program. Maybe deleting and reinstalling Python or Visual Studio. Also make sure to update, update, update!!!\n" ]
[ 0 ]
[]
[]
[ "installation", "mingw", "python" ]
stackoverflow_0005954514_installation_mingw_python.txt
Q: Web2py - request.vars.values()[0] - can't define What would be the possible reasons for getting the error: IndexError: list index out of range Whilst it's trying to define: partialstr = request.vars.values()[0] A: If the list-like thing returned by request.vars.values() has no elements, then this error would be...
Web2py - request.vars.values()[0] - can't define
What would be the possible reasons for getting the error: IndexError: list index out of range Whilst it's trying to define: partialstr = request.vars.values()[0]
[ "If the list-like thing returned by request.vars.values() has no elements, then this error would be expected -- you would be trying to access the first element in an empty list.\nTry displaying len(request.vars.values()). If it is 0 then that's your problem.\n", "As pointed out here, you should use request.vars....
[ 0, 0 ]
[]
[]
[ "python", "variables", "web2py" ]
stackoverflow_0006990629_python_variables_web2py.txt
Q: Generating digits of square root of 2 I want to generate the digits of the square root of two to 3 million digits. I am aware of Newton-Raphson but I don't have much clue how to implement it in C or C++ due to lack of biginteger support. Can somebody point me in the right direction? Also, if anybody knows how to d...
Generating digits of square root of 2
I want to generate the digits of the square root of two to 3 million digits. I am aware of Newton-Raphson but I don't have much clue how to implement it in C or C++ due to lack of biginteger support. Can somebody point me in the right direction? Also, if anybody knows how to do it in python (I'm a beginner), I would al...
[ "You could try using the mapping:\na/b -> (a+2b)/(a+b) starting with a= 1, b= 1. This converges to sqrt(2) (in fact gives the continued fraction representations of it).\nNow the key point: This can be represented as a matrix multiplication (similar to fibonacci)\nIf a_n and b_n are the nth numbers in the steps then...
[ 7, 6, 3, 3, 3, 2, 2, 0, 0 ]
[]
[]
[ "algorithm", "numerical_methods", "python", "sqrt" ]
stackoverflow_0005187664_algorithm_numerical_methods_python_sqrt.txt
Q: Getting DRY with Python Conditionals and Django returns What I'm about to share is a common pattern in my projects. Some cases are longer than others but the pattern is more or less the same and I'm wondering how I can be more DRY. if status == 'ACTIVE' and p.result != "0": messages.add_message(request, messa...
Getting DRY with Python Conditionals and Django returns
What I'm about to share is a common pattern in my projects. Some cases are longer than others but the pattern is more or less the same and I'm wondering how I can be more DRY. if status == 'ACTIVE' and p.result != "0": messages.add_message(request, messages.ERROR, _('Active Message... bla bla bla')) ...
[ "Could it be something in the line of:\nlib module\ndef add_error_message(request, status, result=0):\n if status == 'ACTIVE' and not result:\n msg = 'Active Message... bla bla bla'\n elif status == 'TOO MANY FAILURES':\n msg = 'Failed. Foooobarrrrr'\n elif status == 'DEACTIVATED BY MERCHANT'...
[ 4, 0 ]
[]
[]
[ "django", "dry", "python" ]
stackoverflow_0007003436_django_dry_python.txt
Q: assigning values in a nested list using for loops in python I need to create a nested list, four levels deep. On the fourth level, I need to systematically assign values. I get an index error, regardless of value assigned, when the fourth level is in the middle of its first loop, as you can see in the output bel...
assigning values in a nested list using for loops in python
I need to create a nested list, four levels deep. On the fourth level, I need to systematically assign values. I get an index error, regardless of value assigned, when the fourth level is in the middle of its first loop, as you can see in the output below the code. fourNest = [ [[[[[AA, BB, CC, DD] for AA i...
[ "The order of the loops in the LC needs to be reversed. You also have one level of extra brackets in there\nfourNest = [[[[[AA, BB, CC, DD]\n for DD in range(5)]\n for CC in range(4)] \n for BB in range(3)]\n for AA in range(2)]\n\n", ">>> fourNest[0][0][0][0]\n[[0, 0, 0, 0], [1, 0, 0, 0]]\...
[ 1, 0 ]
[]
[]
[ "for_loop", "list", "nested", "python", "variable_assignment" ]
stackoverflow_0007003821_for_loop_list_nested_python_variable_assignment.txt
Q: Python - Have parent thread handle child threads Exception Is there a way to have the parent that spawned a new thread catch the spawned threads exception? Below is a real basic example of what I am trying to accomplish. It should stop counting when Exception is raised, but I don't know how to catch it. Are exc...
Python - Have parent thread handle child threads Exception
Is there a way to have the parent that spawned a new thread catch the spawned threads exception? Below is a real basic example of what I am trying to accomplish. It should stop counting when Exception is raised, but I don't know how to catch it. Are exceptions thread safe? I would love to be able to use the Subproc...
[ "Why not something like this\ndef test(): \n def exeption_cb():\n os._exit()\n test = thread.start_new_thread(watchdog, (5, exception_cb))\n os.system('count_to_10.exe')\n print('Stopped Counting')\n\ndef watchdog(timeout, callback):\n time.sleep(timeout)\n callback()\n\nThis will stop the ...
[ 3, 2, 2, 1 ]
[]
[]
[ "exception", "multithreading", "parent_child", "python", "watchdog" ]
stackoverflow_0006866900_exception_multithreading_parent_child_python_watchdog.txt
Q: comparing 2 large unsorted CSV files based on 2 columns I am tasks with comparing 2 large unsorted .csv files based on column 1 and 3. Each file contains about 200k records. For the output, I need to know which records based on column 1 and 3 exist in the first file but not the second file. The files are quoted co...
comparing 2 large unsorted CSV files based on 2 columns
I am tasks with comparing 2 large unsorted .csv files based on column 1 and 3. Each file contains about 200k records. For the output, I need to know which records based on column 1 and 3 exist in the first file but not the second file. The files are quoted comma separated value files. Column 3 needs to ignore case when...
[ "Try:\njoin -v 1 -i -t, -1 1 -2 1 -o 1.2 1.3 1.4 1.5 <(awk -F, '{print $1\":\"$3\",\"$0}' f1.txt | sort) <(awk -F, '{print $1\":\"$3\",\"$0}' f2.txt | sort)\n\nHow it works:\n1) I first create a composite key column, by joining column 1 and column3:\nawk -F, '{print $1\":\"$3\",\"$0}' f1.txt\nawk -F, '{print $1\":...
[ 1, 0, 0, 0, 0 ]
[]
[]
[ "awk", "csv", "java", "python", "shell" ]
stackoverflow_0006999705_awk_csv_java_python_shell.txt
Q: py2app with postgres/psycopg2 So I'm trying to use py2app for my project. Now I don't get any errors from py2app. It is writing near the end the following: /usr/bin/strip: for architecture x86_64 object: /Users/bogdan/Documents/TVB/tvb-root/gemenos/trunk/dist/run.app/Contents/Frameworks/libgfortran.2.dylib malfor...
py2app with postgres/psycopg2
So I'm trying to use py2app for my project. Now I don't get any errors from py2app. It is writing near the end the following: /usr/bin/strip: for architecture x86_64 object: /Users/bogdan/Documents/TVB/tvb-root/gemenos/trunk/dist/run.app/Contents/Frameworks/libgfortran.2.dylib malformed object (load command 3 cmdsize ...
[ "This may help!! I just struggled through the same problem.\nFound this site: (not in english unfortunately, but it worked for me)\nhttp://bancaldo.altervista.org/2011/07/py2exe-errori-post-freeze/\nWhat I did was to add an include to my .py\nFor MS SQL\nfrom sqlalchemy.dialects.mssql.base import dialect\n\nOr for...
[ 2 ]
[]
[]
[ "psycopg2", "py2app", "python" ]
stackoverflow_0006664192_psycopg2_py2app_python.txt
Q: web server returns "500 Internal Server Error" after sending this FormRequest using Scrapy I construct the following FormRequest according to httpFox(Firefox addon)'s content. However, web server alway returns "500 Internal Server Error". Could someone help me on this? The original url is: http://www.intel.com/j...
web server returns "500 Internal Server Error" after sending this FormRequest using Scrapy
I construct the following FormRequest according to httpFox(Firefox addon)'s content. However, web server alway returns "500 Internal Server Error". Could someone help me on this? The original url is: http://www.intel.com/jobs/jobsearch/index_ne.htm?Location=200000008 Here is my spider's skeleton: class IntelSpider(Ba...
[ "Your problem is from intel webpage, not from scrapy.\nbut...\nForms usually have some hidden fields,the best way to make POST request is like this:\ndef start_requests(self,response): \n req_china = FormRequest.from_response(response=response, \n formdata={\n ...
[ 2 ]
[]
[]
[ "python", "scrapy" ]
stackoverflow_0004008371_python_scrapy.txt
Q: multiprocessing not creating new processes The multiprocessing module in Python 3.2.1 on Windows 7 x86 seems to be defeating me. I have two modules: servmain.py and sslserver.py. The idea is to (eventually) code an application which will communicate with clients using SSL. This is the part I already have down....
multiprocessing not creating new processes
The multiprocessing module in Python 3.2.1 on Windows 7 x86 seems to be defeating me. I have two modules: servmain.py and sslserver.py. The idea is to (eventually) code an application which will communicate with clients using SSL. This is the part I already have down. However, I need the server listener to be spun...
[ "I think I am missing a few libraries here so I had to remove your logger code because it was a problem for me. To me it would seem that you have a naming/pathing conflict. Please be sure the name 'sslserver' does not collide with any modules in python path. \nAlso, set python path! In my example both of these file...
[ 1 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0007004397_multiprocessing_python.txt
Q: A way to store sensitive data to disk, without (serious) fear of user tampering? I'm writing an application that connects to twitter and uses the OAuth API, my issue is with storing the consumer_key and the consumer_key_secret How can I safely store these values so they're difficult for the user to get to but stil...
A way to store sensitive data to disk, without (serious) fear of user tampering?
I'm writing an application that connects to twitter and uses the OAuth API, my issue is with storing the consumer_key and the consumer_key_secret How can I safely store these values so they're difficult for the user to get to but still have ability to use them within my application? I've had storing them within a pyc a...
[ "An alternative to DRM (which is what you are describing) is to proxy the secured interaction through a server application on your own, controlled machine. Since you're using OAuth, you can use the same authentication credentials against your own server as you would connecting directly to twitter.\nThe advantage t...
[ 1, 0 ]
[]
[]
[ "credentials", "encryption", "python" ]
stackoverflow_0006770610_credentials_encryption_python.txt
Q: Determine whether for loop is iterating over a list or a generator Is there a way to tell whether, in python, you are iterating through a list or a generator? for i in range(10): print some_param # will identify as a list for i in xrange(10): print some_param # will identify as a generator A: ...
Determine whether for loop is iterating over a list or a generator
Is there a way to tell whether, in python, you are iterating through a list or a generator? for i in range(10): print some_param # will identify as a list for i in xrange(10): print some_param # will identify as a generator
[ "In general, no. You can do unpleasant things like isinstance(my_iterable, type(iter(xrange(1)))) vs isinstance(my_iterable, type(iter([]))), but with the bare iterator interface, generators and lists are indistinguishable to their clients.\n" ]
[ 6 ]
[]
[]
[ "python" ]
stackoverflow_0007004826_python.txt
Q: can I use the django comments framework without an attached parent model? I'd like to use the Django comments framework (or something similar) to easily enable comments for my site. According to the Django documentation, a comment thread must be associated with a parent object that is a Django model. (https://docs...
can I use the django comments framework without an attached parent model?
I'd like to use the Django comments framework (or something similar) to easily enable comments for my site. According to the Django documentation, a comment thread must be associated with a parent object that is a Django model. (https://docs.djangoproject.com/en/dev/ref/contrib/comments/). However, most of my views are...
[ "Why not using the URL as the model? You can even write a middleware that creates an Url instance upon a page request, if it does not exist yet.\n" ]
[ 2 ]
[]
[]
[ "comments", "django", "python" ]
stackoverflow_0007004887_comments_django_python.txt
Q: pygame error: DLL load failed (Win32) I am running Windows 7 64-bit, and I have Python 2.6.7 32-bit installed, as well as pygame 1.9.1 for win-32. However, when I import the pygame module, I get the following error: import pygame ImportError: DLL load failed: %1 is not a valid Win32 application. A: Try using th...
pygame error: DLL load failed (Win32)
I am running Windows 7 64-bit, and I have Python 2.6.7 32-bit installed, as well as pygame 1.9.1 for win-32. However, when I import the pygame module, I get the following error: import pygame ImportError: DLL load failed: %1 is not a valid Win32 application.
[ "Try using the 64 bit versions of pygame, as well as a 64bit build of python.\nhttp://www.lfd.uci.edu/~gohlke/pythonlibs/#pygame\n" ]
[ 4 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0007004918_pygame_python.txt
Q: Extracting contents of a string within parentheses I have the following string: string = "Will Ferrell (Nick Halsey), Rebecca Hall (Samantha), Michael Pena (Frank Garcia)" I would like to create a list of tuples in the form of [(actor_name, character_name),...] like so: [(Will Ferrell, Nick Halsey), (Rebecca Hal...
Extracting contents of a string within parentheses
I have the following string: string = "Will Ferrell (Nick Halsey), Rebecca Hall (Samantha), Michael Pena (Frank Garcia)" I would like to create a list of tuples in the form of [(actor_name, character_name),...] like so: [(Will Ferrell, Nick Halsey), (Rebecca Hall, Samantha), (Michael Pena, Frank Garcia)] I am curren...
[ "string = \"Will Ferrell (Nick Halsey), Rebecca Hall (Samantha), Michael Pena (Frank Garcia)\"\n\nimport re\npat = re.compile(r'([^(]+)\\s*\\(([^)]+)\\)\\s*(?:,\\s*|$)')\n\nlst = [(t[0].strip(), t[1].strip()) for t in pat.findall(string)]\n\nThe compiled pattern is a bit tricky. It's a raw string, to make the back...
[ 8, 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007004868_python.txt
Q: Django unzip a file, add contents to database I am trying to create a system that enables the admin to upload a zipfile, then the script will automatically, using signals, unzip it, search for all the files in jpg,png. create a list of them and generate a database record according to it. In models, i have Projec...
Django unzip a file, add contents to database
I am trying to create a system that enables the admin to upload a zipfile, then the script will automatically, using signals, unzip it, search for all the files in jpg,png. create a list of them and generate a database record according to it. In models, i have Project and Photo table, Photo has Many-to-One aka Foreig...
[ "django-photologue has something extractly what you want, and they created a similiar hack to upload zipfile.\nLink: http://code.google.com/p/django-photologue/ incase you don't want to google\nEvenmore, the zip uploading class is GalleryUpload(models.Model)\n", "for root, dirs, files in os.walk(file_path):\n\nfi...
[ 2, 1 ]
[]
[]
[ "database", "django", "os.walk", "python" ]
stackoverflow_0006997108_database_django_os.walk_python.txt
Q: Auto-generate methods for subclasses I have a few dozen classes. Here are two of them: class Class_A(ClassABC): def __init__(self): super().__init__() def from_B(self, b): #do stuff def from_C(self, c): #do stuff #... def to_B(self): rt = Class_B() ...
Auto-generate methods for subclasses
I have a few dozen classes. Here are two of them: class Class_A(ClassABC): def __init__(self): super().__init__() def from_B(self, b): #do stuff def from_C(self, c): #do stuff #... def to_B(self): rt = Class_B() rt.from_A(self) return rt def...
[ "First of all, your to_* methods aren't going to work because you need to explicitly include self at the beginning of the argument list to be able to use it in the method body. Secondly, I'd go with something akin to JBernardo's suggestion.\ndef to_class(self, cls):\n rt = cls()\n rt.from_class(self.__class__...
[ 0 ]
[]
[]
[ "generative_programming", "python", "python_3.x" ]
stackoverflow_0007003544_generative_programming_python_python_3.x.txt
Q: Adding a theme to Sphinx documentation I am trying to add some theme/template design to my documentation and I was wondering if there was any way to add a line of HTML on line 20 of every HTML page generated by Sphinx? A: You can build a custom theme (consider simply copying a default theme) and modify/override ...
Adding a theme to Sphinx documentation
I am trying to add some theme/template design to my documentation and I was wondering if there was any way to add a line of HTML on line 20 of every HTML page generated by Sphinx?
[ "You can build a custom theme (consider simply copying a default theme) and modify/override the appropriate template files. What exactly do you want to accomplish?\n" ]
[ 1 ]
[]
[]
[ "python", "python_sphinx" ]
stackoverflow_0006904296_python_python_sphinx.txt
Q: QApplication in threads I'm using a module named spynner with python. spynner runs on a QApplication instance. I need to run functions using spynner asynchronously. I have tried calling these functions in different threads, using something like: thread.start_new_thread(function_using_spynner) This works if I run ...
QApplication in threads
I'm using a module named spynner with python. spynner runs on a QApplication instance. I need to run functions using spynner asynchronously. I have tried calling these functions in different threads, using something like: thread.start_new_thread(function_using_spynner) This works if I run just one function, but if I t...
[ "You could run function_using_spynner in the main thread and do whatever else you need to do in the other thread. Alternatively, you could start the QApplication in spynner in the main thread before branching into multiple threads.\n" ]
[ 0 ]
[]
[]
[ "asynchronous", "python", "qt", "spynner" ]
stackoverflow_0007004709_asynchronous_python_qt_spynner.txt
Q: Help with custom Jinja2 Extension I've struggled to get this Jinja2 custom extension to work -- the docs weren't kidding when they said writing one was not for "civilians" -- and finally managed to arrive at this working code: class WrapperExtension(Extension): tags = set(['wrap']) def parse(self, parser...
Help with custom Jinja2 Extension
I've struggled to get this Jinja2 custom extension to work -- the docs weren't kidding when they said writing one was not for "civilians" -- and finally managed to arrive at this working code: class WrapperExtension(Extension): tags = set(['wrap']) def parse(self, parser): lineno = parser.stream.next(...
[ "The reason is that parse() is expected to return a statement node, such as CallBlock or Assign. call_method() returns an expression node, which you must wrap in CallBlock to have a statement.\n" ]
[ 4 ]
[]
[]
[ "jinja2", "python" ]
stackoverflow_0005972458_jinja2_python.txt
Q: Why does Elixir/SQLAlchemy's session.bind get set to None within threads? I'll start with some simplified test code to demonstrate the issue I'm referencing. t_model.py from elixir import * metadata.bind = 'sqlite:///test.db' session.bind = metadata.bind t_main.py #!/usr/bin/python import t_model import threa...
Why does Elixir/SQLAlchemy's session.bind get set to None within threads?
I'll start with some simplified test code to demonstrate the issue I'm referencing. t_model.py from elixir import * metadata.bind = 'sqlite:///test.db' session.bind = metadata.bind t_main.py #!/usr/bin/python import t_model import threading class TestThread(threading.Thread): def run(self): print '...
[ "Try replacing this:\nsession.bind = metadata.bind\n\nwith:\nsession.configure(bind=metadata.bind)\n\n" ]
[ 1 ]
[]
[]
[ "multithreading", "python", "python_elixir", "sqlalchemy" ]
stackoverflow_0007004169_multithreading_python_python_elixir_sqlalchemy.txt
Q: Using unitialized variables in Python Background: I have a class modeling a chip with registers, the chip has a bunch of registers, one of them is a high temperature limit for the built-in temperature sensor. I have the following: class foo(): def __init__(self): # does not set self._hiTemp! ... def se...
Using unitialized variables in Python
Background: I have a class modeling a chip with registers, the chip has a bunch of registers, one of them is a high temperature limit for the built-in temperature sensor. I have the following: class foo(): def __init__(self): # does not set self._hiTemp! ... def setHiTemp(self, t): self._hiTemp = t de...
[ "The way I'd do it is set it to None or some other sentinel value that doesn't occur 'in nature'. Then for operations that require it to be set, use an assert to fail fast in case the caller is trying to use your object inappropriately.\ndef __init__(self):\n self._hiTemp = None\n\ndef checkHiTemp(self):\n a...
[ 12, 6, 1, 0, 0 ]
[]
[]
[ "initialization", "pylint", "python" ]
stackoverflow_0007005072_initialization_pylint_python.txt
Q: py2exe - Can no longer Copy/Paste text from other Windows app to my Python app after converting my python script to a .EXE file I recently tried to convert one of my python scripts (used for file-systems I/O) to a executable file by using py2exe. However, after successfully generating the .exe file from my python...
py2exe - Can no longer Copy/Paste text from other Windows app to my Python app after converting my python script to a .EXE file
I recently tried to convert one of my python scripts (used for file-systems I/O) to a executable file by using py2exe. However, after successfully generating the .exe file from my python script, I am no longer able to copy and paste any text(or anything for that matter) from other windows apps to my python app console...
[ "Right-clicking a console window is a \"special feature\" of the command line interpreter of Windows Vista and above. It doesn't work on any other command-line tool, so it doesn't longer works for your converted script. You can still access it using the windows menu (small icon in the title bar or Alt+Space).\nYou ...
[ 7 ]
[]
[]
[ "console", "copy_paste", "py2exe", "python" ]
stackoverflow_0007004772_console_copy_paste_py2exe_python.txt
Q: Sending/Receiving E-mail with Python smtpd module I'm trying to make a simple smtp server using the Python smtpd module. I can receive an e-mail and print it out. I try to send an e-mail back to the person who sent me the e-mail with a hello world message and I end up with an infinite loop. I try to use my own ser...
Sending/Receiving E-mail with Python smtpd module
I'm trying to make a simple smtp server using the Python smtpd module. I can receive an e-mail and print it out. I try to send an e-mail back to the person who sent me the e-mail with a hello world message and I end up with an infinite loop. I try to use my own server to send the e-mail and it just interprets it as ano...
[ "You're not supposed to send the message to yourself...\nPerform a MX lookup and send the message to the appropriate SMTP server.\n" ]
[ 1 ]
[]
[]
[ "python", "smtpd", "smtplib" ]
stackoverflow_0007005647_python_smtpd_smtplib.txt
Q: Are there comment system/user loggin type modules through PHP API/Python API outside of CMS? I'm primarily using Drupal and am considering moving away from CMS. If I were to build my own platform could I integrate modules like commenting systems, user login, etc. through a PHP/Python API? What would be the prope...
Are there comment system/user loggin type modules through PHP API/Python API outside of CMS?
I'm primarily using Drupal and am considering moving away from CMS. If I were to build my own platform could I integrate modules like commenting systems, user login, etc. through a PHP/Python API? What would be the proper steps/good places to look/good tutorial on this? Would I have to build all of my own tables man...
[ "You can drop the Disqus commenting system into any site. Same with Facebook Comments.\n", "First of all if you are considering moving away from CMS than you should consider using some sort of framework but with time you will come to idea that you need your own shit in order to be satisfied.\nSecond, subject you ...
[ 0, 0, 0 ]
[]
[]
[ "php", "python" ]
stackoverflow_0007006013_php_python.txt
Q: Translate the intent of this PHP regex for multiline strings, into Python/PERL Below is a PHP regex intended to match (multiline) strings inside PHP or JavaScript source code (from this post), but I suspect it's got issues. What is the literal Python (or else PERL) equivalent of this? ~'(\\.|[^'])*'|"(\\.|[^"])*"~...
Translate the intent of this PHP regex for multiline strings, into Python/PERL
Below is a PHP regex intended to match (multiline) strings inside PHP or JavaScript source code (from this post), but I suspect it's got issues. What is the literal Python (or else PERL) equivalent of this? ~'(\\.|[^'])*'|"(\\.|[^"])*"~s the s modifier means dot matches all characters, including newline; in Python th...
[ "The \\\\. is meant to match a literal backslash in the pattern, and swallow the following character. Note that since patterns in PHP (and Python) are contained in strings, it would actually need to be \\\\\\\\. in the string, so that it ends up as \\\\. in the regex.\nIt's important to match the backslash and swal...
[ 2, 1 ]
[]
[]
[ "multiline", "php", "python", "regex" ]
stackoverflow_0007004023_multiline_php_python_regex.txt
Q: Is there a better way to implement this? I'm writing a calculator in Python (as an exercise), and there's one bit that I'm wondering about. The program splits up the input into a list of numbers and operators. The result is then computed thusly: import operator ops = {'+' : operator.add, # op...
Is there a better way to implement this?
I'm writing a calculator in Python (as an exercise), and there's one bit that I'm wondering about. The program splits up the input into a list of numbers and operators. The result is then computed thusly: import operator ops = {'+' : operator.add, # operators and corresponding functions '-'...
[ "You can manipulate the index if you use a while loop instead\ndef evaluate(exp):\n for oplist in precedence: # search for operators first in order of precedence\n idx = 0\n while idx < len(exp):\n op = exp[idx]\n if op in oplist:\n result = ops[op](exp[idx - 1...
[ 3, 3, 2 ]
[]
[]
[ "calculator", "implementation", "python" ]
stackoverflow_0007005732_calculator_implementation_python.txt
Q: Getting started about writing documentation for django application I would like to write a documentation for one of my Django based project. I found that Django people uses reStructureText and Sphinx for this purpose. I have following queries. How do I get started with writing documentations using reStructureText...
Getting started about writing documentation for django application
I would like to write a documentation for one of my Django based project. I found that Django people uses reStructureText and Sphinx for this purpose. I have following queries. How do I get started with writing documentations using reStructureText and Sphinx? What best practices should I follow so that documentation r...
[ "Documentation of sphinx is here: https://www.sphinx-doc.org\n\nYou start by running sphinx-quickstart.\n\"Well organized\" is really your own matter. This depends on your taste and your project.\n\"Easy to manage\": include doctests in your code documentation and autodoc in you sphinx setup. This way you can alway...
[ 4 ]
[]
[]
[ "django", "python", "python_sphinx", "restructuredtext" ]
stackoverflow_0007006453_django_python_python_sphinx_restructuredtext.txt
Q: Problem with the Alt key in macro recorder I am writing a macro recorder (based on PyHook) and cannot make it to press key combination #2 after it hooked key combination #1, if #1 contains the Alt key. What else should I do besides unpressing modifier keys? (alt, ctrl, shift)? Below are two main functions. def pre...
Problem with the Alt key in macro recorder
I am writing a macro recorder (based on PyHook) and cannot make it to press key combination #2 after it hooked key combination #1, if #1 contains the Alt key. What else should I do besides unpressing modifier keys? (alt, ctrl, shift)? Below are two main functions. def press_key(Key, gModifiers = []): keybd_event(Ke...
[ "Changing code fragment from\nkeybd_event(KeyDict[\"alt\"], 0, KEYEVENTF_KEYUP, 0)\nkeybd_event(KeyDict[\"ctrl\"], 0, KEYEVENTF_KEYUP, 0)\nkeybd_event(KeyDict[\"shift\"], 0, KEYEVENTF_KEYUP, 0)\n\nto\nkeybd_event(KeyDict[\"ctrl\"], 0, KEYEVENTF_KEYUP, 0)\nkeybd_event(KeyDict[\"shift\"], 0, KEYEVENTF_KEYUP, 0)\nkeyb...
[ 0 ]
[]
[]
[ "keyboard_hook", "python" ]
stackoverflow_0007005613_keyboard_hook_python.txt
Q: Perl or Python SVN Crawler Is there an SVN crawler, that can walk thru an SVN repo and spitt out all existing branches, or tags? Preferably in Perl or Python ... A: SVN tags and branches are just directories, usually following a particular naming convention. You can easily get them in perl like: my @branches = ...
Perl or Python SVN Crawler
Is there an SVN crawler, that can walk thru an SVN repo and spitt out all existing branches, or tags? Preferably in Perl or Python ...
[ "SVN tags and branches are just directories, usually following a particular naming convention. You can easily get them in perl like:\nmy @branches = `svn ls YourRepoBaseURL/branches`;\nchomp @branches; # remove newlines\nchop @branches; # remove trailing /\nmy @tags = `svn ls YourRepoBaseURL/tags`;\nchomp @tags;\n...
[ 6, 1, 0 ]
[]
[]
[ "perl", "python", "svn", "web_crawler" ]
stackoverflow_0006908751_perl_python_svn_web_crawler.txt
Q: Is it possible for a method of a class to be invoked first before the init constructor? My class: from django.contrib.admin.views.main import ChangeList class MyChangeList(ChangeList): def __init__(self, *args): ... def get_query_set(self): ... I added logs in both __init__ and get_query_...
Is it possible for a method of a class to be invoked first before the init constructor?
My class: from django.contrib.admin.views.main import ChangeList class MyChangeList(ChangeList): def __init__(self, *args): ... def get_query_set(self): ... I added logs in both __init__ and get_query_set and I have noticed that the log output in the latter gets printed out (but none for the o...
[ "The __init__ function can call arbitrary methods itself, and construction of objects in Python can also be complicated with __new__, so make sure both outputs refer to the same object (for example, by including id(self) in the output).\nTo find out who called get_query_set, you can use traceback.print_stack:\nimpo...
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0007006763_python.txt
Q: PyXPCOM component not loading in XULRunner I'm planning to create XULRunner based application that need to interface with Python. The plan is to use PyXPCOM. Currently I'm teaching myself in using PyXPCOM and going through the example component developmnet in Creating a Python XPCOM component but can't get it to w...
PyXPCOM component not loading in XULRunner
I'm planning to create XULRunner based application that need to interface with Python. The plan is to use PyXPCOM. Currently I'm teaching myself in using PyXPCOM and going through the example component developmnet in Creating a Python XPCOM component but can't get it to work. I'm using Ubuntu 11.04 and my steps were: ...
[ "The error message indicates that createInstance() call resulted in an error. The good news: this means that everything preceding createInstance() succeeded (PyXPCOM is working and the component was loaded/registered correctly). http://code.google.com/p/pythonext/source/browse/samples/pyshell/components/pyShell.py ...
[ 1 ]
[]
[]
[ "firefox", "python", "pyxpcom", "xpcom", "xulrunner" ]
stackoverflow_0006853595_firefox_python_pyxpcom_xpcom_xulrunner.txt
Q: Is there a convenient way to detect unittests that are causing external calls? I have all of these tests in Django for code uses various third party APIs which I'm of course mocking, but some of the code is old and sometimes people make mistakes. I'd like the code to yell loudly when it makes an external call if p...
Is there a convenient way to detect unittests that are causing external calls?
I have all of these tests in Django for code uses various third party APIs which I'm of course mocking, but some of the code is old and sometimes people make mistakes. I'd like the code to yell loudly when it makes an external call if possible, so that I can figure out which of the 100s of dots that mark passing tests ...
[ "I'm not sure about detecting external calls, but what you can do, is timing test execution times and then checking the slower tests.\nYou could use nose + the pinnocchio plugin, to time your tests.\nThis also seems interesting: http://blog.mahmoudimus.com/2011/02/developing-a-nose-test-plugin-to-time-python-tests/...
[ 1 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0007006961_python_unit_testing.txt
Q: os.path equivalent for web urls in python? For joining, splitting and processing file and directory paths python's os.path modul is great. Is there an equivalent for web urls? A: urlparse - Parse URLs into components, is the module for you.. To actually fetch urls & data, you need urllib2. A: Hope this help : ...
os.path equivalent for web urls in python?
For joining, splitting and processing file and directory paths python's os.path modul is great. Is there an equivalent for web urls?
[ "urlparse - Parse URLs into components, is the module for you..\nTo actually fetch urls & data, you need urllib2.\n", "Hope this help : \nhttp://docs.python.org/library/urlparse.html\nhttp://docs.python.org/library/urllib2.html\n" ]
[ 13, 3 ]
[]
[]
[ "path", "python", "url" ]
stackoverflow_0007007496_path_python_url.txt
Q: Simple idiom to break an n-long list into k-long chunks, when n % k > 0? In Python, it is easy to break an n-long list into k-size chunks if n is a multiple of k (IOW, n % k == 0). Here's my favorite approach (straight from the docs): >>> k = 3 >>> n = 5 * k >>> x = range(k * 5) >>> zip(*[iter(x)] * k) [(0, 1, 2)...
Simple idiom to break an n-long list into k-long chunks, when n % k > 0?
In Python, it is easy to break an n-long list into k-size chunks if n is a multiple of k (IOW, n % k == 0). Here's my favorite approach (straight from the docs): >>> k = 3 >>> n = 5 * k >>> x = range(k * 5) >>> zip(*[iter(x)] * k) [(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11), (12, 13, 14)] (The trick is that [iter(x...
[ "[x[i:i+k] for i in range(0,n,k)]\n\n", "sentinal = object()\nsplit = ( \n (v for v in r if v is not sentinal) for r in\n izip_longest(*[iter(x)]*n, fillvalue=sentinal))\n\nOf course, the better idiom is to call a function as that'll be more readable then anything that'll do the same thing.\n", "from IPyt...
[ 15, 3, 3, 1 ]
[]
[]
[ "map_function", "python", "python_itertools" ]
stackoverflow_0007005323_map_function_python_python_itertools.txt
Q: Will Django be a good choice for a permissions based web-app? I've been exploring the details of Django for about a week now and like what I see. However I've come upon some.. negativity in relation to fine-grained control of permissions to the CRUD interface. What I'm writing is an Intranet client management web-...
Will Django be a good choice for a permissions based web-app?
I've been exploring the details of Django for about a week now and like what I see. However I've come upon some.. negativity in relation to fine-grained control of permissions to the CRUD interface. What I'm writing is an Intranet client management web-app. The organisation is about 6 tiers, and I need to restrict acce...
[ "If I read your updated requirements correctly, I don't think Django's existing auth system will be sufficient. It sounds like you need a full-on ACL system.\nThis subject has come up a number of times. Try googling on django+acl.\nRandom samplings ...\nThere was a Summer of Code project a couple of years ago, but ...
[ 8, 4, 3, 2, 0, 0 ]
[]
[]
[ "django", "permissions", "python" ]
stackoverflow_0000232008_django_permissions_python.txt
Q: Alternative to list comprehension if there will be only one result I'm starting to get used to list comprehension in Python but I'm afraid I'm using it somewhat improperly. I've run into a scenario a few times where I'm using list comprehension but immediately taking the first (and only) item from the list that i...
Alternative to list comprehension if there will be only one result
I'm starting to get used to list comprehension in Python but I'm afraid I'm using it somewhat improperly. I've run into a scenario a few times where I'm using list comprehension but immediately taking the first (and only) item from the list that is generated. Here is an example: actor = [actor for actor in self.actor...
[ "You could use a generator expression and next instead. This would be more efficient as well, since an intermediate list is not created and iteration can stop once a match has been found:\nactor = next(actor for actor in self.actors if actor.name==actorName)\n\nAnd as senderle points out, another advantage to this ...
[ 131, 28, 2, 1 ]
[]
[]
[ "list_comprehension", "python" ]
stackoverflow_0007006839_list_comprehension_python.txt
Q: How do get the same effect as python's raw_input() in Perl? Python's raw_input() preserves all bash features like arrow keys and reverse searching... But when I use Perl's <> to read from stdin,none of the features are supported any more... What's the easiest way to do it as raw_input in Perl? A: According to th...
How do get the same effect as python's raw_input() in Perl?
Python's raw_input() preserves all bash features like arrow keys and reverse searching... But when I use Perl's <> to read from stdin,none of the features are supported any more... What's the easiest way to do it as raw_input in Perl?
[ "According to the Python docs,\n\nIf the readline module was loaded, then raw_input() will use it to provide elaborate line editing and history features.\n\nAs stated in comments to the original post, you need to use an appropriate module, such as Term::ReadLine or Term::ReadLine::Gnu, to access those features. Th...
[ 5 ]
[]
[]
[ "perl", "python" ]
stackoverflow_0007006034_perl_python.txt
Q: Python: Getting files into an archive without the directory? I've been learning python for about 3 weeks now, and I'm currently trying to write a little script for sorting files (about 10.000) by keywords and date appearing in the filename. Files before a given date should be added to an archive. The sorting works...
Python: Getting files into an archive without the directory?
I've been learning python for about 3 weeks now, and I'm currently trying to write a little script for sorting files (about 10.000) by keywords and date appearing in the filename. Files before a given date should be added to an archive. The sorting works fine, but not the archiving It creates an archive - the name is f...
[ "From help(zipfile):\n | write(self, filename, arcname=None, compress_type=None)\n | Put the bytes from filename into the archive under the name\n | arcname.\n\nSo try changing your write() call with:\nx.write(folder + '/' + item + '/' + f, arcname = f)\n\nAbout your code, it seems to me good enough, esp...
[ 21 ]
[]
[]
[ "python", "zip" ]
stackoverflow_0007007868_python_zip.txt
Q: How can I debug Python code without running a script (using Eclipse)? I've noticed how easy it is to debug a Python script from Eclipse. Simply set breakpoints and run a Python script from the debug menu. But is it possible to start a Python Interactive Interpreter instead of running a particular Python script, wh...
How can I debug Python code without running a script (using Eclipse)?
I've noticed how easy it is to debug a Python script from Eclipse. Simply set breakpoints and run a Python script from the debug menu. But is it possible to start a Python Interactive Interpreter instead of running a particular Python script, whilst still having Eclipse breaking on breakpoints? This would make it so mu...
[ "You can explicitly write code to setup a breakpoint in your script, and then \"remote debug\". That means having pydevd in the pythonpath of your script wherever it is running, and running the eclipse pydev remote debugger on your devbox. If it's all happening on the same machine, this is fairly straightforward.\n...
[ 2, 0 ]
[]
[]
[ "aptana", "debugging", "eclipse", "python" ]
stackoverflow_0007000138_aptana_debugging_eclipse_python.txt
Q: How do I make setuptools set the executable bit when deploying some supporting binaries with my egg? I'm using setuptools to create an egg and I would like to include some supporting binaries with it, preferably to be installed in the egg directory. I can include these files with data_files or package_data however...
How do I make setuptools set the executable bit when deploying some supporting binaries with my egg?
I'm using setuptools to create an egg and I would like to include some supporting binaries with it, preferably to be installed in the egg directory. I can include these files with data_files or package_data however the executable bit is not set when they are deployed. Alternatively, I can use scripts but then they will...
[ "The usual (standard) place to put supporting binaries in Linux is in /usr/libexec. So you can make a directory under that with the the data_files option. Make the files +x in your source and the permissions should be preserved. Just put something like\ndata_files=[(os.path.join(sys.prefix, 'libexec', 'myproject'),...
[ 3 ]
[]
[]
[ "linux", "python", "setuptools" ]
stackoverflow_0007007985_linux_python_setuptools.txt
Q: python random.sample stop sampling after all possible outcomes I am using random.sample to sample all possible combinations of sets of data (about 150 sets). The sample sizes I will be testing are 3,4 and 5 and the sets of data range between 2 and 20 items. Each data point will be a string e.g. '101A'. I was goin...
python random.sample stop sampling after all possible outcomes
I am using random.sample to sample all possible combinations of sets of data (about 150 sets). The sample sizes I will be testing are 3,4 and 5 and the sets of data range between 2 and 20 items. Each data point will be a string e.g. '101A'. I was going to just loop the random sampling 1000 times and store the points a...
[ "With not use standard library?\n>>> import itertools\n>>> dataset = ['1','2','3A','4']\n>>> list(itertools.combinations(dataset, 3))\n[('1', '2', '3A'), ('1', '2', '4'), ('1', '3A', '4'), ('2', '3A', '4')]\n\n", "If you can enumerate all combinations and put them in a list\na = [ list of all combinations ]\n\nYo...
[ 5, 0 ]
[]
[]
[ "dictionary", "python", "random" ]
stackoverflow_0007008511_dictionary_python_random.txt
Q: Pythonic way to set sort order? I have a collection on objects that I need to assign a random order. I wrote a pretty dumb java style loop to do it, but what is a fancier pythonic way to achieve the same? from random import shuffle class pair(object): def __init__(self, name): self.name = name ...
Pythonic way to set sort order?
I have a collection on objects that I need to assign a random order. I wrote a pretty dumb java style loop to do it, but what is a fancier pythonic way to achieve the same? from random import shuffle class pair(object): def __init__(self, name): self.name = name self.order = 0 def __repr__(sel...
[ "This isn't a lot simpler than yours, but it's perhaps a little bit neater:\nfor i, t in enumerate(test):\n t.order = i\n\n", "[ x.order = o for o, x in enumerate(test) ]\n\n" ]
[ 6, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006999749_python.txt
Q: Converting u"string" to "string" in Python without changing encoding I have the following: u'\x96' I want to convert it to the following: '\x96' Is there any way to do this? str() doesn't work, and when using .encode(...) it changes the encoding. My main goal is to be able to get the following result, so any sho...
Converting u"string" to "string" in Python without changing encoding
I have the following: u'\x96' I want to convert it to the following: '\x96' Is there any way to do this? str() doesn't work, and when using .encode(...) it changes the encoding. My main goal is to be able to get the following result, so any shortcut to get there would also be accepted: >>> '\x96'.decode("cp1252") u'\...
[ "u'\\x96'.encode('raw_unicode_escape').decode(\"cp1252\")\n\n", "Latin-1 is the encoding that directly maps the first 256 characters of Unicode to their byte values.\n>>> u'\\x96'.encode('latin-1').decode(\"cp1252\")\nu'\\u2013'\n\n" ]
[ 6, 3 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0007008668_python_unicode.txt
Q: Query when parameter is none django I want to make a query, something like Model.objects.filter(x=x).filter(y=y).filter(z=z) ... but there are some cases when for example y is None. This literally searches the database for null values in the y column -- is there a nifty way to essentially disregard that query p...
Query when parameter is none django
I want to make a query, something like Model.objects.filter(x=x).filter(y=y).filter(z=z) ... but there are some cases when for example y is None. This literally searches the database for null values in the y column -- is there a nifty way to essentially disregard that query parameter if it is none, i.e. return the q...
[ "I do not know, if I get your question, but\nModel.objects.filter(x=x, y__isnull = False, z=z)\n\ngives you the queryset, where the ycolumn is non-null (IS NOT NULL).\nHere's the relevant documentation.\nEDIT: Check if y is None and build your queryset dynamically:\nif y is None:\n qs = Model.objects.filter(x=x)...
[ 19, 5, 4, 2, 0 ]
[]
[]
[ "django", "django_models", "mysql", "python" ]
stackoverflow_0007006862_django_django_models_mysql_python.txt
Q: python and static methods So here is my situation. I have a class ABCAdapter. Here I have declared a bunch of methods and between them I have: @staticmethod def __prepare_param_names(attributes_list, prefix = None): ....some processing.... Now from another class, namely FlowService I do: from tvb.core.adapter...
python and static methods
So here is my situation. I have a class ABCAdapter. Here I have declared a bunch of methods and between them I have: @staticmethod def __prepare_param_names(attributes_list, prefix = None): ....some processing.... Now from another class, namely FlowService I do: from tvb.core.adapters.abcadapter import ABCAdapter ...
[ "As you probably know, Python doesn't enforce protected/private attributes: all class attributes are globally accessible. However, there is a convention that attributes whose names start with at least one _ are an implementation detail and not part of the public API.\nDouble-underscored names are a slight hack used...
[ 4, 1, -3 ]
[]
[]
[ "python" ]
stackoverflow_0007008812_python.txt