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: Login input Suppose My system login ID is tom2deu. i have one Python program. Now i am going to modified this Python program. My question Can we print my login ID to a seprate notepad or any other file ? means can we print any person detail(login ID) who had logged the system and modified the program. A: I'm ...
Login input
Suppose My system login ID is tom2deu. i have one Python program. Now i am going to modified this Python program. My question Can we print my login ID to a seprate notepad or any other file ? means can we print any person detail(login ID) who had logged the system and modified the program.
[ "I'm not sure what problem you're trying to solve, but if you want to track changes to source files you should probably use a version control system such as Subversion. In a nutshell, it will track all the changes to your source files and also manage conflicts (when two people try to change a file at the same time)...
[ 2, 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001030966_python.txt
Q: what is python equivalent to PHP $_SERVER? I couldn't find out python equivalent to PHP $_SERVER. Is there any? Or, what are the methods to bring equivalent results? Thanks in advance. A: Using mod_wsgi, which I would recommend over mod_python (long story but trust me) ... Your application is passed an environ...
what is python equivalent to PHP $_SERVER?
I couldn't find out python equivalent to PHP $_SERVER. Is there any? Or, what are the methods to bring equivalent results? Thanks in advance.
[ "Using mod_wsgi, which I would recommend over mod_python (long story but trust me) ... Your application is passed an environment variable such as:\ndef application(environ, start_response):\n ...\n\nAnd the environment contains typical elements from $_SERVER in PHP\n...\nenviron['REQUEST_URI'];\n...\n\nAnd so on...
[ 11, 1 ]
[]
[]
[ "php", "python" ]
stackoverflow_0001031192_php_python.txt
Q: encryption/decryption of one time password in python how to encrypt one time password using the public key and again recover it by the private key of the user , i need to do it using python A: You can use Python's encryption library called PyCrypto (www.pycrypto.org). Here's some overview of Public Key encrypti...
encryption/decryption of one time password in python
how to encrypt one time password using the public key and again recover it by the private key of the user , i need to do it using python
[ "You can use Python's encryption library called PyCrypto (www.pycrypto.org). Here's some overview of Public Key encryption using PyCrypto: http://www.dlitz.net/software/pycrypto/doc/#crypto-publickey-public-key-algorithms\n", "Use an encryption library, for example pyopenssl, which looks more up-to-date then pycr...
[ 4, 0 ]
[]
[]
[ "encryption", "python" ]
stackoverflow_0001031588_encryption_python.txt
Q: Profiling self and arguments in python? How do I profile a call that involves self and arguments in python? def performProfile(self): import cProfile self.profileCommand(1000000) def profileCommand(self, a): for i in a: pass In the above example how would I profile just the call to profileCom...
Profiling self and arguments in python?
How do I profile a call that involves self and arguments in python? def performProfile(self): import cProfile self.profileCommand(1000000) def profileCommand(self, a): for i in a: pass In the above example how would I profile just the call to profileCommand? I figured out I need to use runctx for ...
[ "you need to pass locals/globals dict and pass first argument what you will usually type\ne.g.\ncProfile.runctx(\"self.profileCommand(100)\", globals(),locals())\n\nuse something like this\nclass A(object):\n def performProfile(self):\n import cProfile\n cProfile.runctx(\"self.profileCommand(100)\"...
[ 13 ]
[]
[]
[ "profiling", "python" ]
stackoverflow_0001031657_profiling_python.txt
Q: "Adding" Dictionaries in Python? Possible Duplicate: python dict.add_by_value(dict_2) ? My input is two dictionaries that have string keys and integer values. I want to add the two dictionaries so that the result has all the keys of the input dictionaries, and the values are the sum of the input dictionaries' va...
"Adding" Dictionaries in Python?
Possible Duplicate: python dict.add_by_value(dict_2) ? My input is two dictionaries that have string keys and integer values. I want to add the two dictionaries so that the result has all the keys of the input dictionaries, and the values are the sum of the input dictionaries' values. For clarity, if a key appears ...
[ "How about that:\ndict( [ (n, a.get(n, 0)+b.get(n, 0)) for n in set(a)|set(b) ] )\n\nOr without creating an intermediate list (generator is enough):\ndict( (n, a.get(n, 0)+b.get(n, 0)) for n in set(a)|set(b) )\n\n\nPost Scriptum:\nAs a commentator addressed correctly, there is a way to implement that easier with th...
[ 51, 15, 15, 4 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0001031199_dictionary_python.txt
Q: Python: finding keys with unique values in a dictionary? I receive a dictionary as input, and want to return a list of keys for which the dictionary values are unique in the scope of that dictionary. I will clarify with an example. Say my input is dictionary a, constructed as follows: a = dict() a['cat'] = 1 ...
Python: finding keys with unique values in a dictionary?
I receive a dictionary as input, and want to return a list of keys for which the dictionary values are unique in the scope of that dictionary. I will clarify with an example. Say my input is dictionary a, constructed as follows: a = dict() a['cat'] = 1 a['fish'] = 1 a['dog'] = 2 # <-- unique a['bat'] = ...
[ "I think efficient way if dict is too large would be\ncountMap = {}\nfor v in a.itervalues():\n countMap[v] = countMap.get(v,0) + 1\nuni = [ k for k, v in a.iteritems() if countMap[v] == 1]\n\n", "Note that this actually is a bruteforce:\nl = a.values()\nb = [x for x in a if l.count(a[x]) == 1]\n\n", "Here i...
[ 14, 5, 5, 4, 2, 2, 0 ]
[ "You could do something like this (just count the number of occurrences for each value):\ndef unique(a):\n from collections import defaultdict\n count = defaultdict(lambda: 0)\n for k, v in a.iteritems():\n count[v] += 1\n for v, c in count.iteritems():\n if c <= 1:\n yield v\n\...
[ -1, -2 ]
[ "dictionary", "python" ]
stackoverflow_0001032281_dictionary_python.txt
Q: Check if only one variable in a list of variables is set I'm looking for a simple method to check if only one variable in a list of variables has a True value. I've looked at this logical xor post and is trying to find a way to adapt to multiple variables and only one true. Example >>>TrueXor(1,0,0) True >>>TrueX...
Check if only one variable in a list of variables is set
I'm looking for a simple method to check if only one variable in a list of variables has a True value. I've looked at this logical xor post and is trying to find a way to adapt to multiple variables and only one true. Example >>>TrueXor(1,0,0) True >>>TrueXor(0,0,1) True >>>TrueXor(1,1,0) False >>>TrueXor(0,0,0,0,0)...
[ "There isn't one built in but it's not to hard to roll you own:\ndef TrueXor(*args):\n return sum(args) == 1\n\nSince \"[b]ooleans are a subtype of plain integers\" (source) you can sum the list of integers quite easily and you can also pass true booleans into this function as well.\nSo these two calls are homog...
[ 26, 10, 5, 1, 1 ]
[]
[]
[ "python", "xor" ]
stackoverflow_0001032411_python_xor.txt
Q: Decorators that are properties of decorated objects? I want to create a decorator that allows me to refer back to the decorated object and grab another decorator from it, the same way you can use setter/deleter on properties: @property def x(self): return self._x @x.setter def x(self, y): self._x = y Spe...
Decorators that are properties of decorated objects?
I want to create a decorator that allows me to refer back to the decorated object and grab another decorator from it, the same way you can use setter/deleter on properties: @property def x(self): return self._x @x.setter def x(self, y): self._x = y Specifically, I'd like it to act basically the same as proper...
[ "I fixed many little details and the following version seems to work as you require:\ndef listprop(indices):\n def dec(func):\n class c(object):\n def __init__(self, l, obj=None):\n self.l = l\n self.obj = obj\n def __get__(self, obj, cls=None):\n ...
[ 3 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0001033107_decorator_python.txt
Q: Simple User management example for Google App Engine? I am newbie in Google App Engine. While I was going through the tutorial, I found several things that we do in php-mysql is not available in GAE. For example in dataStore auto increment feature is not available. Also I am confused about session management in GA...
Simple User management example for Google App Engine?
I am newbie in Google App Engine. While I was going through the tutorial, I found several things that we do in php-mysql is not available in GAE. For example in dataStore auto increment feature is not available. Also I am confused about session management in GAE. Over all I am confused and can not visualize the whole t...
[ "I tend to use my own user and session manangement\nFor my web handlers I will attach a decorator called session and one called authorize. The session decorator will attach a session to every request, and the authorize decorator will make sure that the user is authorised.\n(A word of caution, the authorize decorat...
[ 22, 6, 1 ]
[]
[]
[ "google_app_engine", "php", "python" ]
stackoverflow_0001030293_google_app_engine_php_python.txt
Q: Pylons - use Python 2.5 or 2.6? Which version of Python is recommended for Pylons, and why? A: Pylons itself says it needs at least 2.3, and recommends 2.4+. Since 2.6 is production ready, I'd use that. A: You can use Python 2.3 to 2.6, though 2.3 support will be dropped in the next version. You can't use Pyth...
Pylons - use Python 2.5 or 2.6?
Which version of Python is recommended for Pylons, and why?
[ "Pylons itself says it needs at least 2.3, and recommends 2.4+. Since 2.6 is production ready, I'd use that.\n", "You can use Python 2.3 to 2.6, though 2.3 support will be dropped in the next version. You can't use Python 3 yet.\nThere's no real reason to favor Python 2.5 or 2.6 at this point. Use what works best...
[ 5, 2, 1 ]
[]
[]
[ "pylons", "python" ]
stackoverflow_0001033367_pylons_python.txt
Q: Specifying TkInter Callbacks In Dictionary For Display Launcher Function I am having trouble building a Python function that launches TkInter objects, with commands bound to menu buttons, using button specifications held in a dictionary. SITUATION I am building a GUI in Python using TkInter. I have written a Disp...
Specifying TkInter Callbacks In Dictionary For Display Launcher Function
I am having trouble building a Python function that launches TkInter objects, with commands bound to menu buttons, using button specifications held in a dictionary. SITUATION I am building a GUI in Python using TkInter. I have written a Display class (based on the GuiMaker class in Lutz, "Programming Python") that sho...
[ "When your lambda executes is when scope applies, but the issue is a bit subtler.\nIn the first case that lambda is a nested function of launchEmployee so the Python compiler (when it compiles the enclosing function) knows to scan its body for references to local variables of the enclosing function and forms the cl...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0001033130_python.txt
Q: Template driven feed parsing Requirements: I have a Python project which parses data feeds from multiple sources in varying formats (Atom, valid XML, invalid XML, CSV, almost-garbage, etc...) and inserts the resulting data into a database. The catch is the information required to parse each of the feeds must also ...
Template driven feed parsing
Requirements: I have a Python project which parses data feeds from multiple sources in varying formats (Atom, valid XML, invalid XML, CSV, almost-garbage, etc...) and inserts the resulting data into a database. The catch is the information required to parse each of the feeds must also be stored in the database. Current...
[ "Instead of evaling scripts, maybe you should consider making a package of them?\nParsing CSV is one thing — the format is simple and regular, parsing XML requires completely another approach. Considering you don't want to write every single parser from scratch, why not just write a bunch of small modules, each hav...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0001032976_python.txt
Q: Monkeypatching a method call in Python How do I put off attribute access in Python? Let's assume we have: def foo(): ... class Bar: ... bar = Bar() Is it possible to implement Bar so that any time bar is accessed, a value returned by the callback foo() would be provided? bar name alr...
Monkeypatching a method call in Python
How do I put off attribute access in Python? Let's assume we have: def foo(): ... class Bar: ... bar = Bar() Is it possible to implement Bar so that any time bar is accessed, a value returned by the callback foo() would be provided? bar name already exists in the context. That's why it's ...
[ "I guess you want to link some attribute \"data\" to foo:\nclass Bar:\n data = property(lambda self: foo())\n\n\nbar = Bar()\nbar.data # calls foo()\n\n", "You're basically asking for a way to hijack a variable (how would you reassign it?) in the module namespace, which is not possible in Python.\nYou'll have ...
[ 6, 2, 0, 0, 0, 0, 0 ]
[]
[]
[ "callback", "properties", "python", "reference" ]
stackoverflow_0001033519_callback_properties_python_reference.txt
Q: python class attribute inheritance I am trying to save myself a bit of typing by writing the following code, but it seems I can't do this: class lgrAdminObject(admin.ModelAdmin): fields = ["title","owner"] list_display = ["title","origin","approved", "sendToFrames"] class Photos(lgrAdminObject): field...
python class attribute inheritance
I am trying to save myself a bit of typing by writing the following code, but it seems I can't do this: class lgrAdminObject(admin.ModelAdmin): fields = ["title","owner"] list_display = ["title","origin","approved", "sendToFrames"] class Photos(lgrAdminObject): fields.extend(["albums"]) why doesn't that w...
[ "Inheritance applies after the class's body executes. In the class body, you can use lgrAdminObject.fields -- you sure you want to alter the superclass's attribute rather than making a copy of it first, though? Seems peculiar... I'd start with a copy:\nclass Photos(lgrAdminObject):\n fields = list(lgrAdminObject...
[ 7, 4, 2, 1 ]
[]
[]
[ "class", "django", "inheritance", "python" ]
stackoverflow_0001033443_class_django_inheritance_python.txt
Q: Python List Question i have an issue i could use some help with, i have python list that looks like this: fail = [ ['da39a3ee5e6b4b0d3255bfef95601890afd80709', 'ron\\b\\include', 'Test.java'] ['b5cc17d3a35877ca8b76f0b2e07497039c250696', 'ron\\c', 'apa1.txt'] ['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', '...
Python List Question
i have an issue i could use some help with, i have python list that looks like this: fail = [ ['da39a3ee5e6b4b0d3255bfef95601890afd80709', 'ron\\b\\include', 'Test.java'] ['b5cc17d3a35877ca8b76f0b2e07497039c250696', 'ron\\c', 'apa1.txt'] ['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'knark.txt'] ['da39a3ee5e6b...
[ "duplicate = []\n# Sort the list so we can compare adjacent values\nfail.sort()\n#if you didn't want to modify the list in place you can use:\n#sortedFail = sorted(fail)\n# and then use sortedFail in the rest of the code instead of fail\nfor i, x in enumerate(fail):\n if i+1 == len(fail):\n #end of t...
[ 3, 1, 1, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0001034145_list_python.txt
Q: How do I use the bash time function from python? I would like to use python to make system calls to programs and time them. From the Linux command line if you type: $ time prog args You get something along the lines of: real 0m0.110s user 0m0.060s sys 0m0.024s if you do a 'man time', it states that you...
How do I use the bash time function from python?
I would like to use python to make system calls to programs and time them. From the Linux command line if you type: $ time prog args You get something along the lines of: real 0m0.110s user 0m0.060s sys 0m0.024s if you do a 'man time', it states that you can type: $ time -f "%E" prog args in order to forma...
[ "You are correct that bash has it's own version of time.\n$ type time\ntime is a shell keyword\n\nPerhaps you could explicitly invoke bash with the -c option to get it's timing.\nDepending on which distribution you're using, the default shell may be dash, a simpler shell that doesn't have time as a keyword. Both D...
[ 2, 0 ]
[]
[]
[ "bash", "linux", "python", "time", "unix" ]
stackoverflow_0001034566_bash_linux_python_time_unix.txt
Q: Flash Characters on Screen in Linux I have a XFCE 4.6 on kernel 2.6. Is there a quick and easy way to flash a message on the screen for a few seconds? My Thinkpad T60 has 3 volume buttons (up, down, mute). When I pressed the buttons, I would like to flash the volume on the screen for a second on screen. Can it be...
Flash Characters on Screen in Linux
I have a XFCE 4.6 on kernel 2.6. Is there a quick and easy way to flash a message on the screen for a few seconds? My Thinkpad T60 has 3 volume buttons (up, down, mute). When I pressed the buttons, I would like to flash the volume on the screen for a second on screen. Can it be done with Python?
[ "notification-daemon-xfce allows libnotify clients to show brief messages in XFCE. libnotify has Python bindings available.\nAs an untested example,\nimport pynotify\nimport sys\npynotify.init(sys.argv[0])\nnotification = pynotify.Notification(\"Title\", \"body\", \"dialog-info\")\nnotification.set_urgency(pynotif...
[ 1, 1 ]
[]
[]
[ "linux", "python", "xfce" ]
stackoverflow_0001030240_linux_python_xfce.txt
Q: python multiprocessing manager My problem is: I have 3 procs that would like to share config loaded from the same class and a couple of queues. I would like to spawn another proc as a multiprocessing.manager to share those informations. How can I do that? Could someone purchase a sample code avoiding use of globa...
python multiprocessing manager
My problem is: I have 3 procs that would like to share config loaded from the same class and a couple of queues. I would like to spawn another proc as a multiprocessing.manager to share those informations. How can I do that? Could someone purchase a sample code avoiding use of global vars and making use of multiproces...
[ "I found this particular section in the Python multiprocessing docs helpful. The following program:\nfrom multiprocessing import Process, Queue, current_process\nimport time\n\ndef f(q):\n name = current_process().name\n config = q.get()\n print \"%s got config: %s\" % (name, config)\n print \"%s beginn...
[ 3 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0001034848_multiprocessing_python.txt
Q: problem running scons I am trying to get started with scons. I have Python 3.0.1 and downloaded Scons 1.2.0; when I try to run scons I get the following error. Am I doing something wrong here? C:\tmp\scons>c:\appl\python\3.0.1\Scripts\scons Traceback (most recent call last): File "<string>", line 1, in <module> ...
problem running scons
I am trying to get started with scons. I have Python 3.0.1 and downloaded Scons 1.2.0; when I try to run scons I get the following error. Am I doing something wrong here? C:\tmp\scons>c:\appl\python\3.0.1\Scripts\scons Traceback (most recent call last): File "<string>", line 1, in <module> File "c:\appl\python\3.0....
[ "That's Python 2 syntax. I assume scons doesn't run on Python 3. You need to run it using Python 2. \n" ]
[ 16 ]
[]
[]
[ "python", "scons" ]
stackoverflow_0001035581_python_scons.txt
Q: Problem with exiting a daemonized process I am writing a daemon program that spawns several other children processes. After I run the stop script, the main process keeps running when it's intended to quit, this really confused me. import daemon, signal from multiprocessing import Process, cpu_count, JoinableQueue ...
Problem with exiting a daemonized process
I am writing a daemon program that spawns several other children processes. After I run the stop script, the main process keeps running when it's intended to quit, this really confused me. import daemon, signal from multiprocessing import Process, cpu_count, JoinableQueue from http import httpserv from worker import wo...
[ "I tried a different approach, and this seems to work (note I took out the daemon portions of the code as I didn't have that module installed).\nimport signal\n\nclass Manager:\n \"\"\"\n This manager starts the http server processes and worker\n processes, creates the input/output queues that keep the pro...
[ 1, 1 ]
[]
[]
[ "daemon", "multiprocessing", "python" ]
stackoverflow_0001021613_daemon_multiprocessing_python.txt
Q: Any Python Script to Save Websites Like Firefox? I am tired of clicking "File" and then "Save Page As" in Firefox when I want to save some websites. Is there any script to do this in Python? I would like to save the pictures and css files so that when I read it offline, it looks normal. A: You could use wget wge...
Any Python Script to Save Websites Like Firefox?
I am tired of clicking "File" and then "Save Page As" in Firefox when I want to save some websites. Is there any script to do this in Python? I would like to save the pictures and css files so that when I read it offline, it looks normal.
[ "You could use wget\nwget -m -k -E [url]\n-E, --html-extension save HTML documents with `.html' extension.\n-m, --mirror shortcut for -N -r -l inf --no-remove-listing.\n-k, --convert-links make links in downloaded HTML point to local files.\n\n", "probably a tool like wget is more approp...
[ 10, 1, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001035825_python.txt
Q: Find cpu-hogging plugin in multithreaded python I have a system written in python that processes large amounts of data using plug-ins written by several developers with varying levels of experience. Basically, the application starts several worker threads, then feeds them data. Each thread determines the plugin to...
Find cpu-hogging plugin in multithreaded python
I have a system written in python that processes large amounts of data using plug-ins written by several developers with varying levels of experience. Basically, the application starts several worker threads, then feeds them data. Each thread determines the plugin to use for an item and asks it to process the item. A p...
[ "You apparently don't need multithreading, only concurrency because your threads don't share any state : \nTry multiprocessing instead of multithreading\nSingle thread / N subprocesses. \nThere you can time each request, since no GIL is hold.\nOther possibility is to get rid of multiple execution threads and use e...
[ 3, 0, 0, 0 ]
[]
[]
[ "multithreading", "profiling", "python", "regex" ]
stackoverflow_0001031425_multithreading_profiling_python_regex.txt
Q: Methods for modular customization of locale messages? There many levels for the customization of programs. First of course is making it speak your language by creating i18n messages where tools like gettext and xgettext do a great job. Another comes when you need to modify the meaning of some messages to suite the...
Methods for modular customization of locale messages?
There many levels for the customization of programs. First of course is making it speak your language by creating i18n messages where tools like gettext and xgettext do a great job. Another comes when you need to modify the meaning of some messages to suite the purpose of your project. The question is: is it possible t...
[ "In Java, these localized strings are handled by ResourceBundles. ResourceBundles have a concept of variants. For example, you could have a base English resource, called messages_en.properties. Then you could customize for a specific variant of English with message_en_US.properties or message_en_UK.properties.\nUS ...
[ 1, 1 ]
[]
[]
[ "customization", "internationalization", "language_agnostic", "localization", "python" ]
stackoverflow_0001033580_customization_internationalization_language_agnostic_localization_python.txt
Q: python importing relative modules I have the Python modules a.py and b.py in the same directory. How can I reliably import b.py from a.py, given that a.py may have been imported from another directory or executed directly? This module will be distributed so I can't hardcode a single path. I've been playing around ...
python importing relative modules
I have the Python modules a.py and b.py in the same directory. How can I reliably import b.py from a.py, given that a.py may have been imported from another directory or executed directly? This module will be distributed so I can't hardcode a single path. I've been playing around with __file__, sys.path and os.chdir, b...
[ "Actually, __file__ is available for an imported module, but only if it was imported from a .py/.pyc file. It won't be available if the module is built in. For example:\n>>> import sys, os\n>>> hasattr(os, '__file__')\nTrue\n>>> hasattr(sys, '__file__')\nFalse\n\n", "Using the inspect module will make the built...
[ 6, 1, -1 ]
[]
[]
[ "python", "python_import", "python_module", "relative_path" ]
stackoverflow_0001016105_python_python_import_python_module_relative_path.txt
Q: Simple Image Metrics with PIL I want to process uploaded photos with PIL and determine some "soft" image metrics like: is the image contrastful or dull? colorful or monochrome? bright or dark? is the image warm or cold (regarding light temperature)? is there a dominant hue? the metrics should be measured in a ra...
Simple Image Metrics with PIL
I want to process uploaded photos with PIL and determine some "soft" image metrics like: is the image contrastful or dull? colorful or monochrome? bright or dark? is the image warm or cold (regarding light temperature)? is there a dominant hue? the metrics should be measured in a rating-style, e.g. colorful++++ for a...
[ "I don't think there are methods that give you a metric exactly for what you want, but the methods that it has, like RMS, takes you a long way there. To do things with color, you can split the image into one layer per color, and get the RMS on each layer, which tells you some of the things you want to know. You can...
[ 1 ]
[]
[]
[ "python", "python_imaging_library" ]
stackoverflow_0001037090_python_python_imaging_library.txt
Q: Are there stack based variables in Python? If I do this: def foo(): a = SomeObject() Is 'a' destroyed immediately after leaving foo? Or does it wait for some GC to happen? A: Yes and no. The object will get destroyed after you leave foo (as long as nothing else has a reference to it), but whether it is im...
Are there stack based variables in Python?
If I do this: def foo(): a = SomeObject() Is 'a' destroyed immediately after leaving foo? Or does it wait for some GC to happen?
[ "Yes and no. The object will get destroyed after you leave foo (as long as nothing else has a reference to it), but whether it is immediate or not is an implementation detail, and will vary.\nIn CPython (the standard python implementation), refcounting is used, so the item will immediately be destroyed. There are...
[ 18 ]
[]
[]
[ "python" ]
stackoverflow_0001037533_python.txt
Q: apache prefork/mod_wsgi spawned process count seemingly past configuration in a production environment running nginx reversing back to apache mpm-prefork/mod_wsgi, im seeing 90 apache child processes, when i would expect that 40 would be the maximum, as configured below. the configuration/setup is nothing exciting...
apache prefork/mod_wsgi spawned process count seemingly past configuration
in a production environment running nginx reversing back to apache mpm-prefork/mod_wsgi, im seeing 90 apache child processes, when i would expect that 40 would be the maximum, as configured below. the configuration/setup is nothing exciting: nginx is reverse proxying to apache via proxy_pass, and serving static media ...
[ "The mod_wsgi daemon processes will appear to be Apache server child processes even though they aren't the same. This is because the mod_wsgi daemon processes are a fork of Apache parent process and not a fork/exec. In other words, they executable name doesn't change.\nTo be able to distinguish mod_wsgi daemon proc...
[ 10, 0, 0 ]
[]
[]
[ "apache", "mod_wsgi", "python" ]
stackoverflow_0000913632_apache_mod_wsgi_python.txt
Q: mod_wsgi yield output buffer instead of return Right now I've got a mod_wsgi script that's structured like this.. def application(environ, start_response): status = '200 OK' output = 'Hello World!' response_headers = [('Content-type', 'text/plain'), ('Content-Length', str(len(outpu...
mod_wsgi yield output buffer instead of return
Right now I've got a mod_wsgi script that's structured like this.. def application(environ, start_response): status = '200 OK' output = 'Hello World!' response_headers = [('Content-type', 'text/plain'), ('Content-Length', str(len(output)))] start_response(status, response_headers) ...
[ "def application(environ, start_response):\n status = '200 OK'\n output = 'Hello World!'\n\n response_headers = [('Content-type', 'text/plain'),\n ('Content-Length', str(len(output)))]\n start_response(status, response_headers)\n\n yield output\n\n\n\"However, whenever I swap the o...
[ 7, 7, 0 ]
[]
[]
[ "mod_wsgi", "python", "yield" ]
stackoverflow_0000804898_mod_wsgi_python_yield.txt
Q: Serving static files with mod_wsgi and Django I have a django application using mod_python, fairly typical configuration except that media files are being served by a (I know, not recommended) 'media' directory in the document root. I would like to test and maybe deploy with mod_wsgi but I cannot figure out how t...
Serving static files with mod_wsgi and Django
I have a django application using mod_python, fairly typical configuration except that media files are being served by a (I know, not recommended) 'media' directory in the document root. I would like to test and maybe deploy with mod_wsgi but I cannot figure out how to create something simple to serve static files. m...
[ "I run a a dozen or so Django sites on the same server and here's how I configure the media URL's.\nEach VirtualHost has the following configuration:\nAlias /media /path/to/media/\n<Directory /path/to/media>\n Include /etc/apache2/vhosts.d/media.include\n</Directory>\n\nThis way I can make any changes to the med...
[ 18, 13 ]
[]
[]
[ "django", "mod_python", "mod_wsgi", "python" ]
stackoverflow_0000732190_django_mod_python_mod_wsgi_python.txt
Q: Converting from mod_python to mod_wsgi My website is written in Python and currently runs under mod_python with Apache. Lately I've had to put in a few ugly hacks that make me think it might be worth converting the site to mod_wsgi. But I've gotten used to using some of mod_python's utility classes, especially Fie...
Converting from mod_python to mod_wsgi
My website is written in Python and currently runs under mod_python with Apache. Lately I've had to put in a few ugly hacks that make me think it might be worth converting the site to mod_wsgi. But I've gotten used to using some of mod_python's utility classes, especially FieldStorage and Session (and sometimes Cookie)...
[ "Look at Werkzeug. You may have to do some rewriting. You will probably be pleased with the results of imposing the WSGI world-view on your application.\n", "You can use FieldStorage in 'cgi' module and the 'Cookie' module. There is no equivalent to Session in Python standard libraries. For WSGI applications yo...
[ 9, 2, 1 ]
[]
[]
[ "mod_python", "mod_wsgi", "python" ]
stackoverflow_0000644767_mod_python_mod_wsgi_python.txt
Q: In production, Apache + mod_wsgi or Nginx + mod_wsgi? What to use for a medium to large python WSGI application, Apache + mod_wsgi or Nginx + mod_wsgi? Which combination will need more memory and CPU time? Which one is faster? Which is known for being more stable than the other? I am also thinking to use CherryPy'...
In production, Apache + mod_wsgi or Nginx + mod_wsgi?
What to use for a medium to large python WSGI application, Apache + mod_wsgi or Nginx + mod_wsgi? Which combination will need more memory and CPU time? Which one is faster? Which is known for being more stable than the other? I am also thinking to use CherryPy's WSGI server but I hear it's not very suitable for a very ...
[ "For nginx/mod_wsgi, ensure you read:\nhttp://blog.dscpl.com.au/2009/05/blocking-requests-and-nginx-version-of.html\nBecause of how nginx is an event driven system underneath, it has behavioural characteristics which are detrimental to blocking applications such as is the case with WSGI based applications. Worse ca...
[ 78, 16, 14, 7 ]
[]
[]
[ "apache", "mod_wsgi", "nginx", "python" ]
stackoverflow_0000195534_apache_mod_wsgi_nginx_python.txt
Q: Python POST data using mod_wsgi This must be a very simple question, but I don't seem to be able to figure out. I'm using apache + mod_wsgi to host my python application, and I'd like to get the post content submitted in one of the forms -however, neither the environment values, nor sys.stdin contains any of this ...
Python POST data using mod_wsgi
This must be a very simple question, but I don't seem to be able to figure out. I'm using apache + mod_wsgi to host my python application, and I'd like to get the post content submitted in one of the forms -however, neither the environment values, nor sys.stdin contains any of this data. Mind giving me a quick hand? Ed...
[ "PEP 333 says you must read environ['wsgi.input'].\nI just saved the following code and made apache's mod_wsgi run it. It works.\nYou must be doing something wrong.\nfrom pprint import pformat\n\ndef application(environ, start_response):\n # show the environment:\n output = ['<pre>']\n output.append(pforma...
[ 22, 14 ]
[]
[]
[ "mod_wsgi", "python" ]
stackoverflow_0000394465_mod_wsgi_python.txt
Q: Running a Django site under mod_wsgi I am trying to run my Django sites with mod_wsgi instead of mod_python (RHEL 5). I tried this with all my sites, but get the same problem. I configured it the standard way everyone recommends, but requests to the site simply time out. Apache conf: <VirtualHost 74.54.144.34> ...
Running a Django site under mod_wsgi
I am trying to run my Django sites with mod_wsgi instead of mod_python (RHEL 5). I tried this with all my sites, but get the same problem. I configured it the standard way everyone recommends, but requests to the site simply time out. Apache conf: <VirtualHost 74.54.144.34> DocumentRoot /wwwclients/thymeandagain ...
[ "The real problem is permissions on Apache log directory. It is necessary to tell Apache/mod_wsgi to use an alternate location for the UNIX sockets used to communicate with the daemon processes. See:\nhttp://code.google.com/p/modwsgi/wiki/ConfigurationIssues#Location_Of_UNIX_Sockets\n", "The problem is that mod_p...
[ 10, 4, 1 ]
[]
[]
[ "apache", "django", "mod_wsgi", "python" ]
stackoverflow_0000302679_apache_django_mod_wsgi_python.txt
Q: Passing apache2 digest authentication information to a wsgi script run by mod_wsgi I've got the directive <VirtualHost *> <Location /> AuthType Digest AuthName "global" AuthDigestDomain / AuthUserFile /root/apache_users <Limit GET> Require valid-user ...
Passing apache2 digest authentication information to a wsgi script run by mod_wsgi
I've got the directive <VirtualHost *> <Location /> AuthType Digest AuthName "global" AuthDigestDomain / AuthUserFile /root/apache_users <Limit GET> Require valid-user </Limit> </Location> WSGIScriptAlias / /some/script.wsgi WSGIDaemonProcess m...
[ "add WSGIPassAuthorization On:\n<VirtualHost *>\n <Location />\n AuthType Digest\n AuthName \"global\"\n AuthDigestDomain /\n AuthUserFile /root/apache_users\n <Limit GET>\n Require valid-user\n </Limit>\n </Location>\n WSGIPassAuthorization On\n WSGI...
[ 16, 2 ]
[]
[]
[ "apache", "authentication", "mod_wsgi", "python", "wsgi" ]
stackoverflow_0000123499_apache_authentication_mod_wsgi_python_wsgi.txt
Q: Is mod_wsgi/Python optimizing things out? I have been trying to track down weird problems with my mod_wsgi/Python web application. I have the application handler which creates an object and calls a method: def my_method(self, file): self.sapi.write("In my method for %d time"%self.mmcount) self.mmcount += 1...
Is mod_wsgi/Python optimizing things out?
I have been trying to track down weird problems with my mod_wsgi/Python web application. I have the application handler which creates an object and calls a method: def my_method(self, file): self.sapi.write("In my method for %d time"%self.mmcount) self.mmcount += 1 # ... open file (absolute path to file), ...
[ "That Apache/mod_wsgi may run in both multi process/multi threaded configurations can trip up code which is written with the assumption that it is run in a single process, with that process possibly being single threaded. For a discussion of different configuration possibilities and what that all means for shared d...
[ 3, 1, 1 ]
[]
[]
[ "caching", "debugging", "mod_wsgi", "python" ]
stackoverflow_0000957685_caching_debugging_mod_wsgi_python.txt
Q: Auto-incrementing attribute with custom logic in SQLAlchemy I have a simple "Invoices" class with a "Number" attribute that has to be assigned by the application when the user saves an invoice. There are some constraints: 1) the application is a (thin) client-server one, so whatever assigns the number must look ou...
Auto-incrementing attribute with custom logic in SQLAlchemy
I have a simple "Invoices" class with a "Number" attribute that has to be assigned by the application when the user saves an invoice. There are some constraints: 1) the application is a (thin) client-server one, so whatever assigns the number must look out for collisions 2) Invoices has a "version" attribute too, so I ...
[ "Is there any particular reason you don't just use a default= parameter in your column definition? (This can be an arbitrary Python callable).\ndef generate_invoice_number():\n # special logic to generate a unique invoice number\n\nclass Invoice(DeclarativeBase):\n __tablename__ = 'invoice'\n number = Col...
[ 6 ]
[]
[]
[ "auto_increment", "python", "sqlalchemy" ]
stackoverflow_0001038126_auto_increment_python_sqlalchemy.txt
Q: In Python, how do I easily generate an image file from some source data? I have some data that I would like to visualize. Each byte of the source data roughly corresponds to a pixel value of the image. What is the easiest way to generate an image file (bitmap?) using Python? A: You can create images with a list ...
In Python, how do I easily generate an image file from some source data?
I have some data that I would like to visualize. Each byte of the source data roughly corresponds to a pixel value of the image. What is the easiest way to generate an image file (bitmap?) using Python?
[ "You can create images with a list of pixel values using Pillow:\nfrom PIL import Image\n\nimg = Image.new('RGB', (width, height))\nimg.putdata(my_list)\nimg.save('image.png')\n\n", "Have a look at PIL and pyGame. Both of them allow you to draw on a canvas and then save it to a file.\n" ]
[ 39, 6 ]
[]
[]
[ "data_visualization", "image", "python" ]
stackoverflow_0001038550_data_visualization_image_python.txt
Q: Obtaining references to function objects on the execution stack from the frame object? Given the output of inspect.stack(), is it possible to get the function objects from anywhere from the stack frame and call these? If so, how? (I already know how to get the names of the functions.) Here is what I'm getting at: ...
Obtaining references to function objects on the execution stack from the frame object?
Given the output of inspect.stack(), is it possible to get the function objects from anywhere from the stack frame and call these? If so, how? (I already know how to get the names of the functions.) Here is what I'm getting at: Let's say I'm a function and I'm trying to determine if my caller is a generator or a regula...
[ "Here is a code snippet that do it. There is no error checking. The idea is to find in the locals of the grand parent the function object that was called. The function object returned should be the parent. If you want to also search the builtins, then simply look into stacks[2][0].f_builtins. \ndef f():\n stacks...
[ 2, 0 ]
[]
[]
[ "inspect", "python", "stack_frame" ]
stackoverflow_0001034688_inspect_python_stack_frame.txt
Q: When reading a socket in python, is there any difference between os.read and socket.recv? Suppose I have a socket. What is the difference between these two lines of code? line 1: os.read(some_socket.fileno(), 1024) line 2: some_socket.recv(1024) ...other than the fact that the first one doesn't work on Windows....
When reading a socket in python, is there any difference between os.read and socket.recv?
Suppose I have a socket. What is the difference between these two lines of code? line 1: os.read(some_socket.fileno(), 1024) line 2: some_socket.recv(1024) ...other than the fact that the first one doesn't work on Windows. In other words, can I substitute the second line for the first one? I've got a codebase that...
[ "line 1 uses the underlining file descriptor to read the socket, so it is platform-dependant. Use line 2, since it is a portable, multi-platform way of accomplishing the same thing.\nObligatory: If you're doing anything serious, it's better to avoid having to deal with low-level sockets. They are hard to get right,...
[ 6 ]
[]
[]
[ "python", "sockets", "tcp", "windows" ]
stackoverflow_0001039462_python_sockets_tcp_windows.txt
Q: Run a task at specific intervals in python Possible Duplicate: Suggestions for a Cron like scheduler in Python? What would be the most pythonic way to schedule a function to run periodically as a background task? There are some ideas here, but they all seem rather ugly to me. And incomplete. The java Timer class...
Run a task at specific intervals in python
Possible Duplicate: Suggestions for a Cron like scheduler in Python? What would be the most pythonic way to schedule a function to run periodically as a background task? There are some ideas here, but they all seem rather ugly to me. And incomplete. The java Timer class has a very complete solution. Anyone know of a...
[ "There is a handy event scheduler that might do what you need. Here's a link to the documentation:\nhttp://docs.python.org/library/sched.html\n", "try the multiprocessing module.\nfrom multiprocessing import Process\nimport time\n\ndef doWork():\n while True:\n print \"working....\"\n time.sleep(...
[ 12, 9, 7, 6, 2 ]
[]
[]
[ "python", "timer" ]
stackoverflow_0001038907_python_timer.txt
Q: Crunching json with python Echoing my other question now need to find a way to crunch json down to one line: e.g. {"node0":{ "node1":{ "attr0":"foo", "attr1":"foo bar", "attr2":"value with long spaces" } }} would like to crunch down to a single line: {"node0":{"node1"...
Crunching json with python
Echoing my other question now need to find a way to crunch json down to one line: e.g. {"node0":{ "node1":{ "attr0":"foo", "attr1":"foo bar", "attr2":"value with long spaces" } }} would like to crunch down to a single line: {"node0":{"node1":{"attr0":"foo","attr1":"foo bar...
[ "http://docs.python.org/library/json.html\n>>> import json\n>>> json.dumps(json.loads(\"\"\"\n... {\"node0\":{\n... \"node1\":{\n... \"attr0\":\"foo\",\n... \"attr1\":\"foo bar\",\n... \"attr2\":\"value with long spaces\"\n... }\n... }}\n... \"\"\"))\n'{\"node0\": {\"no...
[ 21, 2 ]
[]
[]
[ "json", "parsing", "python" ]
stackoverflow_0001039877_json_parsing_python.txt
Q: Best way to get the name of a button that called an event? In the following code (inspired by this snippet), I use a single event handler buttonClick to change the title of the window. Currently, I need to evaluate if the Id of the event corresponds to the Id of the button. If I decide to add 50 buttons instead of...
Best way to get the name of a button that called an event?
In the following code (inspired by this snippet), I use a single event handler buttonClick to change the title of the window. Currently, I need to evaluate if the Id of the event corresponds to the Id of the button. If I decide to add 50 buttons instead of 2, this method could become cumbersome. Is there a better way t...
[ "You could give the button a name, and then look at the name in the event handler.\nWhen you make the button\nb = wx.Button(self, 10, \"Default Button\", (20, 20))\nb.myname = \"default button\"\nself.Bind(wx.EVT_BUTTON, self.OnClick, b)\n\nWhen the button is clicked:\ndef OnClick(self, event):\n name = event.Ge...
[ 12, 8, 7, 3, 2, 0, 0 ]
[]
[]
[ "event_handling", "events", "python", "user_interface", "wxpython" ]
stackoverflow_0000976395_event_handling_events_python_user_interface_wxpython.txt
Q: reading a configuration information only once in Python I'm using the ConfigParser to read the configuration information stored in a file. I'm able to read the content and use it across other modules in the project. I'm not sure if the configuration file is read every time I call config.get(parameters). How can I ...
reading a configuration information only once in Python
I'm using the ConfigParser to read the configuration information stored in a file. I'm able to read the content and use it across other modules in the project. I'm not sure if the configuration file is read every time I call config.get(parameters). How can I make sure that the configuration information is read only onc...
[ "I would try assigning the configuration to a variable.\nconfigVariable = config.get(parameters)\n\nThen you can pass the configuration variable to other modules as necessary.\n", "The default implementation of the ConfigParser class reads its data only once. \n" ]
[ 2, 1 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0001040135_oop_python.txt
Q: Python "Event" equivalent in Java? What's the closest thing in Java (perhaps an idiom) to threading.Event in Python? A: The Object.wait() Object.notify()/Object.notifyAll(). Or Condition.await() and Condition.signal()/Condition.signalAll() for Java 5+. Edit: Because the python specification is similar how we usu...
Python "Event" equivalent in Java?
What's the closest thing in Java (perhaps an idiom) to threading.Event in Python?
[ "The Object.wait() Object.notify()/Object.notifyAll().\nOr Condition.await() and Condition.signal()/Condition.signalAll() for Java 5+.\nEdit: Because the python specification is similar how we usually wait a Java implementation would look like this:\nclass Event {\n Lock lock = new ReentrantLock();\n Conditio...
[ 9, 0 ]
[]
[]
[ "java", "multithreading", "python" ]
stackoverflow_0001040818_java_multithreading_python.txt
Q: Configure pyflakes to work with Zope's "script (python)" objects on the filesystem When I run pyflakes on a Zope Filesystem Directory View file (as are found a lot in plone) it always returns lots of warnings that my parameters and special values like 'context' are not defined, which would be true if it were a rea...
Configure pyflakes to work with Zope's "script (python)" objects on the filesystem
When I run pyflakes on a Zope Filesystem Directory View file (as are found a lot in plone) it always returns lots of warnings that my parameters and special values like 'context' are not defined, which would be true if it were a real python script, but for a Filesystem Directory View script, they are defined by magic c...
[ "A possible approach I just tried is to pre-process the zope fspython script so that it is vaild. I've used a few calls to sed (below):\n#!/bin/bash\nsed \"s/\\(^[^#]\\)/ \\1/\" $1 | \\\nsed \"s/^##bind [a-z]*=\\([a-z][a-z]*\\)$/import \\1/\" | \\\nsed \"s/^##parameters=\\(.*\\)/def foo(\\1):/\" | pyflakes\n\nIt w...
[ 2, 1 ]
[]
[]
[ "python", "zope" ]
stackoverflow_0001038863_python_zope.txt
Q: Passing data to mod_wsgi In mod_wsgi I send the headers by running the function start_response(), but all the page content is passed by yield/return. Is there a way to pass the page content in a similar fashion as start_response()? Using the return.yield statement is very restrictive when it comes to working with ...
Passing data to mod_wsgi
In mod_wsgi I send the headers by running the function start_response(), but all the page content is passed by yield/return. Is there a way to pass the page content in a similar fashion as start_response()? Using the return.yield statement is very restrictive when it comes to working with chunked data. E.g. def Applica...
[ "No; But I don't think it is restrictive. Maybe you want to paste an example code where you describe your restriction and we can help.\nTo work with chunk data you just yield the chunks:\ndef application(environ, start_response):\n start_response('200 OK', [('Content-type', 'text/plain')]\n yield 'Chunk 1\\n'...
[ 2, 1, 1 ]
[]
[]
[ "mod_wsgi", "python", "wsgi" ]
stackoverflow_0000940816_mod_wsgi_python_wsgi.txt
Q: Context-sensitive string splitting, preserving delimiters I have a string of the form "foo-bar-1.23-4", and I need to split at the first hypen followed by a numeral, such that the result is ['foo-bar', '1.23-4']. I've tried the following: >>> re.split('-\d', 'foo-bar-1.23-4', 1) ['foo-bar', '.23-4'] and >>> re.sp...
Context-sensitive string splitting, preserving delimiters
I have a string of the form "foo-bar-1.23-4", and I need to split at the first hypen followed by a numeral, such that the result is ['foo-bar', '1.23-4']. I've tried the following: >>> re.split('-\d', 'foo-bar-1.23-4', 1) ['foo-bar', '.23-4'] and >>> re.split('-(\d)', 'foo-bar-1.23-4', 1) ['foo-bar', '1', '.23-4'] wi...
[ "You were very close, try this:\nre.split('-(?=\\d)', 'foo-bar-1.23-4', 1)\n\nI am using positive lookahead to accomplish this - basically I am matching a dash that is immediately followed by a numeric character.\n", "re.split('-(?=\\d)', 'foo-bar-1.23-4', 1)\n\nUsing lookahead, which is exactly what Andrew did b...
[ 2, 0, 0 ]
[]
[]
[ "python", "split", "string" ]
stackoverflow_0001041600_python_split_string.txt
Q: Unable to see Python's approximations in mathematical calculations Problem: to see when computer makes approximation in mathematical calculations when I use Python Example of the problem: My old teacher once said the following statement You cannot never calculate 200! with your computer. I am not completely sure...
Unable to see Python's approximations in mathematical calculations
Problem: to see when computer makes approximation in mathematical calculations when I use Python Example of the problem: My old teacher once said the following statement You cannot never calculate 200! with your computer. I am not completely sure whether it is true or not nowadays. It seems that it is, since I get a ...
[ "Python use arbitrary-precision arithmetic to calculate with integers, so it can exactly calculate 200!. For real numbers (so-called floating-point), Python does not use an exact representation. It uses a binary representation called IEEE 754, which is essentially scientific notation, except in base 2 instead of ...
[ 7, 2, 1, 1, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001041543_python.txt
Q: SQLAlchemy: Object Mappings lost after commit? I got a simple problem in SQLAlchemy. I have one model in a table, lets call it Model1 here. I want to add a row in this table, and get the autoincremented key, so I can create another model with it, and use this key. This is not a flawed database design (1:1 relation...
SQLAlchemy: Object Mappings lost after commit?
I got a simple problem in SQLAlchemy. I have one model in a table, lets call it Model1 here. I want to add a row in this table, and get the autoincremented key, so I can create another model with it, and use this key. This is not a flawed database design (1:1 relation etc). I simply need this key in another table, beca...
[ "A couple of things:\n\nCould you please explain what the variable transaction is bound to?\nExactly what statement raises the UnboundExecutionError?\nPlease provide the full exception message, including stack trace.\nThe 'normal' thing to do in this case, would be to call DBSession.flush(). Have you tried that?\n\...
[ 3, 2, 1 ]
[]
[]
[ "database", "python", "sqlalchemy" ]
stackoverflow_0001033199_database_python_sqlalchemy.txt
Q: Where can I learn more about PyPy's translation function? I've been having a hard time trying to understand PyPy's translation. It looks like something absolutely revolutionary from simply reading the description, however I'm hard-pressed to find good documentation on actually translating a real world piece of co...
Where can I learn more about PyPy's translation function?
I've been having a hard time trying to understand PyPy's translation. It looks like something absolutely revolutionary from simply reading the description, however I'm hard-pressed to find good documentation on actually translating a real world piece of code to something such as LLVM. Does such a thing exist? The of...
[ "This document seems to go into quite a bit of detail (and I think a complete description is out of scope for a stackoverflow answer):\n\nhttp://codespeak.net/pypy/dist/pypy/doc/translation.html\n\nThe general idea of translating from one language to another isn't particularly revolutionary, but it has only recentl...
[ 6, 3, 3, 2, 1 ]
[]
[]
[ "pypy", "python", "translation" ]
stackoverflow_0000027567_pypy_python_translation.txt
Q: jcc.initVM() doesn't return when mod_wsgi is configured as daemon mode I am using mod-wsgi with django, and in django I use pylucene to do full text search. While mod-wsgi is configured to be embedded mode, there is no problem at all. But when mod-wsgi is configured to be daemon mode, the apache just gets stuck, ...
jcc.initVM() doesn't return when mod_wsgi is configured as daemon mode
I am using mod-wsgi with django, and in django I use pylucene to do full text search. While mod-wsgi is configured to be embedded mode, there is no problem at all. But when mod-wsgi is configured to be daemon mode, the apache just gets stuck, and the browser just keep loading but nothing appears. Then I identity the p...
[ "Please refer to http://code.google.com/p/modwsgi/issues/detail?id=131 for the discussion details. \nIn short, the \nmod_wsgi will block signals for the daemon program, which may make initVM doesn't work. Furthermore according to \nAndi from jcc, initVM can only be called from the main thread, and it may cause furt...
[ 1, 1 ]
[]
[]
[ "apache", "jcc", "mod_wsgi", "pylucene", "python" ]
stackoverflow_0000548493_apache_jcc_mod_wsgi_pylucene_python.txt
Q: retrieving current URL from FireFox with python I want to know what is the current url of active tab in running firefox instance from python module. Does FireFox have any API for this and does python know to work with it? A: The most convenient way maybe insatll a firefox extension to open up a tcp service, then...
retrieving current URL from FireFox with python
I want to know what is the current url of active tab in running firefox instance from python module. Does FireFox have any API for this and does python know to work with it?
[ "The most convenient way maybe insatll a firefox extension to open up a tcp service, then you can exchange info with firefox.\nmozrepl can set up a telnet service, you can call js-like command to get info.\nWith telnetscript (http: //code.activestate.com/recipes/152043/), you can write:\n\nimport telnetscript\n\nsc...
[ 3, 1 ]
[]
[]
[ "firefox", "python", "python_extensions" ]
stackoverflow_0000493978_firefox_python_python_extensions.txt
Q: DJANGO - How do you access the current model instance from inside a form class EditAdminForm(forms.ModelForm): password = username.CharField(widget=forms.TextInput()) password = forms.CharField(widget=forms.PasswordInput()) password_confirm = forms.CharField(widget=forms.PasswordInput(), initial=???) ...
DJANGO - How do you access the current model instance from inside a form
class EditAdminForm(forms.ModelForm): password = username.CharField(widget=forms.TextInput()) password = forms.CharField(widget=forms.PasswordInput()) password_confirm = forms.CharField(widget=forms.PasswordInput(), initial=???) You can see what I'm trying to do here. How would I go about pre-populating th...
[ "You can't access the instance in the form declaration, because there isn't one until you instantiate it.\nHowever, if all you want to do is set dynamic initial data, do this with the initial parameter on instantation:\nform = EditAdminForm(initial={'password':'abcdef'})\n\n", "You can define __init__ method in E...
[ 2, 0 ]
[]
[]
[ "django", "instance", "model", "python" ]
stackoverflow_0001040887_django_instance_model_python.txt
Q: Python 2.6 - Upload zip file - Poster 0.4 I came here via this question: Send file using POST from a Python script And by and large it's what I need, plus some additional. Besides the zipfile som additional information is needed and the POST_DATA looks something like this: POSTDATA =-----------------------------2...
Python 2.6 - Upload zip file - Poster 0.4
I came here via this question: Send file using POST from a Python script And by and large it's what I need, plus some additional. Besides the zipfile som additional information is needed and the POST_DATA looks something like this: POSTDATA =-----------------------------293432744627532 Content-Disposition: form-data; ...
[ "Poster has basic and advanced multipart support.\nYou may try something like this (modified from poster documentation):\n# test_client.py\nfrom poster.encode import multipart_encode\nfrom poster.streaminghttp import register_openers\nimport urllib2\n\n# Register the streaming http handlers with urllib2\nregister_o...
[ 4 ]
[]
[]
[ "file_upload", "python", "upload", "urllib2", "zip" ]
stackoverflow_0001042451_file_upload_python_upload_urllib2_zip.txt
Q: Best Practise for transferring a MySQL table to another server? I have a system sitting on a "Master Server", that is periodically transferring quite a few chunks of information from a MySQL DB to another server in the web. Both servers have a MySQL Server and an Apache running. I would like an easy-to-use solutio...
Best Practise for transferring a MySQL table to another server?
I have a system sitting on a "Master Server", that is periodically transferring quite a few chunks of information from a MySQL DB to another server in the web. Both servers have a MySQL Server and an Apache running. I would like an easy-to-use solution for this. Currently I'm looking into: XMLRPC RestFul Services a si...
[ "Server 1: Convert rows to JSON, call the RESTful api of second with JSON data\nServer 2: listens on a URI e.g. POST /data , get json data convert back to dictionary or ORM objects, insert into db\nsqlalchemy/sqlobject and simplejson is what you need.\n", "If the table is small and you can send the whole table an...
[ 2, 1, 0, 0, 0 ]
[]
[]
[ "database_design", "python", "web_services" ]
stackoverflow_0001043528_database_design_python_web_services.txt
Q: Convert param into python? I am trying to learn web programming in python. I am converting my old php-flash project into python. Now, I am confused about how to set param value and create object using python. FYI I used a single php file, index.php to communicate with flash.swf. So, my other php files like login.p...
Convert param into python?
I am trying to learn web programming in python. I am converting my old php-flash project into python. Now, I am confused about how to set param value and create object using python. FYI I used a single php file, index.php to communicate with flash.swf. So, my other php files like login.php, logout.php, mail.php, xml.ph...
[ "Python is a general purpose language, not exactly made for web. There exists some embeddable PHP-like solutions, but in most Python web frameworks, you write Python and HTML (template) code separately.\nFor example in Django web framework you first write a view (view — you know — from that famous Model-View-Contro...
[ 3, 0, 0, 0 ]
[]
[]
[ "parameters", "php", "python" ]
stackoverflow_0001042391_parameters_php_python.txt
Q: Splitting a string @ once using different seps datetime = '0000-00-00 00:00:00'.split('-') Right now it just splits it at the hyphen, but is it possible to split this string at both -'s and :'s ? A: I'm guessing you also want to split on the space in the middle: import re values = re.split(r'[- :]', "1122-33-4...
Splitting a string @ once using different seps
datetime = '0000-00-00 00:00:00'.split('-') Right now it just splits it at the hyphen, but is it possible to split this string at both -'s and :'s ?
[ "I'm guessing you also want to split on the space in the middle:\nimport re\nvalues = re.split(r'[- :]', \"1122-33-44 55:66:77\")\nprint values\n# Prints ['1122', '33', '44', '55', '66', '77']\n\n", "One idea would be something like this (untested):\nyears, months, days = the_string.split('-')\ndays, time = days....
[ 13, 5, 2, 0 ]
[]
[]
[ "python", "split", "string" ]
stackoverflow_0001042751_python_split_string.txt
Q: Unable to solve a Python error message The code is from K. Pollari-Malmi's lecture notes for the course "Introduction to Programming": def main(): print "Ohjelma laskee asuntolainan kuukausierat." rivi = raw_input("Anna lainasumma: ") lainasumma = float(rivi) rivi = raw_input("Anna laina-aika vu...
Unable to solve a Python error message
The code is from K. Pollari-Malmi's lecture notes for the course "Introduction to Programming": def main(): print "Ohjelma laskee asuntolainan kuukausierat." rivi = raw_input("Anna lainasumma: ") lainasumma = float(rivi) rivi = raw_input("Anna laina-aika vuosina: ") laina_aika = int(rivi) i...
[ "Several answers already gave you the crux of your problem, but I want to make a plug for my favorite way to get logical line continuation in Python, when feasible:\nprint \"%2d. %8.2f %8.2f %8.2f\" % ( # no mistake here\n i, lyhennys, korkoera, kuukausiera)\n\ni.e., instead of using extra parent...
[ 10, 6, 2, 2, 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001044705_python.txt
Q: Setting the flags field of the IP header I have a simple Python script that uses the socket module to send a UDP packet. The script works fine on my Windows box, but on my Ubuntu Linux PC the packet it sends is slightly different. On Windows the flags field in the IP header is zero, but using the same code on Linu...
Setting the flags field of the IP header
I have a simple Python script that uses the socket module to send a UDP packet. The script works fine on my Windows box, but on my Ubuntu Linux PC the packet it sends is slightly different. On Windows the flags field in the IP header is zero, but using the same code on Linux created a packet with the flags field set to...
[ "Here's the route I ended up taking. I followed the link posted by SashaN in the comments of D.Shwley's answer and learned a little bit about why the \"don't fragment\" bit is set in Linux's UDP packets. Turns out it has something to do with PMTU discovery. Long story short, you can clear the don't fragment bit fro...
[ 6, 2, 1 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0001035799_python_sockets.txt
Q: Unable to understand a line of Python code exactly Alex's answer has the following line when translated to English print "%2d. %8.2f %8.2f %8.2f" % ( i, payment, interest, monthPayment) I am unsure about the line "%2d. %8.2f %8.2f %8.2f" % #Why do we need the last % here? It seems to mean...
Unable to understand a line of Python code exactly
Alex's answer has the following line when translated to English print "%2d. %8.2f %8.2f %8.2f" % ( i, payment, interest, monthPayment) I am unsure about the line "%2d. %8.2f %8.2f %8.2f" % #Why do we need the last % here? It seems to mean the following apply %2d. to i apply %8.2f to payment a...
[ "The 8 in 8.2 is the width\n\"Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger\"\nThe 2 is the number of decimal places\nThe final % just links the format string (in quo...
[ 7, 4, 1, 1, 1, 0 ]
[]
[]
[ "python", "syntax" ]
stackoverflow_0001044889_python_syntax.txt
Q: How to do cleanup reliably in python? I have some ctypes bindings, and for each body.New I should call body.Free. The library I'm binding doesn't have allocation routines insulated out from the rest of the code (they can be called about anywhere there), and to use couple of useful features I need to make cyclic re...
How to do cleanup reliably in python?
I have some ctypes bindings, and for each body.New I should call body.Free. The library I'm binding doesn't have allocation routines insulated out from the rest of the code (they can be called about anywhere there), and to use couple of useful features I need to make cyclic references. I think It'd solve if I'd find a ...
[ "What you want to do, that is create an object that allocates things and then deallocates automatically when the object is no longer in use, is almost impossible in Python, unfortunately. The del statement is not guaranteed to be called, so you can't rely on that. \nThe standard way in Python is simply:\ntry:\n ...
[ 3, 0 ]
[ "In CPython, __del__ is a reliable destructor of an object, because it will always be called when the reference count reaches zero (note: there may be cases - like circular references of items with __del__ method defined - where the reference count will never reaches zero, but that is another issue).\nUpdate\nFrom ...
[ -1 ]
[ "ctypes", "cyclic_reference", "python" ]
stackoverflow_0001044073_ctypes_cyclic_reference_python.txt
Q: Custom Managers and "through" I have a many-to-many relationship in my django application where I use the "add" method of the manager pretty heavily (ie album.photos.add() ). I find myself needing to store some data about the many-to-many relationship now, but I don't want to lose the add method. Can I just set a ...
Custom Managers and "through"
I have a many-to-many relationship in my django application where I use the "add" method of the manager pretty heavily (ie album.photos.add() ). I find myself needing to store some data about the many-to-many relationship now, but I don't want to lose the add method. Can I just set a default value for all the additiona...
[ "Simplest way is to just add a method to Album (i.e. album.add_photo()) which handles the metadata and manually creates a properly-linked Photo instance.\nIf you want to get all funky, you can write a custom manager for Photos, make it the default (i.e. first assigned manager), set use_for_related_fields = True on ...
[ 2 ]
[]
[]
[ "django", "django_models", "many_to_many", "python" ]
stackoverflow_0001038542_django_django_models_many_to_many_python.txt
Q: Django: Model name clash I am trying to use different open source apps in my project. Problem is that there is a same Model name used by two different apps with their own model definition. I tried using: class Meta: db_table = "db_name" but it didn't work. I am still getting field name clash error at...
Django: Model name clash
I am trying to use different open source apps in my project. Problem is that there is a same Model name used by two different apps with their own model definition. I tried using: class Meta: db_table = "db_name" but it didn't work. I am still getting field name clash error at syncdb. Any suggestions. Upda...
[ "The problem is that both Satchmo and Pinax have a Contact model with a ForeignKey to User. Django tries to add a \"contact_set\" reverse relationship attribute to User for each of those ForeignKeys, so there is a clash.\nThe solution is to add something like related_name=\"pinax_contact_set\" as an argument to th...
[ 6 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0001036506_django_django_models_python.txt
Q: Formatting output when writing a list to textfile i have a list of lists that looks like this: dupe = [['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'apa.txt'], ['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'knark.txt'], ['b5cc17d3a35877ca8b76f0b2e07497039c250696', 'ron\\a', 'apa2.txt'], ['b5cc17...
Formatting output when writing a list to textfile
i have a list of lists that looks like this: dupe = [['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'apa.txt'], ['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'knark.txt'], ['b5cc17d3a35877ca8b76f0b2e07497039c250696', 'ron\\a', 'apa2.txt'], ['b5cc17d3a35877ca8b76f0b2e07497039c250696', 'ron\\a', 'jude.tx...
[ "First, group the lines by the \"key\" (the first two elements of each array):\ndupedict = {}\nfor a, b, c in dupe:\n dupedict.setdefault((a,b),[]).append(c)\n\nThen print it out:\nfor key, values in dupedict.iteritems():\n print ' '.join(key), ', '.join(values)\n\n", "i take it your last question didn't solve ...
[ 2, 1, 1, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0001045699_list_python.txt
Q: Is there any good reason to convert an app written in python to c#? I have written several Python tools for my company. Is there any good reason to convert them from Python to C# now that their usefulness has been proven? Would I be better off just leaving them in Python? A: Quote: "If it doesn't break, don't ...
Is there any good reason to convert an app written in python to c#?
I have written several Python tools for my company. Is there any good reason to convert them from Python to C# now that their usefulness has been proven? Would I be better off just leaving them in Python?
[ "Quote: \"If it doesn't break, don't fix it.\"\nUnless your company is moving towards .NET and/or there are no more qualified Python developer available anymore, then don't.\n", "There's IronPython , a python implementation for .NET. You could port it to that if you really need to get away from the \"standard\" ...
[ 13, 8, 6, 4, 3, 1, 1, 1, 1, 0, 0 ]
[ "i will convert it from language a to language b for 1 million dollars. <--- this would be the only business reason I would consider legit.\n" ]
[ -1 ]
[ ".net", "c#", "python" ]
stackoverflow_0001045334_.net_c#_python.txt
Q: python observer pattern I'm new to python but I've run into a hitch when trying to implement a variation of the observer pattern. class X(models.Model): a = models.ForeignKey(Voter) b = models.CharField(max_length=200) # Register Y.register(X) This doesn't seem to work because it says X is not d...
python observer pattern
I'm new to python but I've run into a hitch when trying to implement a variation of the observer pattern. class X(models.Model): a = models.ForeignKey(Voter) b = models.CharField(max_length=200) # Register Y.register(X) This doesn't seem to work because it says X is not defined. A couple of things a...
[ "In python, code defined in a class block is executed and only then, depending on various things---like what has been defined in this block---a class is created. So if you want to relate one class with another, you'd write:\nclass X(models.Model):\n a = models.ForeignKey(Voter)\n b = models.CharField(max_leng...
[ 5, 4 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001046190_django_python.txt
Q: Unable to put a variable in Python's print My code: year=[51-52,53,55,56,58,59,60,61] photo=[{70,72,73},{64,65,68},{79,80,81,82},{74,77,78},{60,61,62},{84,85,87},{57,58,59},{53,54,55,56}] for i in range(7): print "<img src=\"http://files.getdropbox.com/u/100000/Akuja/",year,"/P10104",photo,".JPG\">" I run it...
Unable to put a variable in Python's print
My code: year=[51-52,53,55,56,58,59,60,61] photo=[{70,72,73},{64,65,68},{79,80,81,82},{74,77,78},{60,61,62},{84,85,87},{57,58,59},{53,54,55,56}] for i in range(7): print "<img src=\"http://files.getdropbox.com/u/100000/Akuja/",year,"/P10104",photo,".JPG\">" I run it and I get File "/tmp/aku.py", line 2 photo=...
[ "Braces are used to indicate a dictionary (associative array). You want to use square brackets, which indicates a list.\nAlso you probably don't want 51-52 in that first line, as that will evaluate to -1. You should put \"51-52\" to ensure that it is a string.\nThen to get the indexing that you seem to want, you ...
[ 3, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001046584_python.txt
Q: Would one have to know the machine architecture to write code? Let's say I'm programming in Java or Python or C++ for a simple problem, could be to build an TCP/UDP echo server or computation of factorial. Do I've to bother about the architecture details, i.e., if it is 32 or 64-bit? IMHO, unless I'm programming s...
Would one have to know the machine architecture to write code?
Let's say I'm programming in Java or Python or C++ for a simple problem, could be to build an TCP/UDP echo server or computation of factorial. Do I've to bother about the architecture details, i.e., if it is 32 or 64-bit? IMHO, unless I'm programming something to do with fairly low-level stuff then I don't have to both...
[ "correct for most circumstances\nThe runtime/language/compiler will abstract those details unless you are dealing directly with word sizes or binary at a low level.\nEven byteorder is abstracted by the NIC/Network stack in the kernel. It is translated for you. When programming sockets in C, you do sometimes have to...
[ 16, 16, 8, 6, 3, 2, 1, 0, 0, 0, 0 ]
[]
[]
[ "32_bit", "64_bit", "c++", "java", "python" ]
stackoverflow_0001046068_32_bit_64_bit_c++_java_python.txt
Q: What is the most secure python "password" encryption I am making a little webgame that has tasks and solutions, the solutions are solved by entering a code given to user after completion of a task. To have some security (against cheating) i dont want to store the codes genereted by the game in plain text. But sinc...
What is the most secure python "password" encryption
I am making a little webgame that has tasks and solutions, the solutions are solved by entering a code given to user after completion of a task. To have some security (against cheating) i dont want to store the codes genereted by the game in plain text. But since i need to be able to give a player the code when he has ...
[ "The most secure encryption is no encryption. Passwords should be reduced to a hash. This is a one-way transformation, making the password (almost) unrecoverable.\nWhen giving someone a code, you can do the following to be actually secure. \n(1) generate some random string.\n(2) give them the string.\n(3) save t...
[ 5, 5, 2, 0 ]
[]
[]
[ "encryption", "python", "security" ]
stackoverflow_0001043735_encryption_python_security.txt
Q: Can a slow network cause a Python app to use *more* CPU? Let's say we have a system like this: ______ { application instances ---network--- (______) { application instances ---network---...
Can a slow network cause a Python app to use *more* CPU?
Let's say we have a system like this: ______ { application instances ---network--- (______) { application instances ---network--- | | requests ---> load balancer { application instance...
[ "In theory, no, in practice, its possible; it depends on what you're doing.\nThere's a full hour-long video and pdf about it, but essentially it boils down to some unforeseen consequences of the GIL with CPU vs IO bound threads with multicores. Basically, a thread waiting on IO needs to wake up, so Python begins \...
[ 6, 1, 1, 1 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0001046873_multithreading_python.txt
Q: Does Python's heapify() not play well with list comprehension and slicing? I found an interesting bug in a program that I implemented somewhat lazily, and wondered if I'm comprehending it correctly. The short version is that Python's heapq implementation doesn't actually order a list, it merely groks the list in a...
Does Python's heapify() not play well with list comprehension and slicing?
I found an interesting bug in a program that I implemented somewhat lazily, and wondered if I'm comprehending it correctly. The short version is that Python's heapq implementation doesn't actually order a list, it merely groks the list in a heap-centric way. Specifically, I was expecting heapify() to result in an order...
[ "A heap is not a sorted list (it's a representation of a partially sorted binary tree).\nSo yes, you're right, if you expect a heapified list to behave like a sorted list, you'll be disappointed. The only sorting assumption you can make about a heap is that heap[0] is always its smallest element.\n(It's difficult ...
[ 9, 0, 0, 0 ]
[]
[]
[ "heap", "list_comprehension", "python" ]
stackoverflow_0001046683_heap_list_comprehension_python.txt
Q: orbited comment server issue I tried installing orbited on vista . but I get following error when I try to run the orbited server.When I type on twisted cmd prompt orbited i get following o/p. C:\&gt;orbited Traceback (most recent call last): File "C:\Python26\scripts\orbited-script.py", line 8, in <module> ...
orbited comment server issue
I tried installing orbited on vista . but I get following error when I try to run the orbited server.When I type on twisted cmd prompt orbited i get following o/p. C:\&gt;orbited Traceback (most recent call last): File "C:\Python26\scripts\orbited-script.py", line 8, in <module> load_entry_point('orbited==0.7.9',...
[ "Do you have write permission on the file debug.log (and the directory it's to be placed in, which I think is the current directory)? If not, you could try tweaking the config.map being used to setup the logging subsystem (about midway through this stack trace).\n" ]
[ 1 ]
[]
[]
[ "comet", "orbited", "python", "twisted" ]
stackoverflow_0001047349_comet_orbited_python_twisted.txt
Q: Easiest way to persist a data structure to a file in python? Let's say I have something like this: d = { "abc" : [1, 2, 3], "qwerty" : [4,5,6] } What's the easiest way to progammatically get that into a file that I can load from python later? Can I somehow save it as python source (from within a python script, n...
Easiest way to persist a data structure to a file in python?
Let's say I have something like this: d = { "abc" : [1, 2, 3], "qwerty" : [4,5,6] } What's the easiest way to progammatically get that into a file that I can load from python later? Can I somehow save it as python source (from within a python script, not manually!), then import it later? Or should I use JSON or somet...
[ "Use the pickle module.\nimport pickle\nd = { \"abc\" : [1, 2, 3], \"qwerty\" : [4,5,6] }\nafile = open(r'C:\\d.pkl', 'wb')\npickle.dump(d, afile)\nafile.close()\n\n#reload object from file\nfile2 = open(r'C:\\d.pkl', 'rb')\nnew_d = pickle.load(file2)\nfile2.close()\n\n#print dictionary object loaded from file\npri...
[ 69, 15, 7, 5, 5, 3, 1 ]
[]
[]
[ "file", "persistence", "python" ]
stackoverflow_0001047318_file_persistence_python.txt
Q: Retrieving a tuple from a collection of tuples based on a contained value I have a data structure which is a collection of tuples like this: things = ( (123, 1, "Floogle"), (154, 33, "Blurgle"), (156, 55, "Blarg") ) The first and third elements are each unique to the collection. What I want to do is retrieve a sp...
Retrieving a tuple from a collection of tuples based on a contained value
I have a data structure which is a collection of tuples like this: things = ( (123, 1, "Floogle"), (154, 33, "Blurgle"), (156, 55, "Blarg") ) The first and third elements are each unique to the collection. What I want to do is retrieve a specific tuple by referring to the third value, eg: >>> my_thing = things.get( va...
[ "A loop (or something 100% equivalent like a list comprehension or genexp) is really the only approach if your outer-level structure is a tuple, as you indicate -- tuples are, by deliberate design, an extremely light-weight container, with hardly any methods in fact (just the few special methods needed to implement...
[ 4, 1, 1 ]
[]
[]
[ "python", "tuples" ]
stackoverflow_0001047403_python_tuples.txt
Q: wxpython: How can I redraw something when a window is retored? In my wx.Frame based wxpython application, I draw some lines on a panel when some events occur by creating wx.ClientDC instances when needed. The only problem is, if the window is minimized and then restored, the lines disappear! Is there some kind of ...
wxpython: How can I redraw something when a window is retored?
In my wx.Frame based wxpython application, I draw some lines on a panel when some events occur by creating wx.ClientDC instances when needed. The only problem is, if the window is minimized and then restored, the lines disappear! Is there some kind of method that I should override or event to bind to that will allow me...
[ "only place you must be drawing is on wx.EVT_PAINT, so bind to that event in init of panel e.g.\nself.Bind(wx.EVT_PAINT, self._onPaint)\n\nin _onPaint, use wx.PaintDC to to draw e.g.\ndc = wx.PaintDC(self)\ndc.DrawLine(0,0,100,100)\n\n", "When the window is restored it is (on some platforms) repainted using EVT_P...
[ 1, 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0001046157_python_wxpython.txt
Q: How to parse for tags with '+' in python I'm getting a "nothing to repeat" error when I try to compile this: search = re.compile(r'([^a-zA-Z0-9])(%s)([^a-zA-Z0-9])' % '+test', re.I) The problem is the '+' sign. How should I handle that? A: re.compile(r'([^a-zA-Z0-9])(%s)([^a-zA-Z0-9])' % '\+test', re.I) The "...
How to parse for tags with '+' in python
I'm getting a "nothing to repeat" error when I try to compile this: search = re.compile(r'([^a-zA-Z0-9])(%s)([^a-zA-Z0-9])' % '+test', re.I) The problem is the '+' sign. How should I handle that?
[ "re.compile(r'([^a-zA-Z0-9])(%s)([^a-zA-Z0-9])' % '\\+test', re.I)\n\nThe \"+\" is the \"repeat at least once\" quantifier in regular expressions. It must follow something that is repeatable, or it must be escaped if you want to match a literal \"+\".\nBetter is this, if you want to build your regex dynamically.\nr...
[ 9, 8 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0001048541_python_regex.txt
Q: Python and PGP/encryption i want to make a function using python to encrypt password by the public key. at the user end i need to install PGP software which will generate the key pair .i want to use public key only for encryption and private key for decryption. The problem is coming with the encryption function(ho...
Python and PGP/encryption
i want to make a function using python to encrypt password by the public key. at the user end i need to install PGP software which will generate the key pair .i want to use public key only for encryption and private key for decryption. The problem is coming with the encryption function(how to use key for encryption) an...
[ "Did you check out PyCrypto?\n", "Here is an open source project for using pgp with python. I think this is what you're looking for.\nYou actually don't have to invent the algorithms yourself, they're already there.\n" ]
[ 4, 4 ]
[]
[]
[ "encryption", "pgp", "python" ]
stackoverflow_0001048722_encryption_pgp_python.txt
Q: Resize images in directory I have a directory full of images that I would like to resize to around 60% of their original size. How would I go about doing this? Can be in either Python or Perl Cheers Eef A: If you want to do it programatically, which I assume is the case, use PIL to resize e.g. newIm = im.resize(...
Resize images in directory
I have a directory full of images that I would like to resize to around 60% of their original size. How would I go about doing this? Can be in either Python or Perl Cheers Eef
[ "If you want to do it programatically, which I assume is the case, use PIL to resize e.g.\nnewIm = im.resize((newW, newH)\n\nthen save it to same file or a new location.\nGo through the folder recursively and apply resize function to all images.\nI have come up with a sample script which I think will work for you. ...
[ 17, 11, 10, 2, 1, 0 ]
[]
[]
[ "image", "image_scaling", "perl", "python", "resize" ]
stackoverflow_0001048658_image_image_scaling_perl_python_resize.txt
Q: Display row count from another table in Django I have the following classes in my models file class HardwareNode(models.Model): ip_address = models.CharField(max_length=15) port = models.IntegerField() location = models.CharField(max_length=50) hostname = models.CharField(max_length=30) def __...
Display row count from another table in Django
I have the following classes in my models file class HardwareNode(models.Model): ip_address = models.CharField(max_length=15) port = models.IntegerField() location = models.CharField(max_length=50) hostname = models.CharField(max_length=30) def __unicode__(self): return self.hostname class...
[ "When creating a foreign_key, the other model gets a manager that returns all instances of the first model (see navigating backward)\nIn your case, it would be named \"subscription_set\".\nIn addition, Django allows for virtual fields in models, called \"Model Methods\", that are not connected to database data, but...
[ 7, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0001048782_django_django_models_python.txt
Q: How to sort on number of visits in Django app? In Django (1.0.2), I have 2 models: Lesson and StatLesson. class Lesson(models.Model): contents = models.TextField() def get_visits(self): return self.statlesson_set.all().count() class StatLesson(models.Model): lesson = models.ForeignKey(Lesson) ...
How to sort on number of visits in Django app?
In Django (1.0.2), I have 2 models: Lesson and StatLesson. class Lesson(models.Model): contents = models.TextField() def get_visits(self): return self.statlesson_set.all().count() class StatLesson(models.Model): lesson = models.ForeignKey(Lesson) datetime = models.DateTimeField(default=datetime...
[ "Django 1.1 will have aggregate support.\nOn Django 1.0.x you can count automatically with an extra field:\nclass Lesson(models.Model):\n contents = models.TextField()\n visit_count = models.IntegerField(default=0)\n\nclass StatLesson(models.Model):\n lesson = models.ForeignKey(Lesson)\n datetime = mode...
[ 2, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001048265_django_python.txt
Q: wxPython SplitterWindow does not expand within a Panel I'm trying a simple layout and the panel divided by a SplitterWindow doesn't expand to fill the whole area, what I want is this: [button] <= (fixed size) --------- TEXT AREA } ~~~~~~~~~ <= (this is the ...
wxPython SplitterWindow does not expand within a Panel
I'm trying a simple layout and the panel divided by a SplitterWindow doesn't expand to fill the whole area, what I want is this: [button] <= (fixed size) --------- TEXT AREA } ~~~~~~~~~ <= (this is the splitter) } this is a panel TEXT AREA ...
[ "The Panel is probably expanding but the ScrolledWindow within the Panel is not, because you aren't using a sizer for the panel, only the frame.\nYou could also try just having the SplitterWindow be a child of the frame, without the panel.\n" ]
[ 4 ]
[]
[]
[ "panel", "python", "user_interface", "wxpython" ]
stackoverflow_0001049070_panel_python_user_interface_wxpython.txt
Q: What to do after starting simple_server? For some quick background, I'm an XHTML/CSS guy with some basic PHP knowledge. I'm trying to dip my feet into the Python pool, and so far understand how to start simple_server and access a simple Hello World return in the same .py file. This is the extent of what I understa...
What to do after starting simple_server?
For some quick background, I'm an XHTML/CSS guy with some basic PHP knowledge. I'm trying to dip my feet into the Python pool, and so far understand how to start simple_server and access a simple Hello World return in the same .py file. This is the extent of what I understand though, heh. How do I integrate the simple_...
[ "I would recommend Django.\n", "The other answers give good recommendations for what you probably want to do towards your \"eventual goal\", but, if you first want to persist with wsgiref.simple_server for an instructive while, you can do that too. WSGI is the crucial \"glue\" between web servers (not just the si...
[ 3, 3, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001046980_python.txt
Q: Importing database data into Joomla How to import data from a database to Joomla CMS? I have a database with lots of data I want to use in my new website. An ideal solution for me would be a Python/Perl/PHP API that would know how to do Joomla' basic routines: adding/removing a section/category/material/menu/modu...
Importing database data into Joomla
How to import data from a database to Joomla CMS? I have a database with lots of data I want to use in my new website. An ideal solution for me would be a Python/Perl/PHP API that would know how to do Joomla' basic routines: adding/removing a section/category/material/menu/module; changing properties of existing entit...
[ "You could try the following extensions:\n\nBulk Import\nCSV Import\n\nIf that doesn't work for you, maybe take a look at the Joomla API\n" ]
[ 1 ]
[]
[]
[ "api", "content_management_system", "database", "joomla", "python" ]
stackoverflow_0001049320_api_content_management_system_database_joomla_python.txt
Q: Dictionaries with volatile values in Python unit tests? I need to write a unit test for a function that returns a dictionary. One of the values in this dictionary is datetime.datetime.now() which of course changes with every test run. I want to ignore that key completely in my assert. Right now I have a dictionary...
Dictionaries with volatile values in Python unit tests?
I need to write a unit test for a function that returns a dictionary. One of the values in this dictionary is datetime.datetime.now() which of course changes with every test run. I want to ignore that key completely in my assert. Right now I have a dictionary comparison function but I really want to use assertEqual lik...
[ "Just delete the timestamp from the dict before doing the comparison:\nclass MonkeyTester(unittest.TestCase):\n def test_myfunc(self):\n without_timestamp = my_func()\n del without_timestamp[\"monkey_creation\"]\n self.assertEqual(without_timestamp, {'monkey_head_count': 3})\n\nIf you find y...
[ 9 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0001049551_python_unit_testing.txt
Q: How do I link a combo box and a command button? This is my combo box code: self.lblname = wx.StaticText(self, -1,"Timeslot" ,wx.Point(20,150)) self.sampleList = ['09.00-10.00','10.00-11.00','11.00-12.00'] self.edithear=wx.ComboBox(self, 30, "", wx.Point(150,150 ), wx.Size(95, -1), self.sampleList, wx.CB_DROPDOWN...
How do I link a combo box and a command button?
This is my combo box code: self.lblname = wx.StaticText(self, -1,"Timeslot" ,wx.Point(20,150)) self.sampleList = ['09.00-10.00','10.00-11.00','11.00-12.00'] self.edithear=wx.ComboBox(self, 30, "", wx.Point(150,150 ), wx.Size(95, -1), self.sampleList, wx.CB_DROPDOWN) and this is my command button code: def OnClick(se...
[ "If the Onclick method is in the same class you can reach your combo via self.edithear \n" ]
[ 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0001048831_python_wxpython.txt
Q: subprocess module: using the call method with tempfile objects I have created temporary named files, with the tempfile libraries NamedTemporaryFile method. I have written to them flushed the buffers, and I have not closed them (or else they might go away) I am trying to use the subprocess module to call some shell...
subprocess module: using the call method with tempfile objects
I have created temporary named files, with the tempfile libraries NamedTemporaryFile method. I have written to them flushed the buffers, and I have not closed them (or else they might go away) I am trying to use the subprocess module to call some shell commands using these generated files. subprocess.call('cat %s' % f....
[ "Why don't you make your NamedTemporaryFiles with the optional parameter delete=False? That way you can safely close them knowing they won't disappear, use them normally afterwards, and explicitly unlink them when you're done. This way everything will work cross-platform, too.\n", "Are you using shell=True option...
[ 3, 1 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0001049648_python_subprocess.txt
Q: Get remote text file, process, and update database - approach and scripting language to use? I've been having to do some basic feed processing. So, get a file via ftp, process it (i.e. get the fields I care about), and then update the local database. And similarly the other direction: get data from db, create file...
Get remote text file, process, and update database - approach and scripting language to use?
I've been having to do some basic feed processing. So, get a file via ftp, process it (i.e. get the fields I care about), and then update the local database. And similarly the other direction: get data from db, create file, and upload by ftp. The scripts will be called by cron. I think the idea would be for each type o...
[ "Kind of depends on the format of the files you're ftp'ing. If it's a crazy proprietary format, you might be stuck with whatever language already has a library managing it. If it's CSV or XML, then any language might do.\n\nFTP: Net::FTP\nParse: Text::CSV_XS (for CSV or tab-separated) or XML::Twig (for XML)\nInse...
[ 3, 2, 1, 1 ]
[]
[]
[ "feed", "parsing", "perl", "php", "python" ]
stackoverflow_0001050089_feed_parsing_perl_php_python.txt
Q: Problem with SQLite executemany I can't find my error in the following code. When it is run a type error is given for line: cur.executemany(sql % itr.next()) => 'function takes exactly 2 arguments (1 given), import sqlite3 con = sqlite3.connect('test.sqlite') cur = con.cursor() cur.execute("create table IF NOT E...
Problem with SQLite executemany
I can't find my error in the following code. When it is run a type error is given for line: cur.executemany(sql % itr.next()) => 'function takes exactly 2 arguments (1 given), import sqlite3 con = sqlite3.connect('test.sqlite') cur = con.cursor() cur.execute("create table IF NOT EXISTS fred (dat)") def newSave(class...
[ "Like it says, executemany takes two arguments. Instead of interpolating the string values yourself with the %, you should pass both the sql and the values and let the db adapter quote them.\nsql = \" '''insert into %s (%s) values(%%s)''',\" % (className, colNames)\ncur.executemany(sql, itr.next())\n\n", "See the...
[ 3, 2, 2, 0 ]
[]
[]
[ "pysqlite", "python" ]
stackoverflow_0001030941_pysqlite_python.txt
Q: Parsing an unknown data structure in python I have a file containing lots of data put in a form similar to this: Group1 { Entry1 { Title1 [{Data1:Member1, Data2:Member2}] Title2 [{Data3:Member3, Data4:Member4}] } Entry2 { ... } } Group2 { DifferentEntry1 ...
Parsing an unknown data structure in python
I have a file containing lots of data put in a form similar to this: Group1 { Entry1 { Title1 [{Data1:Member1, Data2:Member2}] Title2 [{Data3:Member3, Data4:Member4}] } Entry2 { ... } } Group2 { DifferentEntry1 { DiffTitle1 { ... } ...
[ "The data structure basically seems to be a dict where they keys are strings and the value is either a string or another dict of the same type, so I'd recommend maybe pulling it into that sort of python structure,\neg:\n{'group1': {'Entry2': {}, 'Entry1': {'Title1':{'Data4': 'Member4',\n'Data1': 'Member1','Data3': ...
[ 3, 3, 2, 1, 1, 1 ]
[]
[]
[ "data_structures", "parsing", "python" ]
stackoverflow_0001050773_data_structures_parsing_python.txt
Q: Including a dynamic image in a web page using POST? I have written a CGI script that creates an image dynamically using GET data. To include this image in my webpage, I am using the following code: <img src="image.py?text=xxxxxxxxxxxxxx"> The problem is that I expect in the future the "text" field will get very l...
Including a dynamic image in a web page using POST?
I have written a CGI script that creates an image dynamically using GET data. To include this image in my webpage, I am using the following code: <img src="image.py?text=xxxxxxxxxxxxxx"> The problem is that I expect in the future the "text" field will get very long and the URL will become too large. From Googling arou...
[ "Store the text somewhere (e.g. a database) and then pass through the primary key.\n", "This will get you an Image as the result of a POST -- you may not like it\n\nPut an iFrame where you want the image and size it and remove scrollbars\nSet the src to a form with hidden inputs set to your post parameters and th...
[ 5, 1, 1, 0, 0, 0, 0, 0 ]
[]
[]
[ "cgi", "django", "html", "image", "python" ]
stackoverflow_0000243375_cgi_django_html_image_python.txt
Q: Anyone successfully adopted JaikuEngine? Are there real world adaptations of JaikuEngine on Google App Engine? (Question from my boss which wants to use it instead writing our own system) A: This is jaikuengine running on AppEngine - https://jaiku.appspot.com/ If you wish to have your own version of jaiku, its p...
Anyone successfully adopted JaikuEngine?
Are there real world adaptations of JaikuEngine on Google App Engine? (Question from my boss which wants to use it instead writing our own system)
[ "This is jaikuengine running on AppEngine - https://jaiku.appspot.com/\nIf you wish to have your own version of jaiku, its pretty straightforward. Check this out- http://code.google.com/p/jaikuengine/\n", "Whilst I love the App-Engine. Does your solution need to be hosted on the AppEngine? If not I would check ...
[ 2, 1, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0000852268_google_app_engine_python.txt
Q: How can I write my own aggregate functions with sqlalchemy? How can I write my own aggregate functions with SQLAlchemy? As an easy example I would like to use numpy to calculate the variance. With sqlite it would look like this: import sqlite3 as sqlite import numpy as np class self_written_SQLvar(object): def ...
How can I write my own aggregate functions with sqlalchemy?
How can I write my own aggregate functions with SQLAlchemy? As an easy example I would like to use numpy to calculate the variance. With sqlite it would look like this: import sqlite3 as sqlite import numpy as np class self_written_SQLvar(object): def __init__(self): import numpy as np self.values = [] def...
[ "The creation of new aggregate functions is backend-dependant, and must be done \ndirectly with the API of the underlining connection. SQLAlchemy offers no \nfacility for creating those.\nHowever after created you can just use them in SQLAlchemy normally.\nExample:\nimport sqlalchemy\nfrom sqlalchemy import Column,...
[ 13 ]
[ "at first you have to import func from sqlalchemy\nyou can write \nfunc.avg('fieldname')\nor func.avg('fieldname').label('user_deined') \nor you can go thru for mre information \nhttp://www.sqlalchemy.org/docs/05/ormtutorial.html#using-subqueries\n" ]
[ -1 ]
[ "aggregate_functions", "python", "sqlalchemy", "sqlite" ]
stackoverflow_0000996922_aggregate_functions_python_sqlalchemy_sqlite.txt
Q: Create SQL query using SqlAlchemy select and join functions I have two tables "tags" and "deal_tag", and table definition follows, Table('tags', metadata, Column('id', types.Integer(), Sequence('tag_uid_seq'), primary_key=True), Column('name', types.String()), ) Table('d...
Create SQL query using SqlAlchemy select and join functions
I have two tables "tags" and "deal_tag", and table definition follows, Table('tags', metadata, Column('id', types.Integer(), Sequence('tag_uid_seq'), primary_key=True), Column('name', types.String()), ) Table('deal_tag', metadata, Column('dealid', types.Integer(), Fore...
[ "Give this a try...\ns = select([tags.c.Name, tags.c.id, func.count(deal_tag.dealid)], \n tags.c.id == deal_tag.c.tagid).group_by(tags.c.Name, tags.c.id)\n\n", "you can join table in the time of mapping table\nin the orm.mapper()\nfor more information you can go thru the link\nwww.sqlalchemy.org/docs/\n...
[ 2, 0 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0000950910_python_sqlalchemy.txt
Q: How can I parse the output of /proc/net/dev into key:value pairs per interface using Python? The output of /proc/net/dev on Linux looks like this: Inter-| Receive | Transmit face |bytes packets errs drop fifo frame compressed multicast|bytes packets errs dro...
How can I parse the output of /proc/net/dev into key:value pairs per interface using Python?
The output of /proc/net/dev on Linux looks like this: Inter-| Receive | Transmit face |bytes packets errs drop fifo frame compressed multicast|bytes packets errs drop fifo colls carrier compressed lo:18748525 129811 0 0 0 0 0 0 ...
[ "this is pretty formatted input and you can easily get columns and data list by splitting each line, and then create a dict of of it.\nhere is a simple script without regex\nlines = open(\"/proc/net/dev\", \"r\").readlines()\n\ncolumnLine = lines[1]\n_, receiveCols , transmitCols = columnLine.split(\"|\")\nreceiveC...
[ 15, 1, 1 ]
[]
[]
[ "linux", "parsing", "python" ]
stackoverflow_0001052589_linux_parsing_python.txt
Q: Creating an interactive shell for .NET apps and embed scripting languages like python/iron python into it I was learning python using the tutorial that comes with the standard python installation. One of the benefits that the author states about python is "maybe you’ve written a program that could use an extension...
Creating an interactive shell for .NET apps and embed scripting languages like python/iron python into it
I was learning python using the tutorial that comes with the standard python installation. One of the benefits that the author states about python is "maybe you’ve written a program that could use an extension language, and you don’t want to design and implement a whole new language for your application" - My question ...
[ "This sounds like a great use of IronPython.\nIt's fairly easy to set up a simple scripting host from C# to allow calls into IronPython scripts, as well as allowing IronPython to call into your C# code. There are samples and examples on the CodePlex site that show how to do this very thing.\nAnother good site for e...
[ 12, 3, 1, 1, 1, 0 ]
[]
[]
[ ".net", "c#", "ironpython", "python", "python.net" ]
stackoverflow_0000808692_.net_c#_ironpython_python_python.net.txt
Q: How can I convert a Perl regex with named groups to Python? I am trying to convert the following Perl regex I found in the Video::Filename Perl module to a Python 2.5.4 regex to parse a filename # Perl > v5.10 re => '^(?:(?<name>.*?)[\/\s._-]*)?(?<openb>\[)?(?<season>\d{1,2})[x\/](?<episode>\d{1,2})(?:-(?:\k<seaso...
How can I convert a Perl regex with named groups to Python?
I am trying to convert the following Perl regex I found in the Video::Filename Perl module to a Python 2.5.4 regex to parse a filename # Perl > v5.10 re => '^(?:(?<name>.*?)[\/\s._-]*)?(?<openb>\[)?(?<season>\d{1,2})[x\/](?<episode>\d{1,2})(?:-(?:\k<season>x)?(?<endep>\d{1,2}))?(?(<openb>)\])(?:[\s._-]*(?<epname>[^\/]+...
[ "There are 2 problems with your translation. First of all, the second mention of openb has extra parenthesis around it making it a conditional expression, not a named expression.\nNext is that you didn't translate the \\k<season> backreference, Python uses (P=season) to match the same. The following compiles for me...
[ 6, 2, 0, 0 ]
[]
[]
[ "perl", "python", "regex" ]
stackoverflow_0001052930_perl_python_regex.txt
Q: Testing for ImportErrors in Python We're having a real problem with people checking in code that doesn't work because something's been refactored. Admittedly, this is partly because our developers don't really have any good tools for finding these kinds of mistakes easily. Are there any tools to help find ImportE...
Testing for ImportErrors in Python
We're having a real problem with people checking in code that doesn't work because something's been refactored. Admittedly, this is partly because our developers don't really have any good tools for finding these kinds of mistakes easily. Are there any tools to help find ImportErrors in Python? Of course, the correct...
[ "Pychecker is for you. It imports the modules and will find these errors.\nhttp://pychecker.sourceforge.net/\nOh, and \"pylint <modulename>\" will import the module, but I guess you would have to call it once for every module you want, where pychecker at least supports *.py. (Pylint also support *.py but won't impo...
[ 3, 1 ]
[]
[]
[ "continuous_integration", "importerror", "python", "refactoring", "unit_testing" ]
stackoverflow_0001052931_continuous_integration_importerror_python_refactoring_unit_testing.txt
Q: python-scapy: how to translate port numbers to service names? A TCP layer in Scapy contains source port: >>> a[TCP].sport 80 Is there a simple way to convert port number to service name? I've seen Scapy has TCP_SERVICES and UDP_SERVICES to translate port number, but print TCP_SERVICES[80] # fails print TCP_SERVI...
python-scapy: how to translate port numbers to service names?
A TCP layer in Scapy contains source port: >>> a[TCP].sport 80 Is there a simple way to convert port number to service name? I've seen Scapy has TCP_SERVICES and UDP_SERVICES to translate port number, but print TCP_SERVICES[80] # fails print TCP_SERVICES['80'] # fails print TCP_SERVICES.__getitem__(80) # fails print ...
[ "Python's socket module will do that:\n>>> import socket\n>>> socket.getservbyport(80)\n'http'\n>>> socket.getservbyport(21)\n'ftp'\n>>> socket.getservbyport(53, 'udp')\n'domain'\n\n", "If this is something you need to do frequently, you can create a reverse mapping of TCP_SERVICES:\n>>> TCP_REVERSE = dict((TCP_S...
[ 20, 5, 1, 0, 0 ]
[]
[]
[ "python", "scapy", "tcp" ]
stackoverflow_0000976599_python_scapy_tcp.txt
Q: How to "keep-alive" with cookielib and httplib in python? In python, I'm using httplib because it "keep-alive" the http connection (as oppose to urllib(2)). Now, I want to use cookielib with httplib but they seem to hate each other!! (no way to interface them together). Does anyone know of a solution to that prob...
How to "keep-alive" with cookielib and httplib in python?
In python, I'm using httplib because it "keep-alive" the http connection (as oppose to urllib(2)). Now, I want to use cookielib with httplib but they seem to hate each other!! (no way to interface them together). Does anyone know of a solution to that problem?
[ "HTTP handler for urllib2 that supports keep-alive\n", "You should consider using the Requests library instead at the earliest chance you have to refactor your code. In the mean time;\nHACK ALERT! :)\nI'd go other suggested way, but I've done a hack (done for different reasons though), which does create an interf...
[ 2, 2 ]
[]
[]
[ "cookies", "httplib", "python", "urllib2" ]
stackoverflow_0001016765_cookies_httplib_python_urllib2.txt
Q: How do I convert a Python float to a hexadecimal string in python 2.5? Nonworking solution attached What I really need to do is to export a floating point number to C with no precision loss. I did this in python: import math import struct x = math.sqrt(2) print struct.unpack('ii', struct.pack('d', x)) # prints (17...
How do I convert a Python float to a hexadecimal string in python 2.5? Nonworking solution attached
What I really need to do is to export a floating point number to C with no precision loss. I did this in python: import math import struct x = math.sqrt(2) print struct.unpack('ii', struct.pack('d', x)) # prints (1719614413, 1073127582) And in C I try this: #include <math.h> #include <stdio.h> int main(void) { unsi...
[ "The Python code appears to work. The problem is in the C code: you have the long long filled out right, but then you convert the integer value directly into floating point, rather than reinterpreting the bytes as a double. If you throw some pointers/addressing at it it works:\njkugelman$ cat float.c\n#include <std...
[ 6, 3, 1 ]
[]
[]
[ "double", "python" ]
stackoverflow_0001053121_double_python.txt