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: Celery tasks vanishing - Django/Celery here is my code: my task from celery.decorators import task @task() def add(x, y): return x + y using my tasks from core.tasks import add results = [] for i in range(100): results.append(add.delay(i, i)) problem 1 after a few seconds I perform the following: for ...
Celery tasks vanishing - Django/Celery
here is my code: my task from celery.decorators import task @task() def add(x, y): return x + y using my tasks from core.tasks import add results = [] for i in range(100): results.append(add.delay(i, i)) problem 1 after a few seconds I perform the following: for result in results: print result.result ...
[ "The task.delay() is asynchronous. BTW, the whole AMQP thing is about making tasks asynchronous. If you want synchronous behavior, what is the point of using celery?\nfrom celery.decorators import task\n\n@task()\ndef add(x, y, results):\n results.append(x + y)\n\n------------8<-------------\nfrom core.tasks imp...
[ 4 ]
[]
[]
[ "celery", "django", "message_queue", "python" ]
stackoverflow_0004542134_celery_django_message_queue_python.txt
Q: Modifying a Python dictionary from different threads When it comes to threading, I know you have to make sure you're not editing a variable at the same time another thread is editing it, as your changes can be lost (when incrementing a counter, for example) Does the same apply to dictionaries? Or is a dictionary a...
Modifying a Python dictionary from different threads
When it comes to threading, I know you have to make sure you're not editing a variable at the same time another thread is editing it, as your changes can be lost (when incrementing a counter, for example) Does the same apply to dictionaries? Or is a dictionary a collection of variables? If every thread were to lock the...
[ "\nDoes the same apply to dictionaries? Or is a dictionary a collection of variables?\n\nLet's be more general:\nWhat does \"atomic operation\" mean?\nFrom Wikipedia :\n\nIn concurrent programming, an\n operation (or set of operations) is\n atomic, linearizable, indivisible or\n uninterruptible if it appears to ...
[ 26, 8, 0 ]
[]
[]
[ "dictionary", "locking", "multithreading", "python", "variables" ]
stackoverflow_0004542344_dictionary_locking_multithreading_python_variables.txt
Q: Parsing dictionaries within dictionaries For example, I have this Python dictionaries within dictionaries, which is returned JSON object: { u'BrowseNode': { u'Ancestors': { u'BrowseNode': { u'Ancestors': { u'BrowseNode': { u'Ancest...
Parsing dictionaries within dictionaries
For example, I have this Python dictionaries within dictionaries, which is returned JSON object: { u'BrowseNode': { u'Ancestors': { u'BrowseNode': { u'Ancestors': { u'BrowseNode': { u'Ancestors': { u'BrowseNo...
[ "Something like this also works for the given data and it's not recursive:\ndef collect_names( node ):\n names = []\n while True:\n names.append(node[u'Name'])\n try:\n # deeper node\n node = node[u'Ancestors'][u'BrowseNode']\n except KeyError:\n # we are ...
[ 2, 1, 1 ]
[]
[]
[ "dictionary", "json", "python" ]
stackoverflow_0004541051_dictionary_json_python.txt
Q: How to redirect stdout for a subprocess? def StartProc(dir, parm): global proc proc_log = open(dir + os.sep + "MyLog.txt","w") #new path for each file if parm: proc = subprocess.Popen(path, 0, None, subprocess.PIPE, proc_log, None) else: MyReset(proc) #res...
How to redirect stdout for a subprocess?
def StartProc(dir, parm): global proc proc_log = open(dir + os.sep + "MyLog.txt","w") #new path for each file if parm: proc = subprocess.Popen(path, 0, None, subprocess.PIPE, proc_log, None) else: MyReset(proc) #reset the process(proc) to its default values ...
[ "Like unwind said, you cannot change the file descriptor that the child process is writing its output to.\nWhat you can do, is read the output from the child process in your python script and then write it back to whatever file you want to. E.g.:\nproc = subprocess.Popen(path, 0, None, subprocess.PIPE, subprocess.P...
[ 6, 4, 1 ]
[]
[]
[ "python", "stdout", "subprocess" ]
stackoverflow_0002161409_python_stdout_subprocess.txt
Q: Why is there a start argument in Python's built-in sum function? In the sum function, the prototype is sum(iterable[,start]), which sums everything in the iterable object plus the start value. I wonder why there is a start value in here? Is there nay particular use case this value is needed? Please don't give any ...
Why is there a start argument in Python's built-in sum function?
In the sum function, the prototype is sum(iterable[,start]), which sums everything in the iterable object plus the start value. I wonder why there is a start value in here? Is there nay particular use case this value is needed? Please don't give any more examples how start is used. I am wondering why it exist in this f...
[ "If you are summing things that aren't integers you may need to provide a start value to avoid an error.\n>>> from datetime import timedelta\n>>> timedeltas = [timedelta(1), timedelta(2)]\n\n>>> sum(timedeltas)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: unsupported oper...
[ 16 ]
[]
[]
[ "python" ]
stackoverflow_0004543129_python.txt
Q: javascript-aware html parser for Python ~ <html> <head> <script type="text/javascript"> document.write('<a href="http://www.google.com">f*** js</a>'); document.write("f*** js!"); </script> </head> <body> <script type="text/javascript"> document.write('<a href="http://www.google.com">f*** js...
javascript-aware html parser for Python ~
<html> <head> <script type="text/javascript"> document.write('<a href="http://www.google.com">f*** js</a>'); document.write("f*** js!"); </script> </head> <body> <script type="text/javascript"> document.write('<a href="http://www.google.com">f*** js</a>'); document.write("f*** js!"); </s...
[ "Not a clue about javascript-aware parser in python but you can use ANTLR to do the job. The idea is not mine so I'm leaving you the link.\nIt's actually quite cool because you can optimize your parser to selectively choose what instruction needs to be parsed (and executed).\n", "In Java there is Cobra. I don't k...
[ 1, 0, 0 ]
[]
[]
[ "javascript", "lxml", "python" ]
stackoverflow_0004542959_javascript_lxml_python.txt
Q: What is the best way to keep an almost static data for web application? I'm building a web application in python. A part of this application is working with the data that can be described as follows: Symbol Begin Date End Date AAPL Jan-1-1985 Dec-27-2010 ... The data is somewhat static - it wi...
What is the best way to keep an almost static data for web application?
I'm building a web application in python. A part of this application is working with the data that can be described as follows: Symbol Begin Date End Date AAPL Jan-1-1985 Dec-27-2010 ... The data is somewhat static - it will be periodically updated, that is: new entries may be added, and the "End D...
[ "I would generate a Python source file every time the data changes, and have that file primarily consisting of a dictionary. This assumes that lookup is by symbol, and that the data readily fit into memory.\ndata = {\n \"AAPL\": (\"Jan-1-1985\", \"Dec-27-2010\"),\n...\n}\n\nTo bulk-update the end date, ...
[ 3, 1, 0, 0, 0, 0 ]
[]
[]
[ "data_structures", "python", "static" ]
stackoverflow_0004541570_data_structures_python_static.txt
Q: Python PyCrypto and RSA problem I'e got simple RSA python script: import Crypto.PublicKey.RSA import rsakey from Crypto.PublicKey import pubkey # Some global stuff impl = Crypto.PublicKey.RSA.RSAImplementation(use_fast_math = True) RSAObj = impl.construct(rsakey.RSAKeys) def decrypt(encrypted): return RS...
Python PyCrypto and RSA problem
I'e got simple RSA python script: import Crypto.PublicKey.RSA import rsakey from Crypto.PublicKey import pubkey # Some global stuff impl = Crypto.PublicKey.RSA.RSAImplementation(use_fast_math = True) RSAObj = impl.construct(rsakey.RSAKeys) def decrypt(encrypted): return RSAObj.decrypt(encrypted) and when I t...
[ "Crypto.PublicKey.RSA contains a class called RSAImplementation (see http://www.dlitz.net/software/pycrypto/apidoc/Crypto.PublicKey.RSA.RSAImplementation-class.html).\nThe following works for me (in Python 2.7.1 on 32-bit Windows):\nimport Crypto.PublicKey.RSA\nimpl = Crypto.PublicKey.RSA.RSAImplementation()\n\nNot...
[ 3, 0, 0 ]
[]
[]
[ "pycrypto", "python", "rsa" ]
stackoverflow_0004542477_pycrypto_python_rsa.txt
Q: libsvm predict method confusion I have a question about the svm_predict() method in libsvm. The README has this quickstart example code: >>> y, x = [1,-1], [{1:1, 3:1}, {1:-1,3:-1}] >>> prob = svm_problem(y, x) >>> param = svm_parameter('-c 4 -b 1') >>> m = svm_train(prob, param) >>> p_label, p_acc, p_val = svm_...
libsvm predict method confusion
I have a question about the svm_predict() method in libsvm. The README has this quickstart example code: >>> y, x = [1,-1], [{1:1, 3:1}, {1:-1,3:-1}] >>> prob = svm_problem(y, x) >>> param = svm_parameter('-c 4 -b 1') >>> m = svm_train(prob, param) >>> p_label, p_acc, p_val = svm_predict(y, x, m) Now I understand th...
[ "It uses the true labels to give you accuracy statistics in case you are doing an out-of-sample test. \nIf you are running it \"online\", i.e. you actually don't have the true labels, then just put [0]*len(z) instead of y\n", "You might consider using\nhttp://scikit-learn.sourceforge.net/\nThat has a great python...
[ 5, 1 ]
[]
[]
[ "libsvm", "machine_learning", "python" ]
stackoverflow_0004542367_libsvm_machine_learning_python.txt
Q: Problems with Nested Functions THIS TURNED OUT TO BE A SYNTAX ERROR ON MY PART A LINE EARLIER IN THE CODE. Hello, I'm having some trouble with a nested function I wrote in python. Here is the relevant code. device = "/dev/sr0" def burn(): global device burnaudiotrack(device) createiso(device) burntra...
Problems with Nested Functions
THIS TURNED OUT TO BE A SYNTAX ERROR ON MY PART A LINE EARLIER IN THE CODE. Hello, I'm having some trouble with a nested function I wrote in python. Here is the relevant code. device = "/dev/sr0" def burn(): global device burnaudiotrack(device) createiso(device) burntrack2(device) I'm confused, becaus...
[ "You are missing a close parenthesis on line 61.\nLooks like the quote and paren at the end of the line are swapped.\nspeed = raw_input(\"Recomended(4);Default(8))\"\n\nshould be\nspeed = raw_input(\"Recomended(4);Default(8)\")\n\n", "The code you have pasted into your question appears to have tabs as well as spa...
[ 2, 0 ]
[]
[]
[ "function", "nested", "python" ]
stackoverflow_0004543402_function_nested_python.txt
Q: Ideas on how to retrieve and analyze server logs with python? To start off, this desktop app is really to give myself an excuse to learn python and how a gui works. Im trying to help my clients visualize how much bandwidth they are going through, when its happening and where their visitors are. All of this would ...
Ideas on how to retrieve and analyze server logs with python?
To start off, this desktop app is really to give myself an excuse to learn python and how a gui works. Im trying to help my clients visualize how much bandwidth they are going through, when its happening and where their visitors are. All of this would be displayed by graphs or whatever would be most convienient. (Down...
[ "sftp or shelling out to rsync seems like a reasonable way to retrieve the logs. As for parsing them, regular expressions are what most people tend to use. However, there are other approaches, too. For instance:\n\nParse Apache logs to SQLite database\nUsing pyparsing to parse logs. This one is parsing a different ...
[ 1 ]
[]
[]
[ "paramiko", "python", "twisted", "user_interface" ]
stackoverflow_0004543369_paramiko_python_twisted_user_interface.txt
Q: How to sort my paws? In my previous question I got an excellent answer that helped me detect where a paw hit a pressure plate, but now I'm struggling to link these results to their corresponding paws: I manually annotated the paws (RF=right front, RH= right hind, LF=left front, LH=left hind). As you can see there...
How to sort my paws?
In my previous question I got an excellent answer that helped me detect where a paw hit a pressure plate, but now I'm struggling to link these results to their corresponding paws: I manually annotated the paws (RF=right front, RH= right hind, LF=left front, LH=left hind). As you can see there's clearly a repeating pat...
[ "Alright! I've finally managed to get something working consistently! This problem pulled me in for several days... Fun stuff! Sorry for the length of this answer, but I need to elaborate a bit on some things... (Though I may set a record for the longest non-spam stackoverflow answer ever!)\nAs a side note, I'm usi...
[ 124, 4, 2 ]
[]
[]
[ "image_processing", "python" ]
stackoverflow_0004502656_image_processing_python.txt
Q: Google App Engine - Importing my own source modules (multiple files) I am writing a GAE application and am having some difficulty with the following problem. I've created multiple python files (say a.py and b.py) which are both stored in the same folder. I am able to call code in a.py or b.py by mapping URL's to ...
Google App Engine - Importing my own source modules (multiple files)
I am writing a GAE application and am having some difficulty with the following problem. I've created multiple python files (say a.py and b.py) which are both stored in the same folder. I am able to call code in a.py or b.py by mapping URL's to them (using app.yaml). What I haven't figured out how to do is import the ...
[ "Have you tried importing as if you were starting at the top level? Like \n\nimport modules.b\n\n", "If the files a.py and b.py aren't located, be sure to include the respective paths in sys.path.\nimport sys\nsys.path.append(r\"/parent/of/module/b\")\n\n", "Note that the usual pattern with GAE is not to have e...
[ 8, 2, 1, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0000437791_google_app_engine_python.txt
Q: How to print Facebook style timestamps in Django I have a datetime that represents an event creation time and I need to show how much time has passed since then. Examples: “right now”, “2 days ago”, “3 months from now”. I know of PrettyTime for Java, but I need something for Django. Thanks! A: Py-Pretty should d...
How to print Facebook style timestamps in Django
I have a datetime that represents an event creation time and I need to show how much time has passed since then. Examples: “right now”, “2 days ago”, “3 months from now”. I know of PrettyTime for Java, but I need something for Django. Thanks!
[ "Py-Pretty should do the trick... It also has support for future events as well.\n", "Not sure if it is exactly what you are looking for, but Django does have a built in template filter that achieves something similar: timesince\n\nFormats a date as the time since that date (e.g., \"4 days, 6 hours\").\nTakes an ...
[ 4, 2 ]
[]
[]
[ "django", "facebook", "python" ]
stackoverflow_0004543588_django_facebook_python.txt
Q: crc24 from c to python can someone please translate this code to python? i have tried and tried again, but have not managed it: #define CRC24_INIT 0xB704CEL #define CRC24_POLY 0x1864CFBL typedef long crc24; crc24 crc_octets(unsigned char *octets, size_t len) { crc24 crc = CRC24_INIT; int i; ...
crc24 from c to python
can someone please translate this code to python? i have tried and tried again, but have not managed it: #define CRC24_INIT 0xB704CEL #define CRC24_POLY 0x1864CFBL typedef long crc24; crc24 crc_octets(unsigned char *octets, size_t len) { crc24 crc = CRC24_INIT; int i; while (len--) { ...
[ "# Yes, there is no 'length' parameter here. We don't need it in Python.\ndef crc24(octets):\n INIT = 0xB704CE\n POLY = 0x1864CFB\n crc = INIT\n for octet in octets: # this is what the '*octets++' logic is effectively\n # accomplishing in the C code.\n crc ^= (octet << 16)\n # Throw tha...
[ 2, 1 ]
[]
[]
[ "c", "port", "python", "translation" ]
stackoverflow_0004544154_c_port_python_translation.txt
Q: python - how to run a function on last day of every month? I have a python function and I want to run the function on last day of the every month. how can i do that? A: This calls for the use of a cron job or a similiar scheduling application. http://en.wikipedia.org/wiki/Cron #!/bin/bash TODAY=`/bin/date +%d` ...
python - how to run a function on last day of every month?
I have a python function and I want to run the function on last day of the every month. how can i do that?
[ "This calls for the use of a cron job or a similiar scheduling application.\nhttp://en.wikipedia.org/wiki/Cron\n#!/bin/bash\n\nTODAY=`/bin/date +%d`\nTOMORROW=`/bin/date +%d -d \"1 day\"`\n\n# See if tomorrow's day is less than today's\nif [ $TOMORROW -lt $TODAY ]; then\n exit 0\nfi\n\nexit 1\n\nNow we can a...
[ 3, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004543971_python.txt
Q: Python: type() gives blank result What does it mean when I do print type(foo) and get absolutely nothing? foo is the response from an eBay REST search query, and it's supposed to be XML according to the eBay docs. When I print foo I get stuff -- a long string of values about ebay items all butted-up against one...
Python: type() gives blank result
What does it mean when I do print type(foo) and get absolutely nothing? foo is the response from an eBay REST search query, and it's supposed to be XML according to the eBay docs. When I print foo I get stuff -- a long string of values about ebay items all butted-up against one another.
[ "It means type is a function or other callable object that returns an empty string. Since the built-in function doesn't do that, you have most likely called another function type(). Change the name of that function to something else. type_() is good. Or _type(), or somethingtype().\n" ]
[ 7 ]
[]
[]
[ "python", "types" ]
stackoverflow_0004543948_python_types.txt
Q: Location of Substrings within strings and their extentions this is a python noob posting here so plz dont be too harsh I am tying to create a list of strings that are taken from a larger string which has multiple copys of the substring which in contains a relevent phrase such as the extention of a picture file lik...
Location of Substrings within strings and their extentions
this is a python noob posting here so plz dont be too harsh I am tying to create a list of strings that are taken from a larger string which has multiple copys of the substring which in contains a relevent phrase such as the extention of a picture file like a .jpg I have a programe that returns a list of the search phr...
[ "If what you want is a list of all the filenames which end in .jpg you could use a regular expression something like the following:\nimport re\njpglist = re.findall(r\"[\\w-]+\\.jpg\", string)\n\nHere [\\w-] will permit file names with alphanumeric, underscore and hyphen characters, but you can expand on that if ne...
[ 1 ]
[]
[]
[ "python", "substring" ]
stackoverflow_0004544371_python_substring.txt
Q: Python __future__ methods Would it be correct to say that if 'print' is not listed as one of the methods in __future__.__dict__.keys() then the version of Python that I am using does not supply the future print function? (I am using Python 2.5.5.) A: Almost correct. The feature is called print_function, not...
Python __future__ methods
Would it be correct to say that if 'print' is not listed as one of the methods in __future__.__dict__.keys() then the version of Python that I am using does not supply the future print function? (I am using Python 2.5.5.)
[ "Almost correct. The feature is called print_function, not print.\nPython 2.6.5 (r265:79063, Apr 16 2010, 13:57:41) \n[GCC 4.4.3] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import __future__\n>>> __future__.print_function\n_Feature((2, 6, 0, 'alpha', 2), (3, 0, 0...
[ 2, 2, 0 ]
[]
[]
[ "printing", "python" ]
stackoverflow_0004544622_printing_python.txt
Q: Automatically growing lists in Python Is there a way to make an automatically growing list in Python? What I mean is to make a list that would grow when an index that does not yet exist is referenced. Basically the behaviour of Ruby arrays. Thanks in advance! A: Sure it's possible, you just have to use a subclas...
Automatically growing lists in Python
Is there a way to make an automatically growing list in Python? What I mean is to make a list that would grow when an index that does not yet exist is referenced. Basically the behaviour of Ruby arrays. Thanks in advance!
[ "Sure it's possible, you just have to use a subclass of list to do it.\nclass GrowingList(list):\n def __setitem__(self, index, value):\n if index >= len(self):\n self.extend([None]*(index + 1 - len(self)))\n list.__setitem__(self, index, value)\n\nUsage:\n>>> grow = GrowingList()\n>>> g...
[ 45, 2 ]
[ "No, but you could use a dictionary (hash table) to achieve the same thing.\n" ]
[ -1 ]
[ "list", "python" ]
stackoverflow_0004544630_list_python.txt
Q: writing unicode to binary file in python I'm wondering how to write unicode (utf-8) to a binary file. Here's the background: I've got a 40 byte header (10 ints), and a table with a variable number of triple-int structs. Writing these was cake. Now, I want to add a bunch of strings to the end of the file. Wri...
writing unicode to binary file in python
I'm wondering how to write unicode (utf-8) to a binary file. Here's the background: I've got a 40 byte header (10 ints), and a table with a variable number of triple-int structs. Writing these was cake. Now, I want to add a bunch of strings to the end of the file. Writing regular ASCII based strings is easy: valu...
[ "Unicode != UTF-8. UTF-8 is a binary encoding of Unicode, so just write the UTF-8 string just as you would an ASCII string. No need to pack an encoded string either. It's already \"just a bunch of bytes\".\n# coding: utf8\nimport struct\ntext = u'我是美国人。'\nencoded_text = text.encode('utf8')\n\n# proof packing is ...
[ 6, 2 ]
[]
[]
[ "file_io", "python", "unicode" ]
stackoverflow_0004542961_file_io_python_unicode.txt
Q: Need urllib.urlretrieve and urllib2.OpenerDirector together I'm writing a script in Python 2.7 which uses a urllib2.OpenerDirector instance via urllib2.build_opener() to take advantage of the urllib2.HTTPCookieProcessor class, because I need to store and re-send the cookies I get: opener = urllib2.build_opener(url...
Need urllib.urlretrieve and urllib2.OpenerDirector together
I'm writing a script in Python 2.7 which uses a urllib2.OpenerDirector instance via urllib2.build_opener() to take advantage of the urllib2.HTTPCookieProcessor class, because I need to store and re-send the cookies I get: opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookielib.CookieJar())) However, after ...
[ "urlretrieve is a old interface from urllib. It was there much before urllib2 came into existence. It does not have any session handling capabilities. It just downloads the files. The updated urllib2 provides much better way with the deal with sessions, passwords, proxies extra using its Handler interfaces OpenerD...
[ 4 ]
[]
[]
[ "cookies", "python", "urllib", "urllib2" ]
stackoverflow_0004544831_cookies_python_urllib_urllib2.txt
Q: Python - Separate program logic and GUI code? What would be the best way of separating program logic to the GUI code? I wanted different GUI (GTK, KDE, CLI) code using the same program logic. I was thinking of using different python module (winecellar-common, winecellar-gtk, winecellar-cli) not sure how I would do...
Python - Separate program logic and GUI code?
What would be the best way of separating program logic to the GUI code? I wanted different GUI (GTK, KDE, CLI) code using the same program logic. I was thinking of using different python module (winecellar-common, winecellar-gtk, winecellar-cli) not sure how I would do this and if its the best way. *EDITED* Just to add...
[ "Define functions or classes for your business logic in one module, and define your presentation in another, using those functions to get your presentation. You should almost entirely be using functions and classes from the main module in the GUI module. You should do the same thing for your CLI. That way, you can ...
[ 12, 3 ]
[]
[]
[ "pygtk", "python" ]
stackoverflow_0004522218_pygtk_python.txt
Q: python - how to schedule a function to run at last day of each month? I want to schedule the function to run at last day of each month using python sched. can anyone help me for the same? A: Run everyday with crontab and check if it is the last day of the month using calendar.monthrange: import datetime, calend...
python - how to schedule a function to run at last day of each month?
I want to schedule the function to run at last day of each month using python sched. can anyone help me for the same?
[ "Run everyday with crontab and check if it is the last day of the month using calendar.monthrange:\n import datetime, calendar\n today = datetime.date.today()\n if calendar.monthrange(today.year, today.month)[1] != today.day:\n exit()\n\nPython sched and crontab are not in the same league, unless you are talkin...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004545405_python.txt
Q: Django redis connection backend or how to implement one Is there any plugin or 3rd party backend to manage redis connections in Django, so the methods in view.py don't have to explicitly connect to redis for every request? If not, how would you start implementing one? A new plugin? a new backend? a new django midd...
Django redis connection backend or how to implement one
Is there any plugin or 3rd party backend to manage redis connections in Django, so the methods in view.py don't have to explicitly connect to redis for every request? If not, how would you start implementing one? A new plugin? a new backend? a new django middleware? Thank you.
[ "I think the emerging standard for non-rel databases is django-nonrel . I don't know if django-nonrel is production ready or if support redis, but they have a guide on writing a custom no-sql backend.\nUnfortunately, i don't think that writing support for a redis on standard django is easy as writing a DatabaseBack...
[ 5 ]
[]
[]
[ "django", "python", "redis" ]
stackoverflow_0004545436_django_python_redis.txt
Q: I want to roll 3 dice with independent numbers from each other I want to write a python program that will simulate 3 dice being rolled at the same time but I want the 3 dice to always have a different number from each other every time they are rolled. ex on the first roll I get 2,1,6 that is fine but I dont want t...
I want to roll 3 dice with independent numbers from each other
I want to write a python program that will simulate 3 dice being rolled at the same time but I want the 3 dice to always have a different number from each other every time they are rolled. ex on the first roll I get 2,1,6 that is fine but I dont want the prog. to ever roll duplicates for ex 2,4,2. (3,3,3, would also be...
[ "Try random.sample:\n>>> sides = 6\n>>> dice = random.sample(range(1, sides + 1), 3)\n[3, 6, 1]\n\nI'd advise that you reconsider whether it is a good idea to have variables called die1, die2, die3.\nIt is usually better to use a list as in the above example.\n", "This will work:\na = range(1,7)\nrandom.shuffle(a...
[ 8, 3, 2, 2, 0 ]
[]
[]
[ "python", "random" ]
stackoverflow_0004542768_python_random.txt
Q: Get UTF8 strings from remote DB My application downloads some data from remote MySQL database. Problem is that db stores strings as utf8. But data I receive is ascii decoded. How to get around this ? The code : cursor = conn.cursor() query = """MY QUERY HERE""" cursor.execute(query) result = cursor.fetchall() A:...
Get UTF8 strings from remote DB
My application downloads some data from remote MySQL database. Problem is that db stores strings as utf8. But data I receive is ascii decoded. How to get around this ? The code : cursor = conn.cursor() query = """MY QUERY HERE""" cursor.execute(query) result = cursor.fetchall()
[ "Perhaps an example is in order -- here I create a unicode string \"u\", encode it as utf8, decode that from utf8 back to a unicode string, encode it as ascii (which throws an exception since the extended character in this string can't be encoded as ascii), then finally encode as ascii replacing errors with the \"?...
[ 2, 0, 0 ]
[ "just set your python to utf-8 encoding and you don't have to worry anymore. had this problem with db2/ mongodb to load data.\njust set the defaultencoding to utf-8 under site.py.\nhave a look @ http://blog.ianbicking.org/illusive-setdefaultencoding.html\n" ]
[ -1 ]
[ "decoding", "mysql", "python", "string" ]
stackoverflow_0004526572_decoding_mysql_python_string.txt
Q: C++ slow, python fast? (in terms of development time) I'm thinking of trying to make some simple 2d games, but I've yet to choose a language. A lot of people recommend either C++ with SDL or python with pygame. I keep hearing that developement on C++ is fairly slow, and developement time with Python is fairly fast...
C++ slow, python fast? (in terms of development time)
I'm thinking of trying to make some simple 2d games, but I've yet to choose a language. A lot of people recommend either C++ with SDL or python with pygame. I keep hearing that developement on C++ is fairly slow, and developement time with Python is fairly fast. Anyways, could anyone elaborate on this? What exactly mak...
[ "There are two things that are relevant between C++ and Python that will affect your time-to-develop any project including a game. There are the languages themselves and the libraries. I've played with the SDL to some extent and peeked at PyGame and for your specific instance I don't think the libraries are going...
[ 24, 16, 13, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "c++", "python" ]
stackoverflow_0000977404_c++_python.txt
Q: Which one to prefer - line.lower() vs. word.lower() When I need to split a line, and put all words in a list as lowercase, which one would be the preferred way: 1.) list = [] for word in line.split(): word = word.lower() list.append(word) 2.) list = [] for word in line.lower().spl...
Which one to prefer - line.lower() vs. word.lower()
When I need to split a line, and put all words in a list as lowercase, which one would be the preferred way: 1.) list = [] for word in line.split(): word = word.lower() list.append(word) 2.) list = [] for word in line.lower().split(): list.append(word) Is there any performance...
[ "Something more compact maybe:\n>>> a = \"I AM A DEVELOPER\"\n\n>>> a.lower().split()\n['i', 'am', 'a', 'developer']\n\n", "Maybe try list comprehension\n[x.lower() for x in line]\n\nwill return a list with the words lowered. If you want to omit spaces:\n[x.lower() for x in line if x.strip() != '']\n\n", "I don...
[ 5, 4, 2, 1, 0, 0 ]
[]
[]
[ "coding_style", "python" ]
stackoverflow_0004546879_coding_style_python.txt
Q: Method chaining - how many chained methods are enough? Are there any guidelines on when to stop chaining methods and instead break up the chain into several expressions? Consider e.g. this Python code, which build up a dictionary, with word as key and the corresponding count as the value: def build_dict(filename):...
Method chaining - how many chained methods are enough?
Are there any guidelines on when to stop chaining methods and instead break up the chain into several expressions? Consider e.g. this Python code, which build up a dictionary, with word as key and the corresponding count as the value: def build_dict(filename): with open(filename, 'r') as f: dict = defaultdi...
[ "What would be the point of chaining only two? If you do method chaining, do it right.\nIt's more an issue of formatting, if it gets to much for a single line, I prefer\n(x.Foo()\n .Bar()\n .FooBar()\n .Barf());\n\nAnother issue can be debuggers, that force you to trace into Foo if you want to trace into Bar. \n...
[ 6, 4, 4 ]
[]
[]
[ "coding_style", "method_chaining", "python" ]
stackoverflow_0004546694_coding_style_method_chaining_python.txt
Q: Iterating over a stack (reverse list), is there an isempty() method? What's the best way to iterate over a stack in Python? a = [1,2,3,4] while (len(a) > 0) print a.pop() # prints 4, 3, 2, 1 in sequence I couldn't find an isempty method, and checking the length each time seems wrong somehow. A: The usual con...
Iterating over a stack (reverse list), is there an isempty() method?
What's the best way to iterate over a stack in Python? a = [1,2,3,4] while (len(a) > 0) print a.pop() # prints 4, 3, 2, 1 in sequence I couldn't find an isempty method, and checking the length each time seems wrong somehow.
[ "The usual convention for containers is that they are True while not empty and False when empty, so you can just do:\nwhile a:\n print a.pop()\n\n", "Use the list as a boolean condition which evaluates to False only if the list is empty:\n>>> while a:\n... print a.pop()\n... \n4\n3\n2\n1\n\nNot only is thi...
[ 33, 8, 2 ]
[]
[]
[ "iteration", "python", "stack" ]
stackoverflow_0004547310_iteration_python_stack.txt
Q: Removing code dependency on Greenlets I have some code which depends on Greenlets, and need to remove this dependency. Can anyone explain to me exactly what I'll need to do? They would preferably be replaced with threads or (better yet) processes from the multiprocessing module, but anything that relies solely o...
Removing code dependency on Greenlets
I have some code which depends on Greenlets, and need to remove this dependency. Can anyone explain to me exactly what I'll need to do? They would preferably be replaced with threads or (better yet) processes from the multiprocessing module, but anything that relies solely on the Python standard library would be suff...
[ "It really depends on the structure of your code and high level architecture of your system. If you think that whatever you are using greenlets for can be done using multiprocessing module in the Python Standard library, then you can do that. I think, if you post specific instances than you can get the specific way...
[ 1 ]
[]
[]
[ "multiprocessing", "multithreading", "python" ]
stackoverflow_0004547096_multiprocessing_multithreading_python.txt
Q: python: closures and classes I need to register an atexit function for use with a class (see Foo below for an example) that, unfortunately, I have no direct way of cleaning up via a method call: other code, that I don't have control over, calls Foo.start() and Foo.end() but sometimes doesn't call Foo.end() if it e...
python: closures and classes
I need to register an atexit function for use with a class (see Foo below for an example) that, unfortunately, I have no direct way of cleaning up via a method call: other code, that I don't have control over, calls Foo.start() and Foo.end() but sometimes doesn't call Foo.end() if it encounters an error, so I need to c...
[ "Make a registry a global registry and a function that calls a function in it, and remove them from there when necessary.\ncleaners = set()\n\ndef _call_cleaners():\n for cleaner in list(cleaners):\n cleaner()\n\natexit.register(_call_cleaners)\n\nclass Foo(object):\n def cleanup(self):\n if self.cle...
[ 6, 3, 3, 3, 1 ]
[]
[]
[ "atexit", "class", "python" ]
stackoverflow_0004547277_atexit_class_python.txt
Q: Django self-referential relationship? I'm trying to create model Page, page should be able to have "child pages" too. My model code below keeps crashing Python on my Mac (python 2.6.1) and Ubuntu 10.04 (python 2.6.5): from django.db import models from django.contrib import admin class Page(models.Model): slug...
Django self-referential relationship?
I'm trying to create model Page, page should be able to have "child pages" too. My model code below keeps crashing Python on my Mac (python 2.6.1) and Ubuntu 10.04 (python 2.6.5): from django.db import models from django.contrib import admin class Page(models.Model): slug = models.SlugField(blank=True) title =...
[ "In terms of the model itself you're just thinking of this in the wrong direction. Instead of \nchildren = models.ManyToManyField(\"self\", blank=True)\n\nuse\nparent = models.ForeignKey(\"self\", blank=True, related_name=\"children\")\n\nThis will let you access the children directly from a page record but should ...
[ 14, 8 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0004547101_django_django_models_python.txt
Q: Longer execution through Java shell than console? I have a script in Python which do some computations. When I run this script in console it takes about 7 minutes to complete but when I run it thought Java shell it takes three times longer. I use following code to execute the script in Java: this.p = Runtime.getRu...
Longer execution through Java shell than console?
I have a script in Python which do some computations. When I run this script in console it takes about 7 minutes to complete but when I run it thought Java shell it takes three times longer. I use following code to execute the script in Java: this.p = Runtime.getRuntime().exec("script.py --batch", envp); this.input = ...
[ "Try using the same code without the BufferedReaders and BufferedWriters, in case there is delay introduced by the buffering. I'm not sure how long buffered writers wait to flush, but at the very least, removing them would help simplify your problem.\n" ]
[ 2 ]
[]
[]
[ "java", "python", "shellexecute" ]
stackoverflow_0004545690_java_python_shellexecute.txt
Q: How to test my GAE site for performance I am building a GAE site that uses AJAX/JSON for almost all its tasks including building the UI elements, all interactions and client-server requests. What is a good way to test it for highloads so that I could have some statistics about how much resources 1000 average users...
How to test my GAE site for performance
I am building a GAE site that uses AJAX/JSON for almost all its tasks including building the UI elements, all interactions and client-server requests. What is a good way to test it for highloads so that I could have some statistics about how much resources 1000 average users per some period of time would take. I think ...
[ "The first step is to get Appstats hooked up and configured for your app -- it won't help you with the load-testing part itself, but gives you a ton of useful data about where your app is spending its time. \nAppstats for Python\n", "Writing some python tests that can automate tests is a good way to measure perfo...
[ 3, 1, 1, 0 ]
[]
[]
[ "google_app_engine", "load_testing", "python" ]
stackoverflow_0004529913_google_app_engine_load_testing_python.txt
Q: python in Google App Engine - having the class-instead-of-instance problem, but using db.Model so can't create init method i am writing an app to compare products, using Python and GAE. The products will belong to a set of similar products, and the app calculates the best value in each set. When i create a new pr...
python in Google App Engine - having the class-instead-of-instance problem, but using db.Model so can't create init method
i am writing an app to compare products, using Python and GAE. The products will belong to a set of similar products, and the app calculates the best value in each set. When i create a new product, it can be added to an existing set or a new set can be created. When testing the app, the first set gets created just fin...
[ "In your init you will need to call the super's init, db.Model has some important stuff to do in its init, you will have to match the signature.\nHowever you likely shouldn't be setting up things like defaults in there. Try and just use the datastore Properties ability to set a default.\n", "You've got some (I a...
[ 0, 0 ]
[]
[]
[ "google_app_engine", "list", "python", "set" ]
stackoverflow_0004547315_google_app_engine_list_python_set.txt
Q: Is there any automated conversion from Go to Python? Is there any program to automatically convert Go source code to Python source code? A: It's highly unlikely that you'll find a way to do such a conversion with output that is actually useful. Go is very new, and if anything it would make more sense for someon...
Is there any automated conversion from Go to Python?
Is there any program to automatically convert Go source code to Python source code?
[ "It's highly unlikely that you'll find a way to do such a conversion with output that is actually useful. Go is very new, and if anything it would make more sense for someone to convert the other way around.\n" ]
[ 7 ]
[]
[]
[ "go", "python" ]
stackoverflow_0004548000_go_python.txt
Q: PIL Download for Windows Binary I was wondering where i could download PIL (Python Imaging Library) as a windows 32bit binary? The official sites where it is available are not working, giving 500 server errors. I run Python 2.7. A: Looks like the main site is down, use http://www.lfd.uci.edu/~gohlke/pythonlibs/ ...
PIL Download for Windows Binary
I was wondering where i could download PIL (Python Imaging Library) as a windows 32bit binary? The official sites where it is available are not working, giving 500 server errors. I run Python 2.7.
[ "Looks like the main site is down, use http://www.lfd.uci.edu/~gohlke/pythonlibs/ mirror, filename is PIL-1.1.7.win32-py2.7.‌exe.\n" ]
[ 5 ]
[]
[]
[ "download", "python", "python_imaging_library" ]
stackoverflow_0004548493_download_python_python_imaging_library.txt
Q: Python - Default Counter Variable in For loop Is there any default Counter Variable in For loop? A: No, you give it a name: for i in range(10): ... If you want to iterate over elements of a collection in such a way that you get both the element and its index, the Pythonic way to do it is for i,v in enumerate(l):...
Python - Default Counter Variable in For loop
Is there any default Counter Variable in For loop?
[ "No, you give it a name: for i in range(10): ...\nIf you want to iterate over elements of a collection in such a way that you get both the element and its index, the Pythonic way to do it is for i,v in enumerate(l): print i,v (where l is a list or any other object implementing the sequence protocol.)\n", "General...
[ 15, 6, 5 ]
[]
[]
[ "python" ]
stackoverflow_0004547256_python.txt
Q: Run_simple dev web server from werkzeug does not run using reloader under Windows I can not run the run_simple dev web server from werkzeug under windows and use_reloader=True : run_simple("localhost", 8090, application, use_reloader=True) Eventually it throws too many values to unpack while traversing new_enviro...
Run_simple dev web server from werkzeug does not run using reloader under Windows
I can not run the run_simple dev web server from werkzeug under windows and use_reloader=True : run_simple("localhost", 8090, application, use_reloader=True) Eventually it throws too many values to unpack while traversing new_environ in wergzeug.serving. If I remove use_reloader (defaults to False) than the server run...
[ "Use the development version. The upcoming 0.7 release will fix that.\n" ]
[ 2 ]
[]
[]
[ "python", "werkzeug", "windows" ]
stackoverflow_0004270881_python_werkzeug_windows.txt
Q: What's the Python version for “Code against an interface, not an object”? Inspired by a great question (and bunch of great answers) from here. Does the statement "Code against an interface, not an object" have any significance in Python? I'm looking for answers like the ones in the Original Question but with Pytho...
What's the Python version for “Code against an interface, not an object”?
Inspired by a great question (and bunch of great answers) from here. Does the statement "Code against an interface, not an object" have any significance in Python? I'm looking for answers like the ones in the Original Question but with Python snippets and thoughts.
[ "\"Code against an interface, not an object\" doesn't make literal sense in Python because the language doesn't have an interface feature. The rough Python equivalent is \"use duck typing.\" If you want to see if an object is a duck, in other words, you should check to see whether it has a quack() method, or better...
[ 68, 31, 19, 1 ]
[]
[]
[ "interface", "inversion_of_control", "oop", "python" ]
stackoverflow_0004549018_interface_inversion_of_control_oop_python.txt
Q: Pylons - Redirects will drop from HTTPS to HTTP unless I specify the protocol... Is there a way to fix this? On my Pylons website, I have my login form sending it's data to 'https://mysite.com'. Upon a successful login, a redirect takes place to send them to their profile page. redirect(url(controller='profile')) ...
Pylons - Redirects will drop from HTTPS to HTTP unless I specify the protocol... Is there a way to fix this?
On my Pylons website, I have my login form sending it's data to 'https://mysite.com'. Upon a successful login, a redirect takes place to send them to their profile page. redirect(url(controller='profile')) This sends the user to http://mysite.com/profile instead of https://mysite.com/profile. The only way I've found t...
[ "Since I spent a couple of hours wading through the pylons/routes/beaker/etc. source I thought I'd share my solution.\nFirst a bit of context. I'm using an elastic load balancer (ELB) on AWS with SSL termination. The application is built to run solely over https; this is a post-firesheep world after all. It's layer...
[ 4, 0 ]
[]
[]
[ "https", "pylons", "python", "redirect", "ssl" ]
stackoverflow_0003706024_https_pylons_python_redirect_ssl.txt
Q: How do I create an alias to a Python class through Swig? I've created a C++ library and have successfully used swig to make it accessible through python. Templating is used heavily in the library and each template type is mapped to its own python class by swig like so: %template(Imageint) Image<int>; %template(Im...
How do I create an alias to a Python class through Swig?
I've created a C++ library and have successfully used swig to make it accessible through python. Templating is used heavily in the library and each template type is mapped to its own python class by swig like so: %template(Imageint) Image<int>; %template(Imagedouble) Image<double>; However, I would really like to hav...
[ "In case this helps someone in the future, the way to do what is describe above is to add the following to the interface file:\n%pythoncode %{\nImage = Imagedouble\n%}\n\nI did not realize there was a way to write standard python code in the interface file.\n" ]
[ 8 ]
[]
[]
[ "alias", "python", "rename", "swig", "templates" ]
stackoverflow_0004549588_alias_python_rename_swig_templates.txt
Q: Server side form validation and POST data I have a user input form here: http://www.7bks.com/create (Google login required) When you first create a list you are asked to create a public username. Unfortuantely currently there is no constraint to make this unique. I'm working on the code to enforce unique usernames...
Server side form validation and POST data
I have a user input form here: http://www.7bks.com/create (Google login required) When you first create a list you are asked to create a public username. Unfortuantely currently there is no constraint to make this unique. I'm working on the code to enforce unique usernames at the moment and would like to know the best ...
[ "Can you use the django form validation functionality (which I think should just abstract all this away from you):\nhttp://code.google.com/appengine/articles/djangoforms.html\nSearch in that page for \"adding an item\" - it handles errors automatically (which I think could include non-unique username).\nWarning: al...
[ 1, 1 ]
[]
[]
[ "google_app_engine", "post", "python", "validation" ]
stackoverflow_0004545107_google_app_engine_post_python_validation.txt
Q: Django's Settings Magic I'm building an application that borrows some design ideas from Django - the use of a per-project manage.py and settings.py, for example- and am trying to decipher the magic. When I want to refer to my Django settings, I generally import from django.settings. Obviously, though, my settings ...
Django's Settings Magic
I'm building an application that borrows some design ideas from Django - the use of a per-project manage.py and settings.py, for example- and am trying to decipher the magic. When I want to refer to my Django settings, I generally import from django.settings. Obviously, though, my settings are in their own project-spec...
[ "An environment variable: DJANGO_SETTINGS_MODULE points to your settings module.\nYou can use the __import__ function: See http://docs.python.org/library/functions.html#import\nAnd try, assuming your main app module is myapp:\nmyapp.settings = __import__(SETTINGS_MODULE_NAME, globals(), locals(), [], -1)\n\nThis is...
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004549829_django_python.txt
Q: Removing multiple MongoDB documents in Python Greetings, I am attempting to remove multiple documents from a MongoDB collection using the following syntax. I don't know if this is correct as I found it somewhere on the internet and haven't been able to find anything since enforcing the legitimacy of this statement...
Removing multiple MongoDB documents in Python
Greetings, I am attempting to remove multiple documents from a MongoDB collection using the following syntax. I don't know if this is correct as I found it somewhere on the internet and haven't been able to find anything since enforcing the legitimacy of this statement: pymongo_collection_object.remove( [ {...
[ "You can do so by using $or / $in operators. \nTry this:\npymongo_collection_object.remove({'$or': [{'sku': '100-00'}, {'sku': '200-00'}]}, safe=True)\n\nor\npymongo_collection_object.remove({'sku': {'$in': ['100-00', '200-00']}}, safe=True)\n\n" ]
[ 12 ]
[]
[]
[ "mongodb", "nosql", "pymongo", "python" ]
stackoverflow_0004549871_mongodb_nosql_pymongo_python.txt
Q: pycurl/curl not following the CURLOPT_TIMEOUT option I have a multi-threaded script which occasionally freezes when it connects to a server but the server doesn't send anything back. Netstat shows a connected tcp socket. This happens even if I have TIMEOUT set. The timeout works fine in an unthreaded script. Here'...
pycurl/curl not following the CURLOPT_TIMEOUT option
I have a multi-threaded script which occasionally freezes when it connects to a server but the server doesn't send anything back. Netstat shows a connected tcp socket. This happens even if I have TIMEOUT set. The timeout works fine in an unthreaded script. Here's some sample code. def xmlscraper(url): htmlpage = Stri...
[ "I modified your 'edit2' code to spawn multiple threads and it works fine on my machine (Ubuntu 10.10 with Python 2.6.6)\nimport threading\nimport pycurl\n\ndef testf():\n c = pycurl.Curl()\n c.setopt(pycurl.CONNECTTIMEOUT, 3)\n c.setopt(pycurl.TIMEOUT, 3)\n c.setopt(pycurl.NOSIGNAL, 1)\n c.setopt(py...
[ 3, 1 ]
[]
[]
[ "multithreading", "pycurl", "python", "timeout" ]
stackoverflow_0004549490_multithreading_pycurl_python_timeout.txt
Q: python convert degrees to change in x and change in y I am making a snake game in python with pygame and for moving the character I have a integer which is the degrees of the angle it should move. Is there any way I can get the change in x and y to move it based on the degrees? For example: func(90) # [0, 5] or fu...
python convert degrees to change in x and change in y
I am making a snake game in python with pygame and for moving the character I have a integer which is the degrees of the angle it should move. Is there any way I can get the change in x and y to move it based on the degrees? For example: func(90) # [0, 5] or func(0) # [5, 0]
[ "import math\n\nspeed = 5\nangle = math.radians(90) # Remember to convert to radians!\nchange = [speed * math.cos(angle), speed * math.sin(angle)]\n\n", "The sine and cosine of the angle, multiplied by the total amount of the move, will give you the X and Y changes.\nimport math\ndef func(degrees, magnitude):\...
[ 9, 5, 3 ]
[]
[]
[ "coordinates", "degrees", "pygame", "python" ]
stackoverflow_0004550315_coordinates_degrees_pygame_python.txt
Q: How can I write this without so many floats? float(float(1)/float(i) * float(score)) A: Assuming Python 2.x: 1.0 / i * score The main case you need to worry about is the division because in Python 2.x, division is defaulted to integer division. In order to have floating-point division, either the dividend or div...
How can I write this without so many floats?
float(float(1)/float(i) * float(score))
[ "Assuming Python 2.x: 1.0 / i * score\nThe main case you need to worry about is the division because in Python 2.x, division is defaulted to integer division. In order to have floating-point division, either the dividend or divisor needs to be a float, hence the 1.0. Thus, 1.0/i will be a float, and multiplying a f...
[ 10, 3, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004550717_python.txt
Q: Django: What is a clean way to populate a list of optional object attributes that need to be wrapped in try/except? Is this a good place for eval()? I repeatedly find myself in a position where I'm writing specific django model instance fields into a list for various reasons (exporting to CSV, logging) and I'd ima...
Django: What is a clean way to populate a list of optional object attributes that need to be wrapped in try/except? Is this a good place for eval()?
I repeatedly find myself in a position where I'm writing specific django model instance fields into a list for various reasons (exporting to CSV, logging) and I'd imagine the same is true for many other people. Generating a report could require traversing through foreign keys IF they exist. The larger the report, the m...
[ "Why aren't you just using getattr?\nfor item in django_model_instances:\n date_created = getattr(item.order, 'date_created', '')\n if date_created:\n date_created = date_created.strftime('%Y/%m/%d')\n\nor a simple wrapper, if this particular pattern is used a lot:\ndef get_strftime(object, attr):\n ...
[ 3, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004550144_django_python.txt
Q: Replace newlines and XML tags with ',' I have an XML document that looks like this: <file> <name>NAME_OF_FILE</name> </file> <file> <name>NAME_OF_FILE</name> </file> I’m trying to write a Python script that will replace all newlines, tags and whitespace between tags (i.e. not the elements themselv...
Replace newlines and XML tags with ','
I have an XML document that looks like this: <file> <name>NAME_OF_FILE</name> </file> <file> <name>NAME_OF_FILE</name> </file> I’m trying to write a Python script that will replace all newlines, tags and whitespace between tags (i.e. not the elements themselves) with ','. The output for the file above ...
[ "Remove the rs, as they quote the string literally.\none = re.sub(\"\\n\", '', line)\ntwo = re.sub(\"\\r\", '', one)\n\nYou can also use string.replace() for these simple replacements, as well as combine them into one line.\nline = re.sub('r</name>.*<name>', \"','\", line.replace('\\n', '').replace('\\r', ''))\nout...
[ 2, 0, 0, 0 ]
[]
[]
[ "python", "regex", "xml" ]
stackoverflow_0004549459_python_regex_xml.txt
Q: Iterative printing over two data types in Python I often browse freely-available art on the web. Actually, I can't think of a better use for the internet than to turn it into a gigantic art gallery. When I encounter a set of pieces I quite like, I download them all to my hard drive. wget makes that easy, especiall...
Iterative printing over two data types in Python
I often browse freely-available art on the web. Actually, I can't think of a better use for the internet than to turn it into a gigantic art gallery. When I encounter a set of pieces I quite like, I download them all to my hard drive. wget makes that easy, especially in combination with Python's print function, and I u...
[ "for i in ['a','b','c','d','e','f','g']:\n for j in range(1,15):\n url = BASE_URL + i + str(j)\n print url\n\nIs that what you are looking for?\n", "Try this:\n['{0}{1}'.format(letter, number + 1) for letter in 'abcdefg'\n for number in range(14)]\n\n", "['ht...
[ 4, 3, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004550513_python.txt
Q: How to authorize application to post to Facebook User's Wall? I'm using GAE, Python and the Facebook-Python SDK to build an application. I've got FB login working, have a Facebook Application set up of course and am now trying to use the Graph API to post a message on my Wall from the app. When I attempt to POST ...
How to authorize application to post to Facebook User's Wall?
I'm using GAE, Python and the Facebook-Python SDK to build an application. I've got FB login working, have a Facebook Application set up of course and am now trying to use the Graph API to post a message on my Wall from the app. When I attempt to POST to Facebook I get the response: GraphAPIError: (#200) The user hasn...
[ "This works:\n\nThere are 6 extended permissions params you can pass to the login button: http://developers.facebook.com/docs/authentication/permissions/\n" ]
[ 2 ]
[]
[]
[ "facebook", "facebook_graph_api", "google_app_engine", "python" ]
stackoverflow_0004548082_facebook_facebook_graph_api_google_app_engine_python.txt
Q: UnicodeDecodeError when redirecting to file I run this snippet twice, in the Ubuntu terminal (encoding set to utf-8), once with ./test.py and then with ./test.py >out.txt: uni = u"\u001A\u0BC3\u1451\U0001D10C" print uni Without redirection it prints garbage. With redirection I get a UnicodeDecodeError. Can someon...
UnicodeDecodeError when redirecting to file
I run this snippet twice, in the Ubuntu terminal (encoding set to utf-8), once with ./test.py and then with ./test.py >out.txt: uni = u"\u001A\u0BC3\u1451\U0001D10C" print uni Without redirection it prints garbage. With redirection I get a UnicodeDecodeError. Can someone explain why I get the error only in the second ...
[ "The whole key to such encoding problems is to understand that there are in principle two distinct concepts of \"string\": (1) string of characters, and (2) string/array of bytes. This distinction has been mostly ignored for a long time because of the historic ubiquity of encodings with no more than 256 characters ...
[ 257, 21, 12 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0004545661_python_unicode.txt
Q: Partial FTP upload with storbinary I'm sending a xml file over ftp to the server but it cuts off at 48KB out of 53KB. The code is: if __name__ == '__main__': ftp = ftplib.FTP("IP") ftp.login(user = 'NAME', passwd = 'PASS') ftp.cwd('/web/content/tree/_demo') a.write('<root>\n' + DirXML(dirname) +...
Partial FTP upload with storbinary
I'm sending a xml file over ftp to the server but it cuts off at 48KB out of 53KB. The code is: if __name__ == '__main__': ftp = ftplib.FTP("IP") ftp.login(user = 'NAME', passwd = 'PASS') ftp.cwd('/web/content/tree/_demo') a.write('<root>\n' + DirXML(dirname) + '\n</root>') f=open(outputname,'rb'...
[ "You're using storlines instead of storbinary.\nThe former will do line end translation.\nThe storbinary ftplib code does a TYPE I before the transfer to ensure that the transfer mode is set to Image. (Binary).\nAlso check to ensure that the file you are transferring has been flushed or closed before the transfer b...
[ 0 ]
[]
[]
[ "ftp", "python" ]
stackoverflow_0004549119_ftp_python.txt
Q: Can't change state of checkable QListViewItem with custom widget I have a QListWidget where I want to add a bunch of items with a custom widget: listWidget = QListWidget() item = QListWidgetItem() item.setFlags(item.flags() | Qt.ItemIsUserCheckable) item.setCheckState(Qt.Unchecked) ...
Can't change state of checkable QListViewItem with custom widget
I have a QListWidget where I want to add a bunch of items with a custom widget: listWidget = QListWidget() item = QListWidgetItem() item.setFlags(item.flags() | Qt.ItemIsUserCheckable) item.setCheckState(Qt.Unchecked) listWidget.addItem(item) widget = MyLabelAndPushButton...
[ "I'm not sure why exactly list item doesn't want to change its state when widget is set. I guess the workaround for this issue would be either adding a check box in your widget or connect to the listwidget's itemClicked signal and reset item's state there. Pls, see if an example below would work for you:\nimport sy...
[ 2, 1 ]
[]
[]
[ "pyqt", "python", "qlistwidget", "qt" ]
stackoverflow_0004510341_pyqt_python_qlistwidget_qt.txt
Q: Python tk scroll frame? I'm creating a simple GUI app using Tkinter with Python, but I'm having problems adding a scrollbar to a single frame. The frame is visible from top to bottom on my 20" but in order to display everything on a netbook or any other low res screen it needs a scrollbar. Here's a snippet of how...
Python tk scroll frame?
I'm creating a simple GUI app using Tkinter with Python, but I'm having problems adding a scrollbar to a single frame. The frame is visible from top to bottom on my 20" but in order to display everything on a netbook or any other low res screen it needs a scrollbar. Here's a snippet of how I thought it would work (it ...
[ "The frame widget of tkinter doesn't scroll. One solution is to put your whole frame in a canvas (as a canvas object), and attach the scrollbar to the canvas. You have to tell the canvas how big the scrollable area is, which you can do by getting the size of the frame once you've placed all the widgets in it. Thoug...
[ 6 ]
[]
[]
[ "frame", "python", "scrollbar", "tk_toolkit", "tkinter" ]
stackoverflow_0004551296_frame_python_scrollbar_tk_toolkit_tkinter.txt
Q: Does Ctypes Structures and POINTERS automatically free the memory when the Python object is deleted? When using Python CTypes there are the Structures, that allow you to clone c-structures on the Python side, and the POINTERS objects that create a sofisticated Python Object from a memory address value and can be u...
Does Ctypes Structures and POINTERS automatically free the memory when the Python object is deleted?
When using Python CTypes there are the Structures, that allow you to clone c-structures on the Python side, and the POINTERS objects that create a sofisticated Python Object from a memory address value and can be used to pass objects by reference back and forth C code. What I could not find on the documentation or else...
[ "The memory is not freed, because Python has no idea if or how it should be freed. Compare these two functions:\nvoid testfunc1(PIX *pix)\n{\n static char staticBuffer[256] = \"static memory\";\n pix->text = staticBuffer;\n}\n\nvoid testfunc2(PIX *pix)\n{\n pix->text = (char *)malloc(32);\n strcpy(pix-...
[ 13 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0004551436_ctypes_python.txt
Q: Condition mako base template from inheriting one I have a base.mako template with a if statement to include or not jQuery <head> % if getattr(c, 'includeJQuery', False): <script type="text/javascript" src="jquery.js"></script> % endif ... Several templates inherit from base.mako, someone needs jQuery, someone...
Condition mako base template from inheriting one
I have a base.mako template with a if statement to include or not jQuery <head> % if getattr(c, 'includeJQuery', False): <script type="text/javascript" src="jquery.js"></script> % endif ... Several templates inherit from base.mako, someone needs jQuery, someone don't. At the moment I have to set the attribute in t...
[ "You shouldn't be using \"c\" in your template.\n<% includeJquery = True %>\n\nand\n% if includeJquery:\n...\n% endif\n\nshould suffice.\nI think you are doing this wrong... In your base template you should make a blank def for a jquery block and call it. Then in the inherited template just redefine the block.\nb...
[ 3, 2 ]
[]
[]
[ "mako", "pylons", "python" ]
stackoverflow_0003923337_mako_pylons_python.txt
Q: Using a Sort Order Breaks Google App Engine Queries I'm having a problem with my app-engine queries. When I run my query without sort order, everything works just fine: q = models.Contact.all(); q.filter("location = ", x); if(cur_search_cursor != None): q.with_cursor(cur_search_cursor); results = q.fetch(limit ...
Using a Sort Order Breaks Google App Engine Queries
I'm having a problem with my app-engine queries. When I run my query without sort order, everything works just fine: q = models.Contact.all(); q.filter("location = ", x); if(cur_search_cursor != None): q.with_cursor(cur_search_cursor); results = q.fetch(limit = max_fetch) cursor = q.cursor(); The above query proper...
[ "Figured it out... the 'name' field is a TextProperty. A TextProperty is not orderable, as per the documentation:\nhttp://code.google.com/appengine/docs/python/datastore/typesandpropertyclasses.html\nThat was a waste of three hours.\n" ]
[ 4 ]
[]
[]
[ "fetch", "google_app_engine", "python" ]
stackoverflow_0004551573_fetch_google_app_engine_python.txt
Q: pythonic way of modifying a mutable inside an immutable let's say I have a class that behaves as an int to the outside world, but in fact is a mutable object that has a fixed place within several structures. if n is my object, I can update it now by writing n.update(34), but I find I'm always wanting to write n = ...
pythonic way of modifying a mutable inside an immutable
let's say I have a class that behaves as an int to the outside world, but in fact is a mutable object that has a fixed place within several structures. if n is my object, I can update it now by writing n.update(34), but I find I'm always wanting to write n = 34 instead. I've glanced over http://docs.python.org/referenc...
[ "Your basic obj.value = newvalue is basically the best, most understandable way. As you surmise, it is not possible to override assignment in Python.\nYou could implement __call__() on your class to do the assignment, so that you can just do obj(newvalue). However, it's not at all clear to the casual reader that th...
[ 3 ]
[]
[]
[ "class", "default", "internals", "object", "python" ]
stackoverflow_0004551790_class_default_internals_object_python.txt
Q: Tkinter Cxfreeze Error I'm trying to make an exe in Windows out of python I developed in Linux. The program works on it's own in python under Windows, and when I use cxfreeze it completes and makes the exe. However when I run it I get: C:\projects\0802001S\dist>listen.exe Traceback (most recent call last): Fil...
Tkinter Cxfreeze Error
I'm trying to make an exe in Windows out of python I developed in Linux. The program works on it's own in python under Windows, and when I use cxfreeze it completes and makes the exe. However when I run it I get: C:\projects\0802001S\dist>listen.exe Traceback (most recent call last): File "C:\Python26\lib\site-pack...
[ "I just ran into something similar. The conclusion I have so far is to copy both tcl8.5 and tk8.5 into the directory where you're running listen.exe (dist/build dir).\nI was also on the cx_freeze mailinglist and there was mentioning about the hook possibly only running on Unix since it was never tested in Windows a...
[ 1 ]
[]
[]
[ "exe", "python", "tkinter", "windows" ]
stackoverflow_0003888011_exe_python_tkinter_windows.txt
Q: Python-like decorators in Java? I spend most of my time programming in Python, so forgive me if my approach to this problem is short-sited: I want to have certain methods of a class require login credentials. Simply, each method should check whether the class variable user is set, and if so, continue, but if not, ...
Python-like decorators in Java?
I spend most of my time programming in Python, so forgive me if my approach to this problem is short-sited: I want to have certain methods of a class require login credentials. Simply, each method should check whether the class variable user is set, and if so, continue, but if not, spit out a "you need to login" messag...
[ "One way to solve this in Java is to use an Aspect-oriented programming tool. One such tool is AspectJ. You will probably find that this type of problem is an example that is commonly used to motivate AOP.\nAOP might be a pretty heavyweight way to solve this particular problem, so you may want to explore just addin...
[ 16, 8, 7 ]
[]
[]
[ "java", "python" ]
stackoverflow_0004551457_java_python.txt
Q: ImportError in Django with FastCGI & Lighttpd However, I am very new to django and lighttpd and have very rough idea about FastCGI. I have a django project named 'myproject' under my "server.document-root". When I try to browse the following url: http://192.168.1.198:8093/myproject.fcgi I get an import error sayi...
ImportError in Django with FastCGI & Lighttpd
However, I am very new to django and lighttpd and have very rough idea about FastCGI. I have a django project named 'myproject' under my "server.document-root". When I try to browse the following url: http://192.168.1.198:8093/myproject.fcgi I get an import error saying: Request Method: GET Request URL: http:/...
[ "Ok, since I figured out the problem myself I am answering my own question hoping that it would help other newbies like me..\nThere was a problem with the value of DJANGO_MODULE_SETTINGS.\nSetting it as :\nos.environ['DJANGO_SETTINGS_MODULE'] = \"myproject.settings\"\n\nsolved my ImportError... :-)\n" ]
[ 0 ]
[]
[]
[ "django", "fastcgi", "lighttpd", "python" ]
stackoverflow_0004551828_django_fastcgi_lighttpd_python.txt
Q: Phonemes and Chronemes Is there any methodology/algorithm for computing phonemes and chronemes of a word(text and not audio)? A: Here you have all the explanation of how to compute text to phonemes using neural networks. It is a pretty complex task. Hope it helps.
Phonemes and Chronemes
Is there any methodology/algorithm for computing phonemes and chronemes of a word(text and not audio)?
[ "Here you have all the explanation of how to compute text to phonemes using neural networks. It is a pretty complex task. Hope it helps.\n" ]
[ 1 ]
[]
[]
[ "nlp", "python" ]
stackoverflow_0004552113_nlp_python.txt
Q: Mapping numbers I know this is a noobish question put i could not figure it out >.< I have an number from -1000 to 1000 and I need to map it to numbers 0 to 200. I think it has to do with the map() function but i'm not sure. Thanks A: "0 would be 100, -500, would be 50 and 500 would be 150" Then try the followin...
Mapping numbers
I know this is a noobish question put i could not figure it out >.< I have an number from -1000 to 1000 and I need to map it to numbers 0 to 200. I think it has to do with the map() function but i'm not sure. Thanks
[ "\"0 would be 100, -500, would be 50 and 500 would be 150\"\nThen try the following function:\ndef mapNumber(a):\n return int(a + 1000) / 10\n\nThis way:\nmapNumber(-1000)\n> 0\n\nmapNumber(-500)\n> 50\n\nmapNumber(0)\n> 100\n\nmapNumber(500)\n> 150\n\nmapNumber(1000)\n> 200\n\nThis will map your integers into i...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004552102_python.txt
Q: What is the best way to go about modeling something like Digg? I'm creating a news platform identical to Digg. How would I model its voting mechanism algorithm? I'm looking for a logical/mathematical approach. A: https://reddit.com is a better version of the now abandoned Digg and guess what, reddit's code and ...
What is the best way to go about modeling something like Digg?
I'm creating a news platform identical to Digg. How would I model its voting mechanism algorithm? I'm looking for a logical/mathematical approach.
[ "https://reddit.com is a better version of the now abandoned Digg and guess what, reddit's code and ranking mechanism is open source.\nFind the developer page for reddit here.\nHow Reddit ranking algorithms work (amix.dk)\n" ]
[ 4 ]
[]
[]
[ "algorithm", "matlab", "python", "scipy", "statistics" ]
stackoverflow_0004552534_algorithm_matlab_python_scipy_statistics.txt
Q: How to search a word in a file from a cakephp view? I am working on an app designed on cakephp framework which is taking data from twitter. I have to check the relevancy of the location, if the data in the location section is really relevant (city or a country). For this I have a python file (.py) which has all th...
How to search a word in a file from a cakephp view?
I am working on an app designed on cakephp framework which is taking data from twitter. I have to check the relevancy of the location, if the data in the location section is really relevant (city or a country). For this I have a python file (.py) which has all the reowned cities and all the country names, I have to sea...
[ "You do not do any logic from a view file. Views are only meant to render data already present.\nYou are supposed to gather your data within a Controller. \nIn CakePHP you won't be able to call Python directly. It is possible though to:\n\nCall the Python interpreter directly, i.e. use system or exec call. \nCommun...
[ 0 ]
[]
[]
[ "cakephp", "php", "python" ]
stackoverflow_0004538538_cakephp_php_python.txt
Q: How to get current date and time from DB using SQLAlchemy I need to retrieve what's the current date and time for the database I'm connected with SQLAlchemy (not date and time of the machine where I'm running Python code). I've seen this functions, but they don't seem to do what they say: >>> from sqlalchemy impo...
How to get current date and time from DB using SQLAlchemy
I need to retrieve what's the current date and time for the database I'm connected with SQLAlchemy (not date and time of the machine where I'm running Python code). I've seen this functions, but they don't seem to do what they say: >>> from sqlalchemy import * >>> print func.current_date() CURRENT_DATE >>> print func....
[ "I foud the solution: these functions cannot be used in the way I used (print...), but need to be called inside of the code that interacts with the database. For instance:\nprint select([my_table, func.current_date()]).execute()\n\nor assigned to a field in an insert operation.\nAccidentally I discovered that exist...
[ 8 ]
[]
[]
[ "database", "date", "python", "sqlalchemy", "time" ]
stackoverflow_0004552380_database_date_python_sqlalchemy_time.txt
Q: Iterating over key/value pairs in a dict sorted by keys I have the following code, which just print the key/value pairs in a dict (the pairs are sorted by keys): for word, count in sorted(count_words(filename).items()): print word, count However, calling iteritems() instead of items() produces the same output...
Iterating over key/value pairs in a dict sorted by keys
I have the following code, which just print the key/value pairs in a dict (the pairs are sorted by keys): for word, count in sorted(count_words(filename).items()): print word, count However, calling iteritems() instead of items() produces the same output for word, count in sorted(count_words(filename).iteritems())...
[ "In Python 2.x both will give you the same result. The difference between them is that items constructs a list containing the entire contents of the dictionary whereas iteritems gives you an iterator that fetches the items one at a time. In general iteritems is a better choice because it doesn't require so much mem...
[ 76, 10 ]
[]
[]
[ "python" ]
stackoverflow_0004550645_python.txt
Q: How to chmod files within a python setup.py? I created a python package installation with a setup.py, and i want it to copy a data file in the folder (created for the occasion) ~/.did. The problem is that i have to call setup.py with sudo rights, as it writes in /usr/local/... So when my data file is copied in ~/....
How to chmod files within a python setup.py?
I created a python package installation with a setup.py, and i want it to copy a data file in the folder (created for the occasion) ~/.did. The problem is that i have to call setup.py with sudo rights, as it writes in /usr/local/... So when my data file is copied in ~/.did, only the root user has write access to the fi...
[ "I think it would be better, and more customary, to not write to the installer's home directory any config files at all. What about other users? Better would be to have your code check, on initialization, if that file exists for the user running it and only add a new one if it does not.\n", "For me, you're looki...
[ 4, 0 ]
[]
[]
[ "chmod", "linux", "python", "security", "setup.py" ]
stackoverflow_0004552689_chmod_linux_python_security_setup.py.txt
Q: Split string and just get number in python? I have a string like "GoTo: 7018 6453 12654\n" I just want get the number something like this ['7018', '6453', '12654'], I tries regular expression but I can't split string to get just number here is my code: Sample 1: splitter = re.compile(r'\D'); match1 = splitter.spli...
Split string and just get number in python?
I have a string like "GoTo: 7018 6453 12654\n" I just want get the number something like this ['7018', '6453', '12654'], I tries regular expression but I can't split string to get just number here is my code: Sample 1: splitter = re.compile(r'\D'); match1 = splitter.split("GoTo: 7018 6453 12654\n") my output is: ['', ...
[ "If all your numbers are positive integers, you can do that without regular expressions by using the isdigit() method:\n>>> text = \"GoTo: 7018 6453 12654\\n\"\n>>> [token for token in text.split() if token.isdigit()]\n['7018', '6453', '12654']\n\n", ">>> re.findall(r'\\d+', 'GoTo: 7018 6453 12654\\n')\n['7018', ...
[ 15, 7, 4, 2, 1 ]
[]
[]
[ "python", "split", "string" ]
stackoverflow_0004553113_python_split_string.txt
Q: Options for creating forms, distributing them and collecting info What options do I have for creating a form intended for collecting data from a potentially big amount of people? (Preferably in Python) I am looking for options other than HTML forms. PDF Forms seem to be an option, but my tendency until now has bee...
Options for creating forms, distributing them and collecting info
What options do I have for creating a form intended for collecting data from a potentially big amount of people? (Preferably in Python) I am looking for options other than HTML forms. PDF Forms seem to be an option, but my tendency until now has been to avoid them. Standard desktop app seems to be the way to go, but it...
[ "So you have a requirement to NOT use a website for this? That's strange. But PDF forms is OK? And it's potentially a large amount of people? You realize the only way to collect that data is that people fill in the PDF form, save it and e-mail it.\nOr well, a lot of people will print the form out and send it by sna...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0004553034_python.txt
Q: Does anyone have experience with PyS60 mobile development I am in the position of having to make a technology choice early in a project which is targetted at mobile phones. I saw that there is a python derivative for S60 and wondered whether anyone could share experiences, good and bad, and suggest appropriate ID...
Does anyone have experience with PyS60 mobile development
I am in the position of having to make a technology choice early in a project which is targetted at mobile phones. I saw that there is a python derivative for S60 and wondered whether anyone could share experiences, good and bad, and suggest appropriate IDE's and emulators. Please don't tell me that I should be develo...
[ "PyS60 -- its cool :)\nI worked quite a lot on PyS60 ver 1.3 FP2. It is a great language to port your apps on \nSymbian Mobiles and Powerful too. I did my Major project in PyS60, which was a GSM locator(its not the latest version) app for Symbian phones. \nThere is also a very neat py2sis utility which converts you...
[ 8, 3, 3, 1, 0, 0, 0 ]
[]
[]
[ "mobile", "pys60", "python" ]
stackoverflow_0000173484_mobile_pys60_python.txt
Q: Python : Running a loop during a precise duration I need to run a loop during a precise duration. For example, the code I'm trying to make would look like that : initialize and lauch timer while timer<10000sec: do things Do you know how to do this ? Thank you :) A: stop = time.time()+10000 while time.time...
Python : Running a loop during a precise duration
I need to run a loop during a precise duration. For example, the code I'm trying to make would look like that : initialize and lauch timer while timer<10000sec: do things Do you know how to do this ? Thank you :)
[ "stop = time.time()+10000\nwhile time.time() < stop:\n do things\n\nThis requires that each run through the loop is sufficiently short so that you read the current time often enough (for the preciseness that you want to achieve).\n" ]
[ 6 ]
[]
[]
[ "python", "time" ]
stackoverflow_0004553269_python_time.txt
Q: Break the nested (double) loop in Python I use the following method to break the double loop in Python. for word1 in buf1: find = False for word2 in buf2: ... if res == res1: print "BINGO " + word1 + ":" + word2 find = True if find: break Is there a bett...
Break the nested (double) loop in Python
I use the following method to break the double loop in Python. for word1 in buf1: find = False for word2 in buf2: ... if res == res1: print "BINGO " + word1 + ":" + word2 find = True if find: break Is there a better way to break the double loop?
[ "The recommended way in Python for breaking nested loops is... Exception\nclass Found(Exception): pass\ntry:\n for i in range(100):\n for j in range(1000):\n for k in range(10000):\n if i + j + k == 777:\n raise Found\nexcept Found:\n print i, j, k \n\n", "Pr...
[ 65, 60, 15, 14 ]
[]
[]
[ "nested_loops", "python" ]
stackoverflow_0002597104_nested_loops_python.txt
Q: Python or django reporting tools not how to generate pdf, like asp.net crystal report Python or django reporting tools not how to generate pdf, like asp.net crystal report A: Look at Geraldo Reports. Python Report Lab is a level below in the stack but is very, very easy to roll your own report classes based in ...
Python or django reporting tools not how to generate pdf, like asp.net crystal report
Python or django reporting tools not how to generate pdf, like asp.net crystal report
[ "\nLook at Geraldo Reports. \nPython Report Lab is a level below in the stack but is very, very easy to roll your own report classes based in this toolkit.\nIf you love Crystal, you may like to look at Jasper Reports and the wonderful iReport. Once defined in iReport, you can render your reports calling Jasper clas...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0004553466_python.txt
Q: Python urllib2 http -1 error I have this code, that supposed to work but I'm getting strange errors, for other user this code works fine. # -*- coding: utf-8 -*- import re, sys import urllib2 import urllib2_file user_hash='MTggMzc6T1dZgggggzWXpWbVptggggHTXlOV1F5WWgggggggWT0%3D' text_file = 'sveikinimas.txt' pos...
Python urllib2 http -1 error
I have this code, that supposed to work but I'm getting strange errors, for other user this code works fine. # -*- coding: utf-8 -*- import re, sys import urllib2 import urllib2_file user_hash='MTggMzc6T1dZgggggzWXpWbVptggggHTXlOV1F5WWgggggggWT0%3D' text_file = 'sveikinimas.txt' postdata = { 'type': '40', ...
[ "The error message is from urllib2_file. I believe, it is not proper. You may just wish to comment it and try if it that module is not being used.\nI also see that in the post data, you are having another dictionary inside. It should not be the case. Just have the contents of the file. Read the file and have it the...
[ 1 ]
[]
[]
[ "http", "python", "urllib2" ]
stackoverflow_0004553550_http_python_urllib2.txt
Q: Python Problem With sockets Hy, i'm try to create a simple Telnet Server in python, but the server receve just one command send by Client... Code: from socket import * server = socket(AF_INET, SOCK_STREAM) server.bind((gethostname(), 23)) server.listen(5) while 1: (connection, address) = server.accept() d...
Python Problem With sockets
Hy, i'm try to create a simple Telnet Server in python, but the server receve just one command send by Client... Code: from socket import * server = socket(AF_INET, SOCK_STREAM) server.bind((gethostname(), 23)) server.listen(5) while 1: (connection, address) = server.accept() data = connection.recv(1024) pr...
[ "Taking the server.accept outside the while loop will allow your client to send in more commands:\nfrom socket import *\n\nserver = socket(AF_INET, SOCK_STREAM)\nserver.bind((gethostname(), 23))\nserver.listen(5)\n\n(connection, address) = server.accept()\nwhile 1:\n data = connection.recv(1024)\n print data\...
[ 2, 1, 0 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0004553784_python_sockets.txt
Q: TK_LIBRARY and TCL_LIBRARY environment variables on Ubuntu I'm trying to get _tkinter to import into Python. I suspect it may be due to not having values defined for the environment variables TK_LIBRARY and TCL_LIBRARY. This is as it stands after using apt-get for python-tk, tcl, and tk. If I have to set the en...
TK_LIBRARY and TCL_LIBRARY environment variables on Ubuntu
I'm trying to get _tkinter to import into Python. I suspect it may be due to not having values defined for the environment variables TK_LIBRARY and TCL_LIBRARY. This is as it stands after using apt-get for python-tk, tcl, and tk. If I have to set the environment variables manually, what would I set them to? I am usi...
[ "No, setting TK_LIBRARY and TCL_LIBRARY should not be necessary. I suspect you are invoking a Python interpreter different from /usr/bin/python, or /usr/bin/python has been changed to point to a different Python interpreter than the one that goes with the python-tk package. Ubuntu 10.10 ships with Python 2.6 by def...
[ 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0004553869_python_tkinter.txt
Q: How do I add additional arguments to button.connect in PyGTK? I want to pass 2 ComboBox instances to a a method and use them there (e.g., print their active selection). I have something similar to the following: class GUI(): ... def gui(self): ... combobox1 = gtk.combo_box_new_text() # code for in...
How do I add additional arguments to button.connect in PyGTK?
I want to pass 2 ComboBox instances to a a method and use them there (e.g., print their active selection). I have something similar to the following: class GUI(): ... def gui(self): ... combobox1 = gtk.combo_box_new_text() # code for inserting some values into the combobox combobox2 = gtk.combo_box...
[ "do something like this:\nbtn_new.connect(\"clicked\", self.comboprint, combobox1, combobox2)\n\nand in your callback comboprint it should be something like this:\ndef comboprint(self, widget, *data):\n # Widget = btn_new\n # data = [clicked_event, combobox1, combobox2]\n ... \n\n", "I would solve this ...
[ 11, 1 ]
[]
[]
[ "pygtk", "python" ]
stackoverflow_0004553591_pygtk_python.txt
Q: what is missing that prevents my IDLE from working? Installed Ubuntu 10.10 and Python 2.5.5. IDLE did not start from the terminal so I went into the Python interpreter and did "import _tkinter". The package was not found. After searching a bit, I found that Ubuntu/debian might not include _tkinter so I proceede...
what is missing that prevents my IDLE from working?
Installed Ubuntu 10.10 and Python 2.5.5. IDLE did not start from the terminal so I went into the Python interpreter and did "import _tkinter". The package was not found. After searching a bit, I found that Ubuntu/debian might not include _tkinter so I proceeded to "sudo apt-get install python-tk" as per my searches....
[ "There's an IDLE package in the Ubuntu software center that you can install. Install that and IDLE will work.\nUPDATE\nIt is indeed in the Ubuntu software center on Ubuntu 10.10. Evidence:\n \n", "Use Synaptic Package Manager (System > Administration > Synaptic Package Manager). Search for \"idle\".\n", "The p...
[ 1, 1, 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0004551565_python_tkinter.txt
Q: how to modify the reverse url for GET? url: /foo/ href="{% url foo %}" This is my url. I want to send some GET data with this. So, can I modify the href for url: /foo/?bar=1 here. A: something like this maybe: href="{% url foo %}?bar=1"
how to modify the reverse url for GET?
url: /foo/ href="{% url foo %}" This is my url. I want to send some GET data with this. So, can I modify the href for url: /foo/?bar=1 here.
[ "something like this maybe:\nhref=\"{% url foo %}?bar=1\"\n\n" ]
[ 4 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004554180_django_python.txt
Q: pgp algorithm specific data extraction would this be a correct way extract the algorithm specific values from a pgp key? i have a weird problem where all but the last values for DSA and ElGamal can be extracted properly, which then messes up the rest of my program def algorithm(data, pka): #data is a large bin...
pgp algorithm specific data extraction
would this be a correct way extract the algorithm specific values from a pgp key? i have a weird problem where all but the last values for DSA and ElGamal can be extracted properly, which then messes up the rest of my program def algorithm(data, pka): #data is a large binary string with the algorithm specific value...
[ "I'm not familiar with Python, but it seems that data = data[16 + length:] skips 16 + length: bits in data, but in OpenPGP multiprecision integers body is padded to byte boundary, i.e. you should write something like data = data[16 + (((length + 7)/8)*8):]\n" ]
[ 1 ]
[]
[]
[ "information_extraction", "parsing", "pgp", "python" ]
stackoverflow_0004535873_information_extraction_parsing_pgp_python.txt
Q: Except Python codec errors? File "/usr/lib/python3.1/codecs.py", line 300, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf8' codec can't decode byte 0x92 in position 805: invalid start byte Hi, I get this exception. How do I catch it, and continue reading ...
Except Python codec errors?
File "/usr/lib/python3.1/codecs.py", line 300, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf8' codec can't decode byte 0x92 in position 805: invalid start byte Hi, I get this exception. How do I catch it, and continue reading my files when I get this exceptio...
[ "Look at http://docs.python.org/py3k/library/codecs.html. When you open the codecs stream, you probably want to use the additional argument errors='ignore'\nIn Python 3, sys.stdin is by default opened as a text stream (see http://docs.python.org/py3k/library/sys.html), and has strict error checking.\nYou need to re...
[ 8 ]
[]
[]
[ "decode", "encode", "python" ]
stackoverflow_0004554287_decode_encode_python.txt
Q: Repeated host lookups failing in urllib2 I have code which issues many HTTP GET requests using Python's urllib2, in several threads, writing the responses into files (one per thread). During execution, it looks like many of the host lookups fail (causing a name or service unknown error, see appended error log for ...
Repeated host lookups failing in urllib2
I have code which issues many HTTP GET requests using Python's urllib2, in several threads, writing the responses into files (one per thread). During execution, it looks like many of the host lookups fail (causing a name or service unknown error, see appended error log for an example). Is this due to a flaky DNS serv...
[ "This is not a Python problem, on Linux systems make sure nscd (Name Service Cache Daemon) is actually running. \nUPDATE:\nAnd looking at your code you are never calling page.close() hence leaking sockets.\n" ]
[ 3 ]
[]
[]
[ "dns", "http", "multithreading", "python", "urllib2" ]
stackoverflow_0004555026_dns_http_multithreading_python_urllib2.txt
Q: Python interpreter invocation with "-c" and indentation issues I'm trying to invoke Python using the "-c" argument to allow me to run some arbitrary python code easily, like this: python.exe -c "for idx in range(10): print idx" Now this code works fine, from within my batch file, however, I'm running into problems...
Python interpreter invocation with "-c" and indentation issues
I'm trying to invoke Python using the "-c" argument to allow me to run some arbitrary python code easily, like this: python.exe -c "for idx in range(10): print idx" Now this code works fine, from within my batch file, however, I'm running into problems when I want to do anything more than this. Consider the following P...
[ "You need to enter the command string as a multi-line argument. With linux, this is as easy as using the enter key, e.g. (note that bash adds the > characters, I didn't have to type them):\n$ python -c \"foo = 'bar'\n> for idx in range(10):\n> print idx\"\n\nOn Windows though, you need to type the ^ key before ...
[ 3, 2 ]
[]
[]
[ "cmd", "interpreter", "python", "syntax_error" ]
stackoverflow_0004555010_cmd_interpreter_python_syntax_error.txt
Q: How to load current buffer into Python interpreter in Emacs? I'm trying to use emacs to edit and run python programs (emacs23 and python 2.6 on Ubuntu 10.10). I read a file into Emacs (C-x -C-f) I start the interperter (Menu Python - Start interpreter, I haven't found the keyboard shortcut for this yet) Emacs s...
How to load current buffer into Python interpreter in Emacs?
I'm trying to use emacs to edit and run python programs (emacs23 and python 2.6 on Ubuntu 10.10). I read a file into Emacs (C-x -C-f) I start the interperter (Menu Python - Start interpreter, I haven't found the keyboard shortcut for this yet) Emacs split the frame in two windows I place the cursor in the python file...
[ "You may want to hit \"C-c C-z\" (switch to interpreter) to see the results of and buffers or regions you evaluated.\n" ]
[ 9 ]
[]
[]
[ "emacs", "python" ]
stackoverflow_0004555224_emacs_python.txt
Q: Bug or feature: cloning a numpy array w/ slicing Following up to David Morrissey's answer on 'How to clone a list in python?' I was running some performance tests and hit unexpected behavior when working w/ numpy arrays. I know that a numpy array can/ should be cloned w/ clone = numpy.array(original) or clone = n...
Bug or feature: cloning a numpy array w/ slicing
Following up to David Morrissey's answer on 'How to clone a list in python?' I was running some performance tests and hit unexpected behavior when working w/ numpy arrays. I know that a numpy array can/ should be cloned w/ clone = numpy.array(original) or clone = numpy.copy(original) but have incorrectly assumed that...
[ "In numpy, slices are references or \"views\" on the original array, so they are not copies. That is by design, not a bug. The reason is that a copy is not as useful as a view.\n" ]
[ 11 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0004555431_numpy_python.txt
Q: Generating a characterized unique id in Python am planning to create a unique ID from characters and numbers as well. The ID should look something like this XXXX-XXXX-XXXX-XXXX where X is a combination of numbers, small and cap letters. This Id will be stored in a mysql database and will be incremented to maintain...
Generating a characterized unique id in Python
am planning to create a unique ID from characters and numbers as well. The ID should look something like this XXXX-XXXX-XXXX-XXXX where X is a combination of numbers, small and cap letters. This Id will be stored in a mysql database and will be incremented to maintain consistency of data. Any advice on how to start?
[ "Use the uuid module;\n>>> import uuid\n\n# make a UUID based on the host ID and current time\n>>> uuid.uuid1()\nUUID('a8098c1a-f86e-11da-bd1a-00112444be1e')\n\n# make a UUID using an MD5 hash of a namespace UUID and a name\n>>> uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org')\nUUID('6fa459ea-ee8a-3ca4-894e-db77e160355...
[ 15, 3 ]
[]
[]
[ "python" ]
stackoverflow_0004555511_python.txt
Q: Send an image file using sockets , Android to Python Im trying to send an image from an android client to a python server , I have achieved it before with a python test client and the server. Basically my client app takes a form consisting of users details and an image. Once the user selects the image I get the ur...
Send an image file using sockets , Android to Python
Im trying to send an image from an android client to a python server , I have achieved it before with a python test client and the server. Basically my client app takes a form consisting of users details and an image. Once the user selects the image I get the uri in the onActivityResult method and parse it to a string ...
[ "Consider using methods such as File.exists() and File.isFile() to validate if the path is OK and whether the image is really there\nAlso check if the image even hits the wire - using tcpdump ro wireshark\n", "I have solved it , as I use selectedImageUri = Uri.fromFile(photo); to get the uri if its taken by the c...
[ 0, 0 ]
[]
[]
[ "android", "file", "python", "sockets" ]
stackoverflow_0004548416_android_file_python_sockets.txt
Q: Python regex help I am trying to make a regex that finds all names, url and phone numbers in an html page. But I'm having trouble with the phone number part. I think the problem with the numbers part is that is searches until it finds the </strong> but in that process it skips people, instead of making a empty str...
Python regex help
I am trying to make a regex that finds all names, url and phone numbers in an html page. But I'm having trouble with the phone number part. I think the problem with the numbers part is that is searches until it finds the </strong> but in that process it skips people, instead of making a empty string if the person has n...
[ "import lxml.html\n\nroot = lxml.html.parse(\"http://my.example.com/page.html\").getroot()\nrows = root.xpath(\"//table[@id='contactinfo']/tr\")\n\nfor r in rows:\n nameText = r.xpath(\"td[@class='lablinksName']/div/text() | td[@class='lablinksName']/div/a/text()\")\n name = u''.join(nameText).strip()\n\n ...
[ 1, 0, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0004547234_python_regex.txt
Q: tkinter threaded gui instance halts all further spawns When I create a tkinter window instance using a thread, even though the window is destroyed after execution, and the thread is joined; I can't make another tkinter window later on in the program flow. Why? def on_button_click(root): //destroys window on butt...
tkinter threaded gui instance halts all further spawns
When I create a tkinter window instance using a thread, even though the window is destroyed after execution, and the thread is joined; I can't make another tkinter window later on in the program flow. Why? def on_button_click(root): //destroys window on button click root.destroy() def init(): //thread calls thi...
[ "From what I can gather using my Google-foo, the problem is that the Tk event loop (which is created during your call to root.mainloop()) is single-threaded and you can only have one instance of it at a time. So that's probably why its getting stuck at that location. Your thread is properly setting up the Tk subsys...
[ 1 ]
[]
[]
[ "multithreading", "python", "tkinter" ]
stackoverflow_0004554793_multithreading_python_tkinter.txt
Q: Python and Unicode: How everything should be Unicode Forgive if this a long a question: I have been programming in Python for around six months. Self taught, starting with the Python tutorial and then SO and then just using Google for stuff. Here is the sad part: No one told me all strings should be Unicode. No, I...
Python and Unicode: How everything should be Unicode
Forgive if this a long a question: I have been programming in Python for around six months. Self taught, starting with the Python tutorial and then SO and then just using Google for stuff. Here is the sad part: No one told me all strings should be Unicode. No, I am not lying or making this up, but where does the tutori...
[ "The \"always use Unicode\" suggestion is primarily to make the transition to Python 3 easier. If you have a lot of non-Unicode string access in your code, it'll take more work to port it.\nAlso, you shouldn't have to decide on a case-by-case basis whether a string should be stored as Unicode or not. You shouldn'...
[ 13, 10, 5, 3, 2 ]
[ "1/2) Personally I've never heard of \"always use unicode\". That seems pretty stupid to me. I guess I understand if you plan to support other languages that need unicode support. But other than that I wouldn't do that, it seems like more of a pain than it's worth.\n3) I would just read/write the standard way and e...
[ -2 ]
[ "python", "unicode" ]
stackoverflow_0004540791_python_unicode.txt
Q: Python imports issue I have a Utilities module which defines a few functions which are repeatedly used and am also adding in some constants. I'm running into trouble importing these constants though... Let's say I'm working in class A, and I have a class in my constants also named A from Utils.Constants import A ...
Python imports issue
I have a Utilities module which defines a few functions which are repeatedly used and am also adding in some constants. I'm running into trouble importing these constants though... Let's say I'm working in class A, and I have a class in my constants also named A from Utils.Constants import A as DistinctA class A(objec...
[ "The identifier after 'from' must point to a module; you can't refer to a class. While I'm not qualified to say whether your nested classes are 'pythonic', I have never seen it done like that before. I'd be more inclined to create a constants.py module that contains the A class. Then you could do this:\nfrom con...
[ 3 ]
[]
[]
[ "import", "python" ]
stackoverflow_0004556060_import_python.txt
Q: SWIG C++ bindings with callback I am writing some SWIG/Python bindings for some C++ code. This is for what is called the Kinect Accidental API, I have the motor and led functions working. The callbacks to the Listener class which parse and populate the RGB and Depth buffers do not seem to get called from SWIG. The...
SWIG C++ bindings with callback
I am writing some SWIG/Python bindings for some C++ code. This is for what is called the Kinect Accidental API, I have the motor and led functions working. The callbacks to the Listener class which parse and populate the RGB and Depth buffers do not seem to get called from SWIG. The data capture threads evidently start...
[ "By coincidence, I happen to be looking into callbacks with SWIG at the moment.\nThe SWIG 2.0 documentation says this:\n\nSWIG provides full support for function pointers provided that the callback functions are defined in C and not in the target language. ... However, existing C functions can be used as arguments ...
[ 3, 3 ]
[]
[]
[ "c++", "kinect", "python", "swig" ]
stackoverflow_0004255806_c++_kinect_python_swig.txt
Q: Python would not let me use methods inside the class while the class definition has not been finished I am using Python 2.6 as a batch script replacement. It will be started by double-clicking, so all output to stdout will be lost/ignored by the user. So, I decided to add logging, and to make matters simple, I wro...
Python would not let me use methods inside the class while the class definition has not been finished
I am using Python 2.6 as a batch script replacement. It will be started by double-clicking, so all output to stdout will be lost/ignored by the user. So, I decided to add logging, and to make matters simple, I wrote a class for that. The idea is that I can use Logging.Logger anywhere in my code, and the logger will be ...
[ "You're getting that exception because you're calling _assert() rather than Logging._assert(). The error message tells you it's looking for _assert() in the module's global namespace rather than in the class namespace; to get it to look in the latter, you have to explicitly specify it. \nOf course, in this case, yo...
[ 5, 2, 1, 1 ]
[]
[]
[ "class", "methods", "oop", "python", "python_2.6" ]
stackoverflow_0004556289_class_methods_oop_python_python_2.6.txt
Q: Python: Importing a variable inside of a infinite loop I have two modules, a host and a scanner. Both loop indefinitely to communicate with the serial ports. I want to import the variable "bestchannel" from scanner into host but by importing it, the while loop inside scanner runs first and loops forever. I want ea...
Python: Importing a variable inside of a infinite loop
I have two modules, a host and a scanner. Both loop indefinitely to communicate with the serial ports. I want to import the variable "bestchannel" from scanner into host but by importing it, the while loop inside scanner runs first and loops forever. I want each module to run separately but be able to send each other d...
[ "So again, if you haven't explored implementing your code using threads then I'd suggest that to get two loops to run at the same time. So something like this:\nimport threading\nimport Queue\n\ndef host(dataQueue):\n \"\"\"\n Host code goes here.\n \"\"\"\n # Check dataQueue for incoming data among oth...
[ 1 ]
[]
[]
[ "import", "infinite_loop", "loops", "python", "serial_port" ]
stackoverflow_0004555866_import_infinite_loop_loops_python_serial_port.txt
Q: Django: query with ManyToManyField count? In Django, how do I construct a COUNT query for a ManyToManyField? My models are as follows, and I want to get all the people whose name starts with A and who are the lord or overlord of at least one Place, and order the results by name. class Manor(models.Model): lord...
Django: query with ManyToManyField count?
In Django, how do I construct a COUNT query for a ManyToManyField? My models are as follows, and I want to get all the people whose name starts with A and who are the lord or overlord of at least one Place, and order the results by name. class Manor(models.Model): lord = models.ManyToManyField(Person, null=True, re...
[ "Actually it's not the count you're interested in here, but just whether or not there are any members in that relationship. \nQ(lord__isnull=False) | Q(overlord__isnull=False) \n\n", "In this case, better resort to raw SQL. \nfor p in Person.objects.raw('SELECT * FROM myapp_person WHERE...'):\n print p\n\n" ]
[ 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004556294_django_python.txt