content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: Python: super and __init__() vs __init__( self ) A: super( BasicElement, self ).__init__() B: super( BasicElement, self ).__init__( self ) What is the difference between A and B? Most examples that I run across use A, but I am running into an issue where A is not calling the parent __init__ function, but B is. ...
Python: super and __init__() vs __init__( self )
A: super( BasicElement, self ).__init__() B: super( BasicElement, self ).__init__( self ) What is the difference between A and B? Most examples that I run across use A, but I am running into an issue where A is not calling the parent __init__ function, but B is. Why might this be? Which should be used and in which c...
[ "You should not need to do that second form, unless somehow BasicElement class's __init__ takes an argument. \nclass A(object):\n def __init__(self):\n print \"Inside class A init\"\n\nclass B(A):\n def __init__(self):\n super(B, self).__init__()\n print \"Inside class B init\"\n\n>>> b =...
[ 26 ]
[]
[]
[ "python" ]
stackoverflow_0007629556_python.txt
Q: Pyramid and Chameleon ZPT Repetition I am trying to loop through a list and get an output like this: Python: items=['item1', 'item2', 'item3'] return dict(items=items) HTML: <ul> <li><a href="/item1>item1</a></li> <li><a href="/item1>item2</a></li> <li><a href="/item1>item3</a></li> </ul> I can get the list part...
Pyramid and Chameleon ZPT Repetition
I am trying to loop through a list and get an output like this: Python: items=['item1', 'item2', 'item3'] return dict(items=items) HTML: <ul> <li><a href="/item1>item1</a></li> <li><a href="/item1>item2</a></li> <li><a href="/item1>item3</a></li> </ul> I can get the list part right but adding it to the anchor is not ...
[ "How about (supposing 'items' is a namespace passed from your code to your template):\n<ul>\n <tal:block repeat=\"item items\">\n <li><a href=\"\" tal:attributes=\"href item\" tal:content=\"item\">item</a></li>\n </tal:block>\n</ul>\n\nYou can put tal:repeat on the li element, but I personally like to use a dedica...
[ 2 ]
[]
[]
[ "chameleon", "pyramid", "python", "template_tal" ]
stackoverflow_0007628789_chameleon_pyramid_python_template_tal.txt
Q: Python equivalent of find2perl Perl has a lovely little utility called find2perl that will translate (quite faithfully) a command line for the Unix find utility into a Perl script to do the same. If you have a find command like this: find /usr -xdev -type d -name '*share' ^^^^^^^^^^^^ ...
Python equivalent of find2perl
Perl has a lovely little utility called find2perl that will translate (quite faithfully) a command line for the Unix find utility into a Perl script to do the same. If you have a find command like this: find /usr -xdev -type d -name '*share' ^^^^^^^^^^^^ => name with shell expansion of '*sh...
[ "If you're trying to reimplement all of find, then yes, your code is going to get hairy. find is pretty hairy all by itself. \nIn most cases, though, you're not trying to replicate the complete behavior of find; you're performing a much simpler task (e.g., \"find all files that end in .txt\"). If you really need ...
[ 4, 2, 1, 1 ]
[]
[]
[ "find", "os.walk", "python" ]
stackoverflow_0007541863_find_os.walk_python.txt
Q: Proper syntax for executing a function only if another function is successful I have the following code that is part of my email class that I use in my programs. Currently I am running the quit function whether or not a connection to the SMTP server was made in the connect function. I know I could put the quit f...
Proper syntax for executing a function only if another function is successful
I have the following code that is part of my email class that I use in my programs. Currently I am running the quit function whether or not a connection to the SMTP server was made in the connect function. I know I could put the quit function inside of the try statement after the email is sent, but I would like to fi...
[ "You need to finish the \"Errors and Exceptions\" section of the tutorial.\ntry:\n possibly_fail()\nexcept ...:\n handle_exception()\nelse:\n no_exceptions()\nfinally:\n always_run_this()\n\n" ]
[ 4 ]
[]
[]
[ "function", "if_statement", "python", "syntax" ]
stackoverflow_0007629883_function_if_statement_python_syntax.txt
Q: NLTK "generate" function: How to get back returned text? I'm a Python noob, so bear with me. I'm trying to work with the NLTK library, and in particular the 'generate' function. It looks like from the documentation this function simply prints its result (http://nltk.googlecode.com/svn/trunk/doc/api/nltk.text-pysrc...
NLTK "generate" function: How to get back returned text?
I'm a Python noob, so bear with me. I'm trying to work with the NLTK library, and in particular the 'generate' function. It looks like from the documentation this function simply prints its result (http://nltk.googlecode.com/svn/trunk/doc/api/nltk.text-pysrc.html). I would like to manipulate the resulting text prior to...
[ "All generate is doing is generating a trigram model if none exists, then calling\ntext = self._trigram_model.generate(length)\n\nand wrapping and printing it. \nJust take the parts you want -- possibly just the above line (with self replaced by the instance name), or possibly the whole thing, as below, with the fi...
[ 2 ]
[ "Go into Python26/site-packages/nltk/text.py and change the \"generate\" function:\n def generate(self, length=100):\n if '_trigram_model' not in self.__dict__:\n print \"Building ngram index...\"\n estimator = lambda fdist, bins: LidstoneProbDist(fdist, 0.2)\n self._trig...
[ -1 ]
[ "nltk", "python" ]
stackoverflow_0007629872_nltk_python.txt
Q: Can't install module with python-pip properly I would like to install a module but pip is not installing it in the right directory which I assume should be /usr/local/lib/python2.7/site-packages/. After all, I just installed Python 2.7.2 today. Originally I had 2.6.5 and had installed modules successfully there. S...
Can't install module with python-pip properly
I would like to install a module but pip is not installing it in the right directory which I assume should be /usr/local/lib/python2.7/site-packages/. After all, I just installed Python 2.7.2 today. Originally I had 2.6.5 and had installed modules successfully there. So I think something is wrong with my Python path. ...
[ "After you installed Python 2.7, did you install the Python 2.7 version of easy_install and PIP? The existing installations are configured to use Python 2.6 by default which may be causing your issue.\n", "You are probably using pip linked to python2.6, instead of 2.7. If you have installed pip properly with pyth...
[ 5, 5 ]
[]
[]
[ "installation", "module", "pip", "python" ]
stackoverflow_0007622930_installation_module_pip_python.txt
Q: gcc failed with exit status 1 when installing libmemcached While trying to follow the python-libmemcached instructions at http://code.google.com/p/python-libmemcached/ I run into trouble at step 3 ("python setup.py install") (gigmash_venv)m:python-libmemcached matthewparrilla$ python setup.py build running...
gcc failed with exit status 1 when installing libmemcached
While trying to follow the python-libmemcached instructions at http://code.google.com/p/python-libmemcached/ I run into trouble at step 3 ("python setup.py install") (gigmash_venv)m:python-libmemcached matthewparrilla$ python setup.py build running build running build_py creating build creating buil...
[ "The error occurs because the file cmemcached_imp.c is not there, but must be compiled in this step.\nFirst, edit the file cmemcached_imp.pyx and fix the typo in line 506. Instead of\nsys.stderr.write(\"[cmemcached]%s only support string: %s\" % (cmd, key))\n\n, it should say\nsys.stderr.write(\"[cmemcached]%s only...
[ 4 ]
[]
[]
[ "gcc", "libmemcache", "python" ]
stackoverflow_0007629937_gcc_libmemcache_python.txt
Q: Python/C Raw Socket Operations using Django, Mod_WSGI, Apache I'm currently writing a web application using Django, Apache, and mod_wsgi that provides some FreeBSD server management and configuration features, including common firewall operations. My Python/C library uses raw sockets to interact directly with the...
Python/C Raw Socket Operations using Django, Mod_WSGI, Apache
I'm currently writing a web application using Django, Apache, and mod_wsgi that provides some FreeBSD server management and configuration features, including common firewall operations. My Python/C library uses raw sockets to interact directly with the firewall and works perfectly fine when running as root, but raw so...
[ "Use Celery or some other back end service which runs as root. Having a web application process run as root is a security problem waiting to happen. This is why mod_wsgi blocks you running daemon processes as root. Sure you could hack the code to disable the exclusion, but I am not about to tell you how to do that....
[ 1 ]
[]
[]
[ "django", "freebsd", "mod_wsgi", "python", "sockets" ]
stackoverflow_0007628889_django_freebsd_mod_wsgi_python_sockets.txt
Q: pyserial/python and real time data acquisition I have an infrared camera/tracker with which I am communicating via the serial port. I'm using the pyserial module to do this at the moment. The camera updates the position of a tracked object at the rate of 60 Hz. In order to get the position of the tracked object I ...
pyserial/python and real time data acquisition
I have an infrared camera/tracker with which I am communicating via the serial port. I'm using the pyserial module to do this at the moment. The camera updates the position of a tracked object at the rate of 60 Hz. In order to get the position of the tracked object I execute one pyserial.write() and then listen for an ...
[ "This is more a matter of latency than speed.\nPython always performs memory allocation and release, but if the data is reused, the same memory will be reused by the C library.\nSo the OS (C library / UDP/IP stack) will have more impact than Python itself.\nI really think you should use a serial port on your RTOS m...
[ 1, 0, 0 ]
[]
[]
[ "pyserial", "python", "real_time" ]
stackoverflow_0007629403_pyserial_python_real_time.txt
Q: Convert Multiline into list I have extracted a set of data from HTML page and copied to a variable. The variable looks like names=''' Apple Ball Cat''' Now I like to join each line into a list so that I can access any line I want. Is there any way to do that in Python A: Using splitlines() to...
Convert Multiline into list
I have extracted a set of data from HTML page and copied to a variable. The variable looks like names=''' Apple Ball Cat''' Now I like to join each line into a list so that I can access any line I want. Is there any way to do that in Python
[ "Using splitlines() to split by newline character and strip() to remove unnecessary white spaces.\n>>> names='''\n... Apple\n... Ball\n... Cat'''\n>>> names\n'\\n Apple\\n Ball\\n Cat'\n>>> names_list = [y for y in (x.strip() for x in names.splitlines()) if y]\n>>> # if x.strip() is...
[ 21, 14 ]
[ "names.split('\\n') should give you a list split by '\\n'\n" ]
[ -1 ]
[ "list", "python" ]
stackoverflow_0007630273_list_python.txt
Q: Printing out values of a dictionary line by line in Python I have the following code here: tel = {2: [[0, 0, 1, 1], [0, 1, 0, 1]], 3: [[1, 0, 1, 1], [1, 0, 1, 1], [1, 0, 0, 0], [1, 0, 1, 1], [1, 0, 1, 1]]} for i in tel.values(): a = ''.join(map(str,i)) print a The dictionary tel consists of keys which ...
Printing out values of a dictionary line by line in Python
I have the following code here: tel = {2: [[0, 0, 1, 1], [0, 1, 0, 1]], 3: [[1, 0, 1, 1], [1, 0, 1, 1], [1, 0, 0, 0], [1, 0, 1, 1], [1, 0, 1, 1]]} for i in tel.values(): a = ''.join(map(str,i)) print a The dictionary tel consists of keys which are the number of 1s in the keys value(here, they are lists of b...
[ ">>> for x in tel.values():\n... for y in x:\n... print ''.join(str(z) for z in y)\n... \n0011\n0101\n1011\n1011\n1000\n1011\n1011\n\n", "You could do:\nfor key in tel:\n for num in tel[key]:\n print ''.join(str(n) for n in num)\n\nFor your example this prints:\n0011\n0101\n1011\n1011\n1...
[ 2, 1, 0 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0007630237_dictionary_list_python.txt
Q: Python CGI queue I'm working on a fairly simple CGI with Python. I'm about to put it into Django, etc. The overall setup is pretty standard server side (i.e. computation is done on the server): User uploads data files and clicks "Run" button Server forks jobs in parallel behind the scenes, using lots of RAM and...
Python CGI queue
I'm working on a fairly simple CGI with Python. I'm about to put it into Django, etc. The overall setup is pretty standard server side (i.e. computation is done on the server): User uploads data files and clicks "Run" button Server forks jobs in parallel behind the scenes, using lots of RAM and processor power. ~5-1...
[ "Definitely use celery. You can run an amqp server or I think you can sue the database as a queue for the messages. It allows you to run tasks in the background and it can use multiple worker machines to do the processing if you want. It can also do cron jobs that are database based if you use django-celery\nIt's a...
[ 1 ]
[]
[]
[ "cgi", "python", "queue" ]
stackoverflow_0007629147_cgi_python_queue.txt
Q: Which is the fastest way to search a value within a set of many "range" objects in Python I have a list of many Python objects like this: class RangeClass(object): def __init__(self,address,size): self.address=address self.size=size #other attributes and methods... Then, I have a list...
Which is the fastest way to search a value within a set of many "range" objects in Python
I have a list of many Python objects like this: class RangeClass(object): def __init__(self,address,size): self.address=address self.size=size #other attributes and methods... Then, I have a list (rangelist) of RangeClass objects. I need to find within which range a given value is. I can u...
[ "If you have many values to test, then you could use the bisect module to find which range the values are in more quickly. \nIf \n\nm = the number of values to test, and\nn = len(rangelist)\n\nthen looping through the values and rangelist as you suggest would take O(m*n) time.\nIf you use bisection, then you must f...
[ 3, 2, 1, 1 ]
[]
[]
[ "list", "optimization", "performance", "python", "search" ]
stackoverflow_0007625024_list_optimization_performance_python_search.txt
Q: list / string in python I'm trying to parse tweets data. My data shape is as follows: 59593936 3061025991 null null <d>2009-08-01 00:00:37</d> <s>&lt;a href="http://help.twitter.com/index.php?pg=kb.page&amp;id=75" rel="nofollow"&gt;txt&lt;/a&gt;</s> <t>honda just recalled 440k accords...traffic around here is gonn...
list / string in python
I'm trying to parse tweets data. My data shape is as follows: 59593936 3061025991 null null <d>2009-08-01 00:00:37</d> <s>&lt;a href="http://help.twitter.com/index.php?pg=kb.page&amp;id=75" rel="nofollow"&gt;txt&lt;/a&gt;</s> <t>honda just recalled 440k accords...traffic around here is gonna be light...win!!</t> ajc858...
[ "Maybe change if keywords in line: to use a regular expression match instead. For example, something like:\nimport re\n...\nkeywords = \"|\".join(get_keywords('./related_keywords.txt', 'r'))\nmatcher = re.compile(keywords)\nif matcher.match(line):\n text = ...\n\n... And changed get_keywords to something like thi...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0007630515_python.txt
Q: Best way to get date strings with Python What's the best way to get datestrings from a website using Python? The datestrings can be, for example, in the forms of: April 1st, 2011 April 2nd, 2011 April 23, 2011 4/2/2011 04/23/2011 Would this have to be a ton of regex? What's the most elegant solution? A: Consi...
Best way to get date strings with Python
What's the best way to get datestrings from a website using Python? The datestrings can be, for example, in the forms of: April 1st, 2011 April 2nd, 2011 April 23, 2011 4/2/2011 04/23/2011 Would this have to be a ton of regex? What's the most elegant solution?
[ "Consider this lib: http://code.google.com/p/parsedatetime/\nFrom its examples Wiki page, here are a couple of formats it can handle that look relevant to your question:\nresult = p.parseDateText(\"March 5th, 1980\") \nresult = p.parseDate(\"4/4/80\") \n\nEDIT: now I notice it's actually a duplicate of this SO ques...
[ 2, 1 ]
[]
[]
[ "date", "parsing", "python", "regex" ]
stackoverflow_0005609962_date_parsing_python_regex.txt
Q: SWIG: python callback with function template and shared pointer as return value I'm creating wrappers using SWIG for python for my software library and I have the following function: template<class PR> boost::shared_ptr<JobT<PR> > Client::WaitForJob() { boost::shared_ptr<JobT<PR> > job; whi...
SWIG: python callback with function template and shared pointer as return value
I'm creating wrappers using SWIG for python for my software library and I have the following function: template<class PR> boost::shared_ptr<JobT<PR> > Client::WaitForJob() { boost::shared_ptr<JobT<PR> > job; while (!job.get()) { list<boost::shared_ptr<Job> > jobs = GetJobs(p_jobName,...
[ "The Swig object you get back is a proxy for the jobme. It should work just like a JobT wherever you need it.\nAh, I think I see the problem. You need to instantiate the JobT and Client::WaitForJob for each PR you have:\n%include \"boost_shared_ptr.i\"\n%shared_ptr(JobT<Foo>);\n\n#include <JobT.hpp>\n%template(Jo...
[ 0 ]
[]
[]
[ "boost", "python", "shared_ptr", "swig" ]
stackoverflow_0004592981_boost_python_shared_ptr_swig.txt
Q: wxPython and windows 7 taskbar For brevity's sake: I'm trying to implement this with wxPython, but I'm struggling to fit that code into a script based on wxPython. My simple PyQt test code works fine. Here it is: from PyQt4 import QtGui from threading import Thread import time import sys import comtypes.client as ...
wxPython and windows 7 taskbar
For brevity's sake: I'm trying to implement this with wxPython, but I'm struggling to fit that code into a script based on wxPython. My simple PyQt test code works fine. Here it is: from PyQt4 import QtGui from threading import Thread import time import sys import comtypes.client as cc import comtypes.gen.TaskbarLib as...
[ "On the following line:\nhWnd = self.panel.GetId()\n\nYou want to use GetHandle() instead of GetId().\nEdit: This was originally posted as a comment, but I suppose it would be more appropriate for me to repost as an answer.\nRegarding the edit to your question: If it now works I guess there isn't a problem anymore ...
[ 1 ]
[]
[]
[ "api", "python", "taskbar", "user_interface", "windows_7" ]
stackoverflow_0007630440_api_python_taskbar_user_interface_windows_7.txt
Q: Python Strategy for Large Scale Analysis (on-the-fly or deferred) To analyze a large number of websites or financial data and pull out parametric data, what are the optimal strategies? I'm classifying the following strategies as either "on-the-fly" or "deferred". Which is best? On-the-fly: Process data on-the-fl...
Python Strategy for Large Scale Analysis (on-the-fly or deferred)
To analyze a large number of websites or financial data and pull out parametric data, what are the optimal strategies? I'm classifying the following strategies as either "on-the-fly" or "deferred". Which is best? On-the-fly: Process data on-the-fly and store parametric data into a database Deferred: Store all the sou...
[ "I'd use celery either on a single or on multiple machines, with the \"on-the-fly\" strategy. You can have an aggregation Task, that fetches data, and a process Task that analyzes them and stores them in a db. This is a highly scalable approach, and you can tune it according to your computing power.\nThe \"on-the-f...
[ 2, 2 ]
[]
[]
[ "large_data", "python", "sql" ]
stackoverflow_0007607348_large_data_python_sql.txt
Q: Secure authentication system in python? I am making a web application in python and I would like to have a secure login system. I have done login systems many times before by having the user login and then a random string is saved in a cookie which is also saved next to that user in a database which worked fine bu...
Secure authentication system in python?
I am making a web application in python and I would like to have a secure login system. I have done login systems many times before by having the user login and then a random string is saved in a cookie which is also saved next to that user in a database which worked fine but it was not very secure. I believe understan...
[ "This answer mainly addresses password hashing, and not your other subquestions. For those, my main advice would be don't reinvent the wheel: use existing frameworks that work well with GAE. It offers builtin deployments of Django, but also has a builtin install of WebOb, so various WebOb-based frameworks (Pyramid,...
[ 5, 1 ]
[]
[]
[ "authentication", "python", "security", "web_applications" ]
stackoverflow_0007627752_authentication_python_security_web_applications.txt
Q: Python: Clicking a button with urllib or urllib2 I want to click a button with python, the info for the form is automatically filled by the webpage. the HTML code for sending a request to the button is: INPUT type="submit" value="Place a Bid"> How would I go about doing this? Is it possible to click the button wi...
Python: Clicking a button with urllib or urllib2
I want to click a button with python, the info for the form is automatically filled by the webpage. the HTML code for sending a request to the button is: INPUT type="submit" value="Place a Bid"> How would I go about doing this? Is it possible to click the button with just urllib or urllib2? Or will I need to use somet...
[ "Use the form target and send any input as post data like this:\n<form target=\"http://mysite.com/blah.php\" method=\"GET\">\n ......\n ......\n ......\n <input type=\"text\" name=\"in1\" value=\"abc\">\n <INPUT type=\"submit\" value=\"Place a Bid\">\n</form>\n\nPython:\n# parse the page HTML with th...
[ 11, 2, 1 ]
[]
[]
[ "mechanize", "python", "twill", "urllib", "urllib2" ]
stackoverflow_0007630795_mechanize_python_twill_urllib_urllib2.txt
Q: Multiple instances of JQueryUI Autocomplete on same Pyramid page I have a working JQueryUI Autocomplete input widget working nicely with my Pyramid backend. The autocomplete posts its request.params['term'] to the same URL as the page its on, and Pyramid uses request_param='term' as a route predicate to send the ...
Multiple instances of JQueryUI Autocomplete on same Pyramid page
I have a working JQueryUI Autocomplete input widget working nicely with my Pyramid backend. The autocomplete posts its request.params['term'] to the same URL as the page its on, and Pyramid uses request_param='term' as a route predicate to send the term value to my database query view-callable. The problem I have now ...
[ "You need to set your autocomplete for each widget explicitly and indicate a specific url and/or a custom piece of data in the post.\nThis is a clip from the Remote JSONP datasource example on the JQueryUI documentation:\n$( \"#a-particular-auto-complete-widget\" ).autocomplete({\n source: function( request, res...
[ 3 ]
[]
[]
[ "jquery_autocomplete", "pyramid", "python" ]
stackoverflow_0007630263_jquery_autocomplete_pyramid_python.txt
Q: Default server in multiple server configuration of distutils in ~/.pypirc I want to have multiple PyPI servers in my ~/.pypirc file so I can easily publish to different servers, depending on the project. My use-case is this, I have some internal projects that I want to publish to an internal PyPI server (https://p...
Default server in multiple server configuration of distutils in ~/.pypirc
I want to have multiple PyPI servers in my ~/.pypirc file so I can easily publish to different servers, depending on the project. My use-case is this, I have some internal projects that I want to publish to an internal PyPI server (https://pypi.internal), and I have some public projects that I want to publish to the pu...
[ "It's strange that there isn't built-in support for setting a default, but here are two options which may help you work around it.\nOption 1: Probably the simplest solution would be to leave your ~/.pypirc script intact and create shell aliases for your internal and public uploads. This may give you more control ov...
[ 15, 0 ]
[]
[]
[ "distutils", "pypi", "python" ]
stackoverflow_0005467463_distutils_pypi_python.txt
Q: When embedding CPython in Java, why does this hang? I'm embedding CPython into a JVM using Jepp, but when I run import numpy; numpy.finfo(float) the process hangs. gdb says something's blocking a semaphore/lock acquisition, and the stack trace suggests something floating point-related: $ LD_PRELOAD=/usr/lib/libp...
When embedding CPython in Java, why does this hang?
I'm embedding CPython into a JVM using Jepp, but when I run import numpy; numpy.finfo(float) the process hangs. gdb says something's blocking a semaphore/lock acquisition, and the stack trace suggests something floating point-related: $ LD_PRELOAD=/usr/lib/libpython2.6.so gdb --args java -jar jepp.jar -i /tmp/go.py G...
[ "See this post by John Wright who ran into the same problem: http://mail.scipy.org/pipermail/numpy-discussion/2009-July/044046.html\nBasically, numpy is using the Python C api in a way that's incompatible with Jep. Jep uses sub interpreters to allow multiple interpreter environments. It could be possible to change ...
[ 1, 0, 0 ]
[]
[]
[ "cpython", "java", "jvm", "numpy", "python" ]
stackoverflow_0007592565_cpython_java_jvm_numpy_python.txt
Q: Extract partial duplicates from a list of lists; return single match with record of origin of each duplicate; Python I have a list in the following format: L = ['apples oranges x', 'bananas apples y', 'apples oranges z'] For every item in L, if item.split()[0:2] matches another item.split()[0:2] (i.e...
Extract partial duplicates from a list of lists; return single match with record of origin of each duplicate; Python
I have a list in the following format: L = ['apples oranges x', 'bananas apples y', 'apples oranges z'] For every item in L, if item.split()[0:2] matches another item.split()[0:2] (i.e., 'apples oranges' matches 'apples oranges') then I need to output a single item.split()[0:2] followed by the tags record...
[ "d = collections.defaultdict(list)\n\nfor line in L:\n name, value = line.rsplit(' ',1)\n d[name].append(value)\n\nthen you'll have a dict like that:\n{'bananas apples ': ['y'], 'apples oranges ': ['x', 'z']}\n\nSo you only need to format the keys and values:\n[key + ' '.join(values) for key, values in d.item...
[ 4 ]
[]
[]
[ "python", "text_processing" ]
stackoverflow_0007631062_python_text_processing.txt
Q: How to get the 'reactor' when the twisted application is started by twistd? My application uses the 'twisted.web.client.Agent' to get web content. But the Agent class requires a 'reactor' instance to initiate. If I start my application using the 'twistd', there will be no 'reactor.run()' at all. So how can I get t...
How to get the 'reactor' when the twisted application is started by twistd?
My application uses the 'twisted.web.client.Agent' to get web content. But the Agent class requires a 'reactor' instance to initiate. If I start my application using the 'twistd', there will be no 'reactor.run()' at all. So how can I get the 'reactor' instance?
[ "I wish there were a better answer, but the way to get the current, active reactor in a Twisted application is:\nfrom twisted.internet import reactor\n\nThe important thing is to not do this all over the place, but once near the \"top\" of your application code, so that you can easily replace the reactor for testin...
[ 12 ]
[]
[]
[ "python", "service", "twisted" ]
stackoverflow_0007631353_python_service_twisted.txt
Q: Wrapping std::vector of boost::shared_ptr in SWIG for Python EDIT: Solved, my mistake; explained in my answer. I have this: std::vector < boost::shared_ptr < Entity > > entities; and I try to expose it through SWIG like this: %include "boost_shared_ptr.i" %include "std_vector.i" %shared_ptr(Entity) %include <Ent...
Wrapping std::vector of boost::shared_ptr in SWIG for Python
EDIT: Solved, my mistake; explained in my answer. I have this: std::vector < boost::shared_ptr < Entity > > entities; and I try to expose it through SWIG like this: %include "boost_shared_ptr.i" %include "std_vector.i" %shared_ptr(Entity) %include <Entity.h> namespace std { %template(EntityVector) vector<boost::...
[ "I had some difficulty getting a Python sequence of pointer objects to automatically convert into a std::vector of pointer objects. I am currently (stuck) using Swig 1.3; YMMV if you're using Swig 2. The trick was to instantiate in the Swig interface file (with %template) not just the vector, and not just the obj...
[ 5, 0, 0 ]
[]
[]
[ "c++", "python", "shared_ptr", "swig", "vector" ]
stackoverflow_0005535996_c++_python_shared_ptr_swig_vector.txt
Q: Python: How to get the created date and time of a folder? Possible Duplicate: How to get file creation & modification date/times in Python? I would like to get the created date and time of a folder. Are there anyways to do that in python? Thank you A: You might use os.stat to retrieve this information. os.stat...
Python: How to get the created date and time of a folder?
Possible Duplicate: How to get file creation & modification date/times in Python? I would like to get the created date and time of a folder. Are there anyways to do that in python? Thank you
[ "You might use os.stat to retrieve this information.\nos.stat(path).st_mtime // time of most recent content modification,\nos.stat(path).st_ctime // platform dependent; time of most recent metadata change on Unix, or the time of creation on Windows)\n\n" ]
[ 21 ]
[]
[]
[ "directory", "python" ]
stackoverflow_0007631843_directory_python.txt
Q: Python Dictionary DataStructure which method d[] or d.get()? While Using Python Dictionary DataStructure (which contains key-value pair) if i want to retrieve some value from my Dictionary i have two options d[''] and g.get('key') so i am confused now which is better and Why ?? I understand both some way but when ...
Python Dictionary DataStructure which method d[] or d.get()?
While Using Python Dictionary DataStructure (which contains key-value pair) if i want to retrieve some value from my Dictionary i have two options d[''] and g.get('key') so i am confused now which is better and Why ?? I understand both some way but when it comes to memory consumption and evaluation in memory which one...
[ "From the Python Library Docs\n\nd[key]\n Return the item of d with key key. Raises a KeyError if key is not in the map. \nIf a subclass of dict defines a method __missing__(), if the key key is not present, the d[key] operation calls that method with the key key as argument. The d[key] operation then returns or...
[ 44, 5, 3, 0, 0 ]
[]
[]
[ "data_structures", "python" ]
stackoverflow_0007631929_data_structures_python.txt
Q: defining a method inside a class in python I'm taking my first steps in python programming, I have a class named node which holds a list of nodes (I think that legal) named sons. I tried to create a function that returns the length of the list but it fails. Here is my code: class node: name="temp" ID=-1 ...
defining a method inside a class in python
I'm taking my first steps in python programming, I have a class named node which holds a list of nodes (I think that legal) named sons. I tried to create a function that returns the length of the list but it fails. Here is my code: class node: name="temp" ID=-1 abstract="a short description" text="the...
[ "class node:\n name=\"temp\"\n ID=-1\n abstract=\"a short description\"\n text=\"the full description\"\n sons=[]\n def sLen(self): # here\n print (\"hello\")\n return len(self.sons)\n\nn = node()\nn.sons = [1, 2, 3]\nprint n.sLen()\n\n", "The first argument of a class method is al...
[ 3, 1, 0 ]
[]
[]
[ "list", "methods", "python" ]
stackoverflow_0007631991_list_methods_python.txt
Q: Django and tests in docfiles I'm having a small problem with my test suite with Django. I'm working on a Python package that can run in both Django and Plone (http://pypi.python.org/pypi/jquery.pyproxy). All the tests are written as doctests, either in the Python code or in separate docfiles (for example the READ...
Django and tests in docfiles
I'm having a small problem with my test suite with Django. I'm working on a Python package that can run in both Django and Plone (http://pypi.python.org/pypi/jquery.pyproxy). All the tests are written as doctests, either in the Python code or in separate docfiles (for example the README.txt). I can have those tests ru...
[ "I finally solved the problem with the suite() method:\nimport os\nimport doctest\nfrom django.utils import unittest\n\nfrom jquery.pyproxy import base, utils\n\nOPTIONFLAGS = (doctest.ELLIPSIS |\n doctest.NORMALIZE_WHITESPACE)\n\ntestmods = {'base': base,\n 'utils': utils}\ntestfiles = {'r...
[ 1 ]
[]
[]
[ "django", "doctest", "python", "testing" ]
stackoverflow_0007594246_django_doctest_python_testing.txt
Q: Python Audio Transfer Through Lasers I'm currently working on a project that has been relatively easy, up until now. The underlying project is to transmit data/messages over lasers using audio transformation. In a nutshell the process is currently like this The user enters a message Message is turned into binary ...
Python Audio Transfer Through Lasers
I'm currently working on a project that has been relatively easy, up until now. The underlying project is to transmit data/messages over lasers using audio transformation. In a nutshell the process is currently like this The user enters a message Message is turned into binary For each 1 and 0 in the binary message, it...
[ "This sounds like a hardware problem. I'm pretty sure it is a job for FSK. Most modern FSK-type systems use PLLs (Phase-Locking Loop chips) for the actual detection. Frequency-to-Voltage or Frequency-to-current circuits are also usable. \nI've seen practical circuits in dozens of hobbyist books and in data sheets a...
[ 2, 1, 1, 0 ]
[]
[]
[ "audio", "frequency", "python", "signal_processing" ]
stackoverflow_0007606111_audio_frequency_python_signal_processing.txt
Q: Stripping characters from a Python string I have a string: v = "1 - 5 of 5" I would like only the part after 'of' (5 in the above) and strip everything before 'of', including 'of'? The problem is that the string is not fixed as in it could be '1-100 of 100', so I can't specify to strip everything off after the 10...
Stripping characters from a Python string
I have a string: v = "1 - 5 of 5" I would like only the part after 'of' (5 in the above) and strip everything before 'of', including 'of'? The problem is that the string is not fixed as in it could be '1-100 of 100', so I can't specify to strip everything off after the 10 or so characters. I need to search for 'of' th...
[ "Using the partition method is most readable for these cases.\nstring = \"1 - 5 of 5\"\nfirst_part, middle, last_part = string.partition('of')\n\nresult = last_part.strip()\n\n", "str.partition() was built for exactly this kind of problem: \nIn [2]: v = \"1 - 5 of 5\"\n\nIn [3]: v.partition('of')\nOut[3]: ('1 - 5...
[ 7, 4, 0 ]
[ "p = find(v, \"of\")\n\ngives you the position of \"of\" in v\n" ]
[ -1 ]
[ "python", "string" ]
stackoverflow_0007633197_python_string.txt
Q: Extracting words from a string, removing punctuation and returning a list with separated words I was wondering how to implement a function get_words() that returns the words in a string in a list, stripping away the punctuation. How I would like to have it implemented is replace non string.ascii_letters with '' an...
Extracting words from a string, removing punctuation and returning a list with separated words
I was wondering how to implement a function get_words() that returns the words in a string in a list, stripping away the punctuation. How I would like to have it implemented is replace non string.ascii_letters with '' and return a .split(). def get_words(text): '''The function should take one argument which is a s...
[ "This has nothing to do with splitting and punctuation; you just care about the letters (and numbers), and just want a regular expression:\nimport re\ndef getWords(text):\n return re.compile('\\w+').findall(text)\n\nDemo:\n>>> re.compile('\\w+').findall('Hello world, my name is...James the 2nd!')\n['Hello', 'wor...
[ 39, 11, 2 ]
[]
[]
[ "list", "python", "string" ]
stackoverflow_0007633274_list_python_string.txt
Q: django modelform showing an existing instance I have the following model: ynChoice = ((None, 'Acknowledgement not required'), (True, 'Acknowledgement and consent required'), (False, 'Acknowledgement required but consent not required')) class AbstractForm(models.Model): """base class fo...
django modelform showing an existing instance
I have the following model: ynChoice = ((None, 'Acknowledgement not required'), (True, 'Acknowledgement and consent required'), (False, 'Acknowledgement required but consent not required')) class AbstractForm(models.Model): """base class for the below 2 classes""" #require users to say ...
[ "ok i've looked at the forms.fields and\nturns out that when rendering to html, turns out that None is just treated as '', and empty_value is not taken into consideration here. I'm not sure why @Ignacio Vazquez-Abrams dude took away his answer, so if you can please put it back up again, i'll accept it.\n" ]
[ 0 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0007624997_django_django_forms_python.txt
Q: bpython-like autocomplete and parameter description in Emacs Python Mode? I've been using bpython for a while now for all of my Python interpreting needs. It's delightful, particularly when you're using unfamiliar new libraries, or libraries with a multitude of functions. In any case, it's nice to have a bpython...
bpython-like autocomplete and parameter description in Emacs Python Mode?
I've been using bpython for a while now for all of my Python interpreting needs. It's delightful, particularly when you're using unfamiliar new libraries, or libraries with a multitude of functions. In any case, it's nice to have a bpython interpreter running alongside what I'm doing, but it'd be even better if I had...
[ "You're not completely crazy.\npython-mode can integrate with eldoc-mode to display the arg spec of the function you're calling at point. Just do M-x eldoc-mode while you're in a python file to turn it on and it should start working. It talks to an inferior python buffer to inspect the functions directly, so it sho...
[ 10 ]
[]
[]
[ "bpython", "emacs", "python" ]
stackoverflow_0007602169_bpython_emacs_python.txt
Q: Need python Regex for handling sub-string I want to check where the string (Product Name) contains the word beta, Since I am not so good in regex writing : eg. "Crome beta" "Crome_beta" "Crome beta2" "Crome_betaversion" "Crome 3beta" "CromeBerta2.3" "Beta Crome 4" So that I can raise error that this is not vali...
Need python Regex for handling sub-string
I want to check where the string (Product Name) contains the word beta, Since I am not so good in regex writing : eg. "Crome beta" "Crome_beta" "Crome beta2" "Crome_betaversion" "Crome 3beta" "CromeBerta2.3" "Beta Crome 4" So that I can raise error that this is not valid product name , its a product version. i wrote...
[ "Try ((?<![a-z])beta|cromebeta). (the word beta not preceded by a letter or the full word cromebeta)\nI'll add a quote from http://docs.python.org/library/re.html to explain the first part.\n\n(?<!...) Matches if the current position in the string is not preceded\n by a match for .... This is called a negative loo...
[ 2, 0, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007632986_python_regex.txt
Q: Insert string at the beginning of each line How can I insert a string at the beginning of each line in a text file, I have the following code: f = open('./ampo.txt', 'r+') with open('./ampo.txt') as infile: for line in infile: f.insert(0, 'EDF ') f.close I get the following error: 'file' object has no...
Insert string at the beginning of each line
How can I insert a string at the beginning of each line in a text file, I have the following code: f = open('./ampo.txt', 'r+') with open('./ampo.txt') as infile: for line in infile: f.insert(0, 'EDF ') f.close I get the following error: 'file' object has no attribute 'insert'
[ "Python comes with batteries included:\nimport fileinput\nimport sys\n\nfor line in fileinput.input(['./ampo.txt'], inplace=True):\n sys.stdout.write('EDF {l}'.format(l=line))\n\nUnlike the solutions already posted, this also preserves file permissions.\n", "You can't modify a file inplace like that. Files do ...
[ 28, 8, 0, 0 ]
[ "f = open('./ampo.txt', 'r')\nlines = map(lambda l : 'EDF ' + l, f.readlines())\nf.close()\nf = open('./ampo.txt', 'w')\nmap(lambda l : f.write(l), lines)\nf.close()\n\n" ]
[ -1 ]
[ "file", "python", "string" ]
stackoverflow_0007633485_file_python_string.txt
Q: Can Gstreamer be used server-side to stream audio to multiple clients on demand? I'm working on an audio mixing program (DAW) web app, and considering using Python and Python Gstreamer for the backend. I understand that I can contain the audio tracks of a single music project in a gst.Pipeline bin, but playback a...
Can Gstreamer be used server-side to stream audio to multiple clients on demand?
I'm working on an audio mixing program (DAW) web app, and considering using Python and Python Gstreamer for the backend. I understand that I can contain the audio tracks of a single music project in a gst.Pipeline bin, but playback also appears to be controlled by this Pipeline. Is it possible to create several "views...
[ "You might want to look at Flumotion (www.flumotion.org). It is a python based streaming server using GStreamer, you might be able to get implementation ideas from that in terms of how you do your application. It relies heavily on the python library Twisted for its network handling.\n" ]
[ 1 ]
[]
[]
[ "audio", "gstreamer", "python", "stream" ]
stackoverflow_0007630548_audio_gstreamer_python_stream.txt
Q: How to get status of Gearman Jobs by their uniq id? I need to get status of Gearman jobs by these uniq id, not by open handlers, as desribed every place I seen Is it possible? using in python-gearman v. 2... Thanks for assistance! A: Had to dig quite a bit to solve this issue, as it's not exposed in a friendly m...
How to get status of Gearman Jobs by their uniq id?
I need to get status of Gearman jobs by these uniq id, not by open handlers, as desribed every place I seen Is it possible? using in python-gearman v. 2... Thanks for assistance!
[ "Had to dig quite a bit to solve this issue, as it's not exposed in a friendly manner in the python-gearman-API. You can however solve it by creating appropriate instances of the GearmanJob and GearmanJobRequest yourself.\nHere's a small example of how you can do this:\nimport gearman\n\nclient = gearman.GearmanCli...
[ 6 ]
[]
[]
[ "gearman", "python", "python_gearman" ]
stackoverflow_0006983854_gearman_python_python_gearman.txt
Q: Python decoding Unicode is not supported I am having a problem with my encoding in Python. I have tried different methods but I can't seem to find the best way to encode my output to UTF-8. This is what I am trying to do: result = unicode(google.searchGoogle(param), "utf-8").encode("utf-8") searchGoogle returns t...
Python decoding Unicode is not supported
I am having a problem with my encoding in Python. I have tried different methods but I can't seem to find the best way to encode my output to UTF-8. This is what I am trying to do: result = unicode(google.searchGoogle(param), "utf-8").encode("utf-8") searchGoogle returns the first Google result for param. This is the ...
[ "Looks like google.searchGoogle(param) already returns unicode:\n>>> unicode(u'foo', 'utf-8')\n\nTraceback (most recent call last):\n File \"<pyshell#1>\", line 1, in <module>\n unicode(u'foo', 'utf-8')\nTypeError: decoding Unicode is not supported\n\nSo what you want is:\nresult = google.searchGoogle(param).en...
[ 102 ]
[]
[]
[ "character_encoding", "encoding", "python", "utf_8" ]
stackoverflow_0007634715_character_encoding_encoding_python_utf_8.txt
Q: Send Key Event to a Child Window I'm developing an application in python which sends keyboard events to another external application. I use the pywin32 package to set the external application and send the desired key: import win32com.client as w32 shell = w32.Dispatch("WScript.Shell") shell.AppActivate(desired_ap...
Send Key Event to a Child Window
I'm developing an application in python which sends keyboard events to another external application. I use the pywin32 package to set the external application and send the desired key: import win32com.client as w32 shell = w32.Dispatch("WScript.Shell") shell.AppActivate(desired_application) shell.SendKeys("{ENTER}") ...
[ "I manage to choose the specific handle with EnumChildWindow (to enumerate all the handles of the application) and send the message with PostMessage.\n import win32api\n win32api.PostMessage(handler, win32con.WM_KEYDOWN, win32con.VK_RETURN, 0)\n\n" ]
[ 0 ]
[]
[]
[ "childwindow", "keyboard", "python", "pywin32" ]
stackoverflow_0007596502_childwindow_keyboard_python_pywin32.txt
Q: python regular expression exclude from match string I have 3 strings a ="keep the your pass ABCDEFG other text" b ="your pass: TESTVALUE other text" c ="no pass required other text" I want to get capital values after pass, like this re.match(r'.*\spass:?\s([a-zA-Z]+).*',a,re.I).group(1) re.match(r'.*\spass:?\s([a...
python regular expression exclude from match string
I have 3 strings a ="keep the your pass ABCDEFG other text" b ="your pass: TESTVALUE other text" c ="no pass required other text" I want to get capital values after pass, like this re.match(r'.*\spass:?\s([a-zA-Z]+).*',a,re.I).group(1) re.match(r'.*\spass:?\s([a-zA-Z]+).*',b,re.I).group(1) but I want to exclude "no p...
[ "import re\n\nfor x in (\"keep the your pass ABCDEFG other text\",\n \"your pass: TESTVALUE other text\",\n \"no pass required other text\"):\n print re.search('no\\s+pass|pass:?\\s+([A-Z]+)',x).group(1)\nA-Z]+)'\n\nresult\nABCDEFG\nTESTVALUE\nNone\n\n", "It's not OK to use match here. It's p...
[ 3, 1, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007634341_python_regex.txt
Q: Get address out of a paragraph with regex Alright, this one's a bit of a pain. I'm doing some scraping with Python, trying to get an address out of a few lines of poorly tagged HTML. Here's a sample of the format: 256-555-5555<br/> 1234 Fake Ave S<br/> Gotham (Lower Ward)<br/> I'd like to retrieve only 1234 Fak...
Get address out of a paragraph with regex
Alright, this one's a bit of a pain. I'm doing some scraping with Python, trying to get an address out of a few lines of poorly tagged HTML. Here's a sample of the format: 256-555-5555<br/> 1234 Fake Ave S<br/> Gotham (Lower Ward)<br/> I'd like to retrieve only 1234 Fake Ave S, Gotham. Any ideas? I've been doing r...
[ "It is possible that in your case it is easier to focus on what you don't want:\n\nhtml tags (<br>)\nphone numbers\neverything in parenthesis\n\nEach of which can be matched easily with simple regular expressions, making it easy to construct one to match the rest (presumably - the address)\n", "This attempts to i...
[ 1, 1, 0 ]
[]
[]
[ "python", "regex", "scrapy", "street_address" ]
stackoverflow_0007632398_python_regex_scrapy_street_address.txt
Q: Web development with ESN Planet, how does it work? I'm starting a new job soon, in web-app development. While I'm experienced with programming, my background is primarily in game development and desktop/server applications. I have very little experience from modern web app development. Anyway... Our primary develo...
Web development with ESN Planet, how does it work?
I'm starting a new job soon, in web-app development. While I'm experienced with programming, my background is primarily in game development and desktop/server applications. I have very little experience from modern web app development. Anyway... Our primary development tool is going to be something called ESN Planet, w...
[ "I saw a talk by the boss of the company that developed this stuff, at the Europython conference this year. It was ostensibly about the custom IDE that they created to develop in it, but also touched on the Planet system itself. It seems like a pretty run-of-the-mill MVC framework, as far as I can tell.\nAs far as ...
[ 0, 0 ]
[]
[]
[ "javascript", "python", "web_applications" ]
stackoverflow_0003602765_javascript_python_web_applications.txt
Q: How to get RSS date using Universal Feed Parser I have a RSS feed which have the data in the following format: <item> <title><![CDATA[à¨ç·à«çµàµÍÃì-JETSETER-»Å×éÁ-½Ñ¹à»ç¹¨ÃÔ§-¤Í¹àÊÔÃìµãË­è¤ÃÑé§áá㹪ÕÇÔµ-REDioactive-Presents-Jetseter-Music-Inspiration-Concert ]]></title> <link>http://www.thaiticketmajor....
How to get RSS date using Universal Feed Parser
I have a RSS feed which have the data in the following format: <item> <title><![CDATA[à¨ç·à«çµàµÍÃì-JETSETER-»Å×éÁ-½Ñ¹à»ç¹¨ÃÔ§-¤Í¹àÊÔÃìµãË­è¤ÃÑé§áá㹪ÕÇÔµ-REDioactive-Presents-Jetseter-Music-Inspiration-Concert ]]></title> <link>http://www.thaiticketmajor.com/»ÃЪÒÊÑÁ¾Ñ¹¸ìÅÙ¡¤éÒ/à¨ç·à«çµàµÍÃì-JETSETER-»Å×éÁ-...
[ "It's in the format of a time.struct_time class.\nYou can convert it to a datetime object, or just access the properties, however you desire.\n" ]
[ 2 ]
[]
[]
[ "python", "rss", "xml" ]
stackoverflow_0007635315_python_rss_xml.txt
Q: SQLAlchemy -Comparison between existing column value and potential update value I have a SQLAlchemy model which I'm updating with data from an XML file. I want to be notified where the new value differs from the old one. I tried the simple: if ModelInstance.Field <> NewValue: print "Field has changed from", Mo...
SQLAlchemy -Comparison between existing column value and potential update value
I have a SQLAlchemy model which I'm updating with data from an XML file. I want to be notified where the new value differs from the old one. I tried the simple: if ModelInstance.Field <> NewValue: print "Field has changed from", ModelInstance.Field, "to", NewValue But this doesn't work in many cases because the ty...
[ "You probably want an attribute set event. \n" ]
[ 0 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0007633622_python_sqlalchemy.txt
Q: Django query not working Here's the thing. I have a model called User and an attribute counter that counts the number of page access. So, if a user already exists, I have to query up the db and for that user only to increase in counter. Otherwise, create a new user. I have an annoying error in the get method. How ...
Django query not working
Here's the thing. I have a model called User and an attribute counter that counts the number of page access. So, if a user already exists, I have to query up the db and for that user only to increase in counter. Otherwise, create a new user. I have an annoying error in the get method. How can I surpass it? if request.m...
[ "Django has amazing documentation on their QuerySet API. https://docs.djangoproject.com/en/dev/ref/models/querysets/\nget only returns exactly 1 queryset. If no queryset is found, or more then 1 queryset is returned, an error is raised.\nTo catch this particular error you have to specify except User.MultipleObject...
[ 3, 0 ]
[]
[]
[ "django", "models", "python", "views" ]
stackoverflow_0007635339_django_models_python_views.txt
Q: Django OneToOne Field Now I'm working one url mapping. Let's say I have three classes, company, user, and store, and my goal is that their urls will be in the same hierarchy. Since they are the same hierarchy in urls, I have to create a class url_mapping to ensure there is no duplicate name. Let's me give a more c...
Django OneToOne Field
Now I'm working one url mapping. Let's say I have three classes, company, user, and store, and my goal is that their urls will be in the same hierarchy. Since they are the same hierarchy in urls, I have to create a class url_mapping to ensure there is no duplicate name. Let's me give a more concrete problem I have. Cl...
[ "I understand your question as \"I have a URL, and I want to go to the corresponding Store, company or the User\". \nYou can do that using\nURL_mapping.objects.get(url).user\nURL_mapping.objects.get(url).store\nURL_mapping.objects.get(url).company\n\nClearly 2 of these will give you an error and you wouldn't know w...
[ 3, 1 ]
[]
[]
[ "django", "python", "url" ]
stackoverflow_0007630228_django_python_url.txt
Q: python ubuntu virtualenv -> error Newbie here, be kind. The other day I am all: sudo apt-get install python-virtualenv And then I am (following instructions): virtualenv env And Ubuntu 10.10 is like: Traceback (most recent call last): File "/usr/local/bin/virtualenv", line 5, in <module> from pkg_resources...
python ubuntu virtualenv -> error
Newbie here, be kind. The other day I am all: sudo apt-get install python-virtualenv And then I am (following instructions): virtualenv env And Ubuntu 10.10 is like: Traceback (most recent call last): File "/usr/local/bin/virtualenv", line 5, in <module> from pkg_resources import load_entry_point File "/usr/l...
[ "Had the same issue after upgrading to Ubuntu 11.04..\nTurns out it was only because apt installed python-virtualenv 1.4, which was too old.\nI removed the deb package and used pip install instead and it worked fine.\npip install virtualenv\n\n", "The python-virtualenv package should have installed virtualenv in ...
[ 7, 6 ]
[]
[]
[ "python", "ubuntu", "virtualenv" ]
stackoverflow_0005071385_python_ubuntu_virtualenv.txt
Q: nditer: possible to manually handle dimensions with different lengths? Using numpy's nditer, is it possible to manually handle dimensions with different lengths? For example, lets say I had an array A[5, 100] and I wanted to sample every 10 along the second axis so I would end up with an array B[5,10]. Is it possi...
nditer: possible to manually handle dimensions with different lengths?
Using numpy's nditer, is it possible to manually handle dimensions with different lengths? For example, lets say I had an array A[5, 100] and I wanted to sample every 10 along the second axis so I would end up with an array B[5,10]. Is it possible to do this with nditer, handling the iteration over the second axis manu...
[ "a = numpy.arange(500.0).reshape((5,100))\nnumpy.lib.stride_tricks.as_strided(a, (5,10), (6400,64))\n\n" ]
[ 0 ]
[]
[]
[ "cython", "numpy", "python" ]
stackoverflow_0007612672_cython_numpy_python.txt
Q: Using Google OAuth on localhost I started to use OAuth with Python and Django. I need it for Google APIs. I working on localhost, so I can't register a domain for url-callback. I've read about that Google OAuth could be used with anonymous domain. Can't find, how and where I can do that? Edit: I have this view: de...
Using Google OAuth on localhost
I started to use OAuth with Python and Django. I need it for Google APIs. I working on localhost, so I can't register a domain for url-callback. I've read about that Google OAuth could be used with anonymous domain. Can't find, how and where I can do that? Edit: I have this view: def authentication(request): CONSUM...
[ "Just to be clear, you can use the web application flow with localhost while developing on either OAuth 1.0 or OAuth 2.0. OAuth 2.0 should be preferred as it's the mechanism we are focussed on. The user experience for OAuth 2.0 is going to be substantially better.\nThere's nothing stopping you from using localhost ...
[ 12, 2, 1 ]
[]
[]
[ "google_api", "google_api_client", "oauth", "python" ]
stackoverflow_0007626299_google_api_google_api_client_oauth_python.txt
Q: Panel arrangement in wxpython Background As a newbie to python as well as to GUI Programming, I would like to create a wxpython based GUI application. This GUI will run a series of tests The tests written in text files will be running and it's steps should be displayed in the Window. For selecting a particular te...
Panel arrangement in wxpython
Background As a newbie to python as well as to GUI Programming, I would like to create a wxpython based GUI application. This GUI will run a series of tests The tests written in text files will be running and it's steps should be displayed in the Window. For selecting a particular test,click the checkbox (CheckListCtr...
[ "I recommend to you the use of wxglade to design your GUIs. It is fast and effective and after you have some experience you can do most of the things you can do manually. \nwxglade does not have wx.lib widgets suchs as CheckListCtrlMixin or ListCtrlAutoWidthMixin that you are using or combinations such as your cla...
[ 2, 1 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0007633997_python_wxpython.txt
Q: python: adding to a dict gives error playlist = {} playlist.update(position, title) here position and title are two strings. I am getting the following error: TypeError: update expected at most 1 arguments, got 2 could some please help? thanks A: You can only update a dict with another dictionnary (you could ...
python: adding to a dict gives error
playlist = {} playlist.update(position, title) here position and title are two strings. I am getting the following error: TypeError: update expected at most 1 arguments, got 2 could some please help? thanks
[ "You can only update a dict with another dictionnary (you could also give it an iterable of tuples (key, value) :\nplaylist = {item1 : value1}\nplaylist.update({position : title})\nprint playlist\n\n>>> {item1 : value1, position : title}\n\nplaylist.update([(item2, value2),])\nprint playlist\n>>> {item1 : value1, p...
[ 6, 5, 3, 3, 2, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0007634688_dictionary_python.txt
Q: How can I return control from my python script to the calling bash script? I am using a bash script to loop through a configuration file and, based on that, call a python script via ssh. Unfortunately once the Python script does its job and I call quit the bash script also gets closed, therefore the calling bash s...
How can I return control from my python script to the calling bash script?
I am using a bash script to loop through a configuration file and, based on that, call a python script via ssh. Unfortunately once the Python script does its job and I call quit the bash script also gets closed, therefore the calling bash script's loop is terminated prematurely. Here's my Bash Script target | grep 'sr...
[ "Nothing that the remote Python script does should be able to kill your do loop unless you have done a set -e in the local bash first to make it sensitive to command failure — in which case it would die only if, as @EOL says, your remote script is hitting an exception and returning a nonzero/error value to SSH whic...
[ 1, 0 ]
[ "You should be able to simply return from the main function.\n" ]
[ -1 ]
[ "bash", "python" ]
stackoverflow_0007635725_bash_python.txt
Q: BaseHTTPServer thread does not work My code is simple. Using BaseHTTPServer and ThreadInMix I want to run a python script (Script1.py) for every request made simultaneously. My Code- from subprocess import PIPE, Popen from SocketServer import ThreadingMixIn from BaseHTTPServer import HTTPServer, BaseHTTPRequestHa...
BaseHTTPServer thread does not work
My code is simple. Using BaseHTTPServer and ThreadInMix I want to run a python script (Script1.py) for every request made simultaneously. My Code- from subprocess import PIPE, Popen from SocketServer import ThreadingMixIn from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler import time def simple_script(self...
[ "Works just fine for me:\nStarting server, use to stop\nlocalhost.localdomain - - [03/Oct/2011 16:25:55] \"GET / HTTP/1.1\" 200 -\nsimple_script\nlocalhost.localdomain - - [03/Oct/2011 16:25:55] \"GET / HTTP/1.1\" 200 -\nsimple_script\nMon Oct 3 16:25:56 2011\nMon Oct 3 16:25:57 2011\nMon Oct 3 16:25:58 2011\nM...
[ 1 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0007629502_multithreading_python.txt
Q: ssh gateway in python - colors available? I am using python bindings for libssh2 to connect to SSH2 server programmatically. The received output should be forwarded to a remote server and displayed there. The code below works correctly, but it displays the result in monochrome. How can I display the colors or at ...
ssh gateway in python - colors available?
I am using python bindings for libssh2 to connect to SSH2 server programmatically. The received output should be forwarded to a remote server and displayed there. The code below works correctly, but it displays the result in monochrome. How can I display the colors or at least get the VT100 terminal control escape seq...
[ "You can look into the paramiko python library. A good blog post going over details, with links to various python info is here. I'm not sure how paramiko would handle the control codes, but in theory, it will at least allow you to see them in its return data. \nIf you check the section of the docs dealing with invo...
[ 2 ]
[]
[]
[ "libssh", "python", "ssh" ]
stackoverflow_0007636109_libssh_python_ssh.txt
Q: pyQt v4 rowsMoved Signal Im pretty new to Qt and have been trying to create a UI where the user will have rows of information and each row represents a stage in a pipeline. Iam trying to achieve that a user can drag and drop the different rows and that will change the order in which the steps occur. I have achieve...
pyQt v4 rowsMoved Signal
Im pretty new to Qt and have been trying to create a UI where the user will have rows of information and each row represents a stage in a pipeline. Iam trying to achieve that a user can drag and drop the different rows and that will change the order in which the steps occur. I have achieved the drag and drop of the row...
[ "What you want is to subclass the QTableView, and overload the rowMoved() SLOT\nclass MyTableView(QtGui.QTableView):\n def __init__(self, parent=None):\n super(MyTableView, self).__init__(parent)\n\n self.rowsMoved.connect(self.movedRowsSlot) \n\n def rowMoved(self, row, oldIndex, newIndex):\n...
[ 0, 0 ]
[]
[]
[ "drag_and_drop", "pyqt", "python", "signals" ]
stackoverflow_0007628465_drag_and_drop_pyqt_python_signals.txt
Q: Python: Can I have a string as a key and a function as value in a dictionary? In other words, is this giving me errors purely because it's impossible to actually do or am I just writing it wrong: class someClass: self.myString = "Hello" self.myMap = { 'someString' : self.functionInClass } So if ...
Python: Can I have a string as a key and a function as value in a dictionary?
In other words, is this giving me errors purely because it's impossible to actually do or am I just writing it wrong: class someClass: self.myString = "Hello" self.myMap = { 'someString' : self.functionInClass } So if functionInClass takes an argument, I want to call it like so from anywhere inside t...
[ "Yes you can do that, since methods (or bound methods) are just objects themselves.\nIn your code you forgot your function. I think you wanted to write somthing like this:\nclass someClass:\n def __init__(self):\n self.myString = \"Hello\"\n self.myMap = {\n 'someString' : self.function...
[ 3, 1, 0, 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0007636508_dictionary_python.txt
Q: django generic one-to-one relations, with cascading deletes I'm trying to emulate an inheritance model using django's generic relations. So far, this is what I've come up with: class Base(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = ...
django generic one-to-one relations, with cascading deletes
I'm trying to emulate an inheritance model using django's generic relations. So far, this is what I've come up with: class Base(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey() ... other stuff class Meta: ...
[ "Why not have a BaseSubClass, and then inherit from that. So based on your example:\nclass BaseSubClass(models.Model):\n _base = generic.GenericRelation(Base)\n\n class Meta:\n abstract = True\n\n @property\n def base(self):\n return self._base.all()[0]\n\nclass SubClass1(BaseSubClass):\n ...
[ 2 ]
[]
[]
[ "django", "django_models", "generic_relations", "python" ]
stackoverflow_0007593064_django_django_models_generic_relations_python.txt
Q: Newbie python RESULTS BINDINGS question I'm using python with SPARQLWrapper and it has worked until now -- I'm not able to add a new SPARQL object to my results. Here is my working snippet: else: for result in results["results"]["bindings"]: project = result["project"]["value"].encode('utf-8') ...
Newbie python RESULTS BINDINGS question
I'm using python with SPARQLWrapper and it has worked until now -- I'm not able to add a new SPARQL object to my results. Here is my working snippet: else: for result in results["results"]["bindings"]: project = result["project"]["value"].encode('utf-8') filename = result["filename"]["value"...
[ "Either your result dict has no key \"project\", or the result[\"project\"] dict has no key \"value\". \nSo insert\nprint result.keys()\nprint result[\"project\"]\nprint result[\"project\"].keys()\nprint result[\"project\"][\"value\"]\n\nimediatly after for result in ... and you see what is going wrong. \n", "My ...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007437104_python.txt
Q: Binary string in Python issues For some reason I'm having a heck of a time figuring out how to do this in Python. I am trying to represent a binary string in a string variable, and all I want it to have is 0010111010 However, no matter how I try to format it as a string, Python always chops off the leading zeroes...
Binary string in Python issues
For some reason I'm having a heck of a time figuring out how to do this in Python. I am trying to represent a binary string in a string variable, and all I want it to have is 0010111010 However, no matter how I try to format it as a string, Python always chops off the leading zeroes, which is giving me a headache in t...
[ "If I understood you right, you could do it this way:\na = 0b0010111010\n'{:010b}'.format(a)\n\n#The output is: '0010111010'\n\nPython 2.7\nIt uses string format method.\nThis is the answer if you want to represent the binary string with leading zeros.\nIf you are just trying to generate a random string with a bina...
[ 7, 1 ]
[]
[]
[ "binary", "python", "string" ]
stackoverflow_0007636860_binary_python_string.txt
Q: How can I test the validity of a ReferenceProperty in Appengine? I am currently testing a small application I have written. I have not been sufficiently careful in ensuring the data in my datastore is consistent and now I have an issue that I have some records referencing objects which no longer exist. More specif...
How can I test the validity of a ReferenceProperty in Appengine?
I am currently testing a small application I have written. I have not been sufficiently careful in ensuring the data in my datastore is consistent and now I have an issue that I have some records referencing objects which no longer exist. More specifially, I have some objects which have ReferenceProperty's which have b...
[ "This will test key existence without returning an entity:\ndb.Query(keys_only=True).filter('__key__ =', test_key).count(1) == 1\nI'm not certain that it's computationally cheaper than fetching the entity.\n" ]
[ 3 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0007636806_google_app_engine_google_cloud_datastore_python.txt
Q: Picking a suitable GUI framework for project I have a project where I have to show some sort of changing bar graph with results from a function. This bar graph should be in colour and 3d. I want it to look good since it's an open source educational program where it teaches the user about different voting systems a...
Picking a suitable GUI framework for project
I have a project where I have to show some sort of changing bar graph with results from a function. This bar graph should be in colour and 3d. I want it to look good since it's an open source educational program where it teaches the user about different voting systems and how they effect the outcome of an election. I w...
[ "For 3D graphics, you might want to use OpenGL with a game framework, such as PyGame or Pyglet. Use matplotlib as TJD suggested in the other answer.\n\nAs for GUI frameworks, they generally won't help much with 3D graphics:\nPyQt is one choice; I see you already have it in the question tags. PySide is very similar ...
[ 3, 2 ]
[]
[]
[ "pyqt", "python", "qt", "user_interface" ]
stackoverflow_0007637199_pyqt_python_qt_user_interface.txt
Q: Django manager.py sql creates empty file I'm trying to run my first Django application with sqlite3 database. When I run python manage.py sql my_app, it outputs the SQL queries, but the sqlite file is empty. What could be the reason? A: That command just prints the sql statements. If you want to create the schem...
Django manager.py sql creates empty file
I'm trying to run my first Django application with sqlite3 database. When I run python manage.py sql my_app, it outputs the SQL queries, but the sqlite file is empty. What could be the reason?
[ "That command just prints the sql statements. If you want to create the schema in the sqlite file, run:\npython manage.py syncdb\n\nIf you are trying to export the sql statements to a text file:\npython manage.py sql my_app > my_file.sql\n\n" ]
[ 1 ]
[]
[]
[ "django", "python", "sqlite" ]
stackoverflow_0007637384_django_python_sqlite.txt
Q: Python Find & Replace Beautiful Soup I am using Beautiful Soup to replace the occurrences of a pattern with a href link inside a HTML file I am facing a problem as described below modified_contents = re.sub("([^http://*/s]APP[a-z]{2}[0-9]{2})", "<a href=\"http://stack.com=\\1\">\\1</a>", str(soup)) Sample input 1...
Python Find & Replace Beautiful Soup
I am using Beautiful Soup to replace the occurrences of a pattern with a href link inside a HTML file I am facing a problem as described below modified_contents = re.sub("([^http://*/s]APP[a-z]{2}[0-9]{2})", "<a href=\"http://stack.com=\\1\">\\1</a>", str(soup)) Sample input 1: Input File contains APPdd34 Output File...
[ "This may not entirely answer your problem because I don't know an entire input file could look like, but I hope this is a direction you can take. \nfrom BeautifulSoup import BeautifulSoup, Tag\ntext = \"\"\"APPdd34\"\"\"\nsoup = BeautifulSoup(text)\nvar1 = soup.text\ntext = \"\"\"&lt;a href=\"http://stack.com=APPd...
[ 0 ]
[]
[]
[ "beautifulsoup", "find", "html", "python" ]
stackoverflow_0006674310_beautifulsoup_find_html_python.txt
Q: Reliably detect Windows in Python I'm working on a couple of Linux tools and need to prevent installation on Windows, since it depends on FHS and is thus rendered useless on that platform. The platform.platform function comes close but only returns a string. Unfortunately I don't know what to search for in that st...
Reliably detect Windows in Python
I'm working on a couple of Linux tools and need to prevent installation on Windows, since it depends on FHS and is thus rendered useless on that platform. The platform.platform function comes close but only returns a string. Unfortunately I don't know what to search for in that string for it to yield a reliable result....
[ ">>> import platform\n>>> platform.system()\n'Windows'\n\n", "For those that came here looking for a way to detect Cygwin from Python (as opposed to just detecting Windows), here are some example return values from os.name and platform.system on different platforms\nOS/build | os.name | platform.system() \n--...
[ 91, 69, 16, 13, 11, 1 ]
[]
[]
[ "platform_detection", "python", "windows" ]
stackoverflow_0001387222_platform_detection_python_windows.txt
Q: Python: detect redefinition? I'm looking for a way to somehow detect if a python function or class is being redefined or even only if it is defined twice and one definition erases the other. Can this be done with reflection somehow? Maybe by the function (or class) itself somehow? A: Redefinition of a class does...
Python: detect redefinition?
I'm looking for a way to somehow detect if a python function or class is being redefined or even only if it is defined twice and one definition erases the other. Can this be done with reflection somehow? Maybe by the function (or class) itself somehow?
[ "Redefinition of a class does nothing to the original class, it just assigns a whole new class to the same name. Checking is easy – just save the original, and see if the name still refers to it.\nclass SomeClass(object):\n x = 1\n\n# Save the original\n_my_saved_class = SomeClass\n\nclass SomeClass(object):\n ...
[ 3 ]
[]
[]
[ "python", "reflection" ]
stackoverflow_0007637656_python_reflection.txt
Q: Accessing Elements of a Tuple I am accessing an element of length 2 tuple by tuple_name[0] but the python interpreter keeps giving me error Index out of bounds. Here is the code for reference: def full(mask): v = True for i in mask: if i == 0: v = False return v def increment(mask,...
Accessing Elements of a Tuple
I am accessing an element of length 2 tuple by tuple_name[0] but the python interpreter keeps giving me error Index out of bounds. Here is the code for reference: def full(mask): v = True for i in mask: if i == 0: v = False return v def increment(mask, l): i = 0 while (i < l) an...
[ "Changing the final line to simply print a and running the exact code you've pasted above, I get the following output:\n[]\n([100], ['hello'])\n([12], ['hero'])\n([100, 12], ['hello', 'hero'])\n([32], ['fool'])\n([100, 32], ['hello', 'fool'])\n([12, 32], ['hero', 'fool'])\n([100, 12, 32], ['hello', 'hero', 'fool'])...
[ 5, 3, 1 ]
[]
[]
[ "python", "tuples" ]
stackoverflow_0007637673_python_tuples.txt
Q: How to track an objects state in time? In my script I read messages from socket and change the state of some objects in memory depending on the content in message. Everything works fine. But I want to implement deletion of non-active objects: for example, if there's no message for specified object during some time...
How to track an objects state in time?
In my script I read messages from socket and change the state of some objects in memory depending on the content in message. Everything works fine. But I want to implement deletion of non-active objects: for example, if there's no message for specified object during some time, it should be deleted. What is the best way...
[ "This one might not work for you, but:\nif you're okay with not removing objects after a specified time, but only keeping a specified number of objects, Python 3.2 has functools.lru_cache for exactly that.\n", "Store a timestamp in each object - update the timestamp to the current time whenever you modify it.\nTh...
[ 4, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007635456_python.txt
Q: cxfreeze (or equivalent) and cross build? Is it possible for cx_freeze (or any other tool with the same purpose) to cross build binaries? I.e. build Windows binary on a Linux PC? Or is this too much to ask? I tried with cx_freeze and got the following: cx_Freeze.freezer.ConfigError: no base named Win32GUI Tha...
cxfreeze (or equivalent) and cross build?
Is it possible for cx_freeze (or any other tool with the same purpose) to cross build binaries? I.e. build Windows binary on a Linux PC? Or is this too much to ask? I tried with cx_freeze and got the following: cx_Freeze.freezer.ConfigError: no base named Win32GUI Thanks,
[ "If you install Python etc. inside Wine, cx_Freeze will run, but it misses out some key DLLs. So no. If building on Windows isn't an option, you can work out the DLLs that it requires, and manually copy them into the build directory after running cx_Freeze.\n(Technical note: If anyone has the know-how to work on Wi...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0007636619_python.txt
Q: Python: sub string search I am trying to search for whole words with in a string and not sure how to do it. str1 = 'this is' str2 ='I think this isnt right' str1 in str2 gives me True, but I want it to return False. How do I do this? Thank you. I tried str2.find(str1), re.search(str1,str2), but I am not getting t...
Python: sub string search
I am trying to search for whole words with in a string and not sure how to do it. str1 = 'this is' str2 ='I think this isnt right' str1 in str2 gives me True, but I want it to return False. How do I do this? Thank you. I tried str2.find(str1), re.search(str1,str2), but I am not getting them to return nothing or a Fals...
[ "Use the \\b entity in regular expressions to match word boundaries.\nre.search(r'\\bthis is\\b', 'I think this isnt right')\n\n", "Another way using sets without a regular expression:\nset(['this', 'is']).issubset(set('I think this isnt right'.split(' ')))\n\nIf the string is really long or you're going to keep ...
[ 3, 1 ]
[]
[]
[ "python", "search", "string" ]
stackoverflow_0007637798_python_search_string.txt
Q: python output unexpected behaviour Following program is used to sort a list for i in range(len(q)): for j in range(len(q)): if not (q[i] < q[j]): t = q[i] q[i] = q[j] q[j] = t contents of q are : {-1 2 4} The output I get has one empty number...
python output unexpected behaviour
Following program is used to sort a list for i in range(len(q)): for j in range(len(q)): if not (q[i] < q[j]): t = q[i] q[i] = q[j] q[j] = t contents of q are : {-1 2 4} The output I get has one empty number like: 4 -1 2 i.e. extra number (empty) ...
[ "You want to sort a list?\nyour_list.sort()\n\n" ]
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0007637953_python.txt
Q: Non Sequential Loop Optimization in Python I have two dictionary objects, connections and network. This can be visualized as a graph, where each node is a computer and connections depict an edge between the computers and node. Network is a dictionary objects of unique networks where the computers can be a part, fo...
Non Sequential Loop Optimization in Python
I have two dictionary objects, connections and network. This can be visualized as a graph, where each node is a computer and connections depict an edge between the computers and node. Network is a dictionary objects of unique networks where the computers can be a part, for ex 1,2 2,3 4,5 5,1 are four connecti...
[ "I'm didn't really understand your question, but I feel the stock answer to graph-related questions applies here:\nUse NetworkX rather than trying to come up with your own data representations and algorithms. It may be harder to learn, but it'll save you time and headaches in the long run.\n", "while network.has_...
[ 2, 1 ]
[]
[]
[ "loops", "nonsequential", "optimization", "python" ]
stackoverflow_0007637928_loops_nonsequential_optimization_python.txt
Q: python: fast dictionary word lookup with wildcards* Given a text, which is split into a list of words, I want to lookup each of the words in an dictionary of words, which too is read from a text-file and split('\n'). Rather than checking if each word is contained in the dictionary (which is gruesomely slow) I need...
python: fast dictionary word lookup with wildcards*
Given a text, which is split into a list of words, I want to lookup each of the words in an dictionary of words, which too is read from a text-file and split('\n'). Rather than checking if each word is contained in the dictionary (which is gruesomely slow) I need to select a list of elements based on wildcards* ('*' is...
[ "You want a trie. Use the PyTrie package.\n", "Use a dawg, which is more efficient than a Trie in terms of space waste. There are a few python implementations, but for a start take a look here. \n" ]
[ 2, 2 ]
[]
[]
[ "dictionary", "lookup", "python", "tree" ]
stackoverflow_0007637808_dictionary_lookup_python_tree.txt
Q: easy_install failure on windows 7 I have created two eggs using bdist and egg_A is defines as a dependency of egg_B. I check both egg using the command unzip and both are ok, however when I try to insall the egg using easy_install I get the following stack trace : Installed c:\virtualenv\lib\site-packages\pymarke...
easy_install failure on windows 7
I have created two eggs using bdist and egg_A is defines as a dependency of egg_B. I check both egg using the command unzip and both are ok, however when I try to insall the egg using easy_install I get the following stack trace : Installed c:\virtualenv\lib\site-packages\pymarketdata-1.0-py2.7.egg Reading file:C:/pyt...
[ "This error:\n\nbad local file header\n\nseems to say that the file header (which usually determines the filetype) isn't passing Python's test. It could be the zipping program you used.\nTry 7-Zip (free) or a different program when creating your egg. I haven't made them before, but I think there is even a way to do...
[ 1 ]
[]
[]
[ "easy_install", "python", "windows_7" ]
stackoverflow_0007638109_easy_install_python_windows_7.txt
Q: Python regex search My previous example was not clear, I give another example : a = '123 - 48 <!-- 456 - 251 - --> 452 - 348' And if i do something like : [el for el in re.split(r' - ',a)] I catch : ['123', '48 <!-- 456', '251', '--> 452', '348'] But I want this : ['123', '48 <!-- 456 - 251 - --> 452', '348'] ...
Python regex search
My previous example was not clear, I give another example : a = '123 - 48 <!-- 456 - 251 - --> 452 - 348' And if i do something like : [el for el in re.split(r' - ',a)] I catch : ['123', '48 <!-- 456', '251', '--> 452', '348'] But I want this : ['123', '48 <!-- 456 - 251 - --> 452', '348'] Thanks...
[ "First remove the comments using something like this:\nre.sub(\"<!--.*?-->\", \"\", your_string)\n\nthen use your regex to extract numbers.\nYou can also use ?!... (negative lookahead assertion) but that won't be so simple.\n", "If you want one regex you could use something like:\n(\\d+)(?!(?:[^<]+|<(?!!--))*-->)...
[ 5, 0 ]
[ "The result you posted is of re.findall('(\\d+)',a);\nre.findall('(?:\\<\\!--.+\\d+.+--\\>)|(\\d+)',a)\n\n['123', '48', '', '452', '348']\nfilter(None, re.findall('(?:\\<\\!--.+\\d+.+--\\>)|(\\d+)',a))\n\n['123', '48', '452', '348']\n" ]
[ -1 ]
[ "python", "regex" ]
stackoverflow_0007637801_python_regex.txt
Q: Python, redirecting the stream of Popen to a python function I'm new to python programming. I have this problem: I have a list of text files (both compressed and not) and I need to : - connect to the server and open them - after the opening of the file, I need to take his content and pass it to another python fun...
Python, redirecting the stream of Popen to a python function
I'm new to python programming. I have this problem: I have a list of text files (both compressed and not) and I need to : - connect to the server and open them - after the opening of the file, I need to take his content and pass it to another python function that I wrote def readLogs (fileName): f = open (fileName, 'r...
[ "You do not have to split the stream/file into lines yourself. Just iterate:\nfor ln in f:\n # work on line in ln\n\nThis should work equally well for files (using open() for file()) and pipes (using Popen). Use the stdout property of the popen object to access the pipe connected to stdout of the subprocess\nExa...
[ 5, 1, 0, 0 ]
[]
[]
[ "popen", "python", "stream", "subprocess", "yield" ]
stackoverflow_0000650877_popen_python_stream_subprocess_yield.txt
Q: Display image with Tkinter and loop over time I am currently using the PIL and Tkinter to display images. I am streaming in images from a network and want to update my window automatically as the come in (much like a picture slideshow). My code for displaying images works; however, i have to click the [x] button...
Display image with Tkinter and loop over time
I am currently using the PIL and Tkinter to display images. I am streaming in images from a network and want to update my window automatically as the come in (much like a picture slideshow). My code for displaying images works; however, i have to click the [x] button on the display window for the photo to update. I...
[ "Call the method after to schedule a command to run in the future. It's perfectly legal for this command to also call after to schedule itself to run again in the future.\nFor an example that shows a Label getting its text updated every second, see this answer to another question here on SO.\n" ]
[ 1 ]
[]
[]
[ "python", "python_imaging_library", "tkinter" ]
stackoverflow_0007638088_python_python_imaging_library_tkinter.txt
Q: How to do bilinear interpolation for PIL Image in python? I have read an image in python using Image module and converted it into a numpy array as follows... im=Image.open(infile) imdata = scipy.misc.fromimage(im) After processing, what I get are not the integer coordinates but the real values. It ...
How to do bilinear interpolation for PIL Image in python?
I have read an image in python using Image module and converted it into a numpy array as follows... im=Image.open(infile) imdata = scipy.misc.fromimage(im) After processing, what I get are not the integer coordinates but the real values. It is important to note that it is an rgb image. I want to get the...
[ "You are correct that getPixel will only accept integer coordinates.\nYou can do your own linear interpolation if you don't mind it being slow:\ndef lerp(a, b, coord):\n if isinstance(a, tuple):\n return tuple([lerp(c, d, coord) for c,d in zip(a,b)])\n ratio = coord - math.floor(coord)\n return int(...
[ 5 ]
[]
[]
[ "image", "interpolation", "python" ]
stackoverflow_0007638364_image_interpolation_python.txt
Q: What is the difference between accessing image coordinates from image module of python or as a numpy array and storing it? I have read an image in python using Image module and converted it into a numpy array as follows... im=Image.open(infile) imdata = scipy.misc.fromimage(im) im.getPixel(x...
What is the difference between accessing image coordinates from image module of python or as a numpy array and storing it?
I have read an image in python using Image module and converted it into a numpy array as follows... im=Image.open(infile) imdata = scipy.misc.fromimage(im) im.getPixel(x,y) First question is does x belong to the row number and y to the column number. Is it in the same visual order as we see it o...
[ "fromimage\nthe docs state that the returned numpy array is of dimension [width, height, nr_channels], where nr_channels are the different colour bands/channels are stored in the third dimension, such that a grey-image is MxN, an RGB-image MxNx3 and an RGBA-image MxNx4\nso to get 'pixel' x, y (indeed row-x, height-...
[ 2 ]
[]
[]
[ "image", "python" ]
stackoverflow_0007638443_image_python.txt
Q: Python, the web page seems not to see ALL my DATA and does not provide the correct answer? If I enter this URL I will get some XML formatted text as a response: http://skrutten.nada.kth.se/scrut/svesve/?text=g%E5&url=&xmlout=on&x=Granska Now I try to write a Python function that POST a message to the web page and...
Python, the web page seems not to see ALL my DATA and does not provide the correct answer?
If I enter this URL I will get some XML formatted text as a response: http://skrutten.nada.kth.se/scrut/svesve/?text=g%E5&url=&xmlout=on&x=Granska Now I try to write a Python function that POST a message to the web page and I should get the same information. However, I am getting less information from the web page. I...
[ "Try this\ndef fetch_web (name, par1):\n    \"\"\"Fetch the web data defined by name and return a string with the web page\"\"\"\n\n    if name == \"granska\":\n        url = \"http://skrutten.nada.kth.se/scrut/svesve/\"\n        values = {\"text\":par1,\"xmlout\":\"on\",\"x\":\"Granska\",\"url\":\"\"}\n        cod...
[ 3 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0007638375_python_python_3.x.txt
Q: Sort numpy string array with negative numbers? I'm having a problem sorting a numpy array that has numbers as strings. I need to keep these as strings because there are other words after the integers. It's sorting negative numbers in reverse order: >>> import numpy as np >>> a = np.array(["3", "-2", "-1", "0", ...
Sort numpy string array with negative numbers?
I'm having a problem sorting a numpy array that has numbers as strings. I need to keep these as strings because there are other words after the integers. It's sorting negative numbers in reverse order: >>> import numpy as np >>> a = np.array(["3", "-2", "-1", "0", "2"]) >>> a.sort() >>> a array(['-1', '-2', '0', '2'...
[ "You could use natural sorting:\nimport numpy as np\nimport re\n\ndef atoi(text):\n try:\n return int(text)\n except ValueError:\n return text\n\ndef natural_keys(text):\n '''\n alist.sort(key=natural_keys) sorts in human order\n http://nedbatchelder.com/blog/200712/human_sorting.html\n...
[ 6, 2 ]
[]
[]
[ "arrays", "numpy", "python", "sorting" ]
stackoverflow_0007638738_arrays_numpy_python_sorting.txt
Q: Python subprocess.Popen stdin interfering with stdout/stderr Very puzzled by this. When using Popen, if only using stdout or stderr the following code works: def run(self): self.externalProcess = subprocess.Popen(['./external_process.out 1>&2'], shell=True, stderr=subprocess.PIPE) while self.externalBinary...
Python subprocess.Popen stdin interfering with stdout/stderr
Very puzzled by this. When using Popen, if only using stdout or stderr the following code works: def run(self): self.externalProcess = subprocess.Popen(['./external_process.out 1>&2'], shell=True, stderr=subprocess.PIPE) while self.externalBinary.poll() is None: print('Still running') print('Done ru...
[ "It seems like you might be trying to write data to the subprocess (via STDIN) as well as read its output (via STDOUT) interactively.\nAs mentioned in the answer to this SO question, that is a no-no!\nYou could use Popen.communicate, but that is a blocking call which will wait for all communication to finish (you c...
[ 1 ]
[]
[]
[ "popen", "python", "subprocess" ]
stackoverflow_0007638800_popen_python_subprocess.txt
Q: PYTHONPATH - dynamic for different python installs? On my CentOS5 server, I have both Python2.4 and 2.6 (2.4 is required for yum to work). I'm not sure what happened, but suddenly the system gets very confused every time I try to run a file whose modules are loaded into the 2.4 site-packages directory. I checked t...
PYTHONPATH - dynamic for different python installs?
On my CentOS5 server, I have both Python2.4 and 2.6 (2.4 is required for yum to work). I'm not sure what happened, but suddenly the system gets very confused every time I try to run a file whose modules are loaded into the 2.4 site-packages directory. I checked the PYTHONPATH/sys.path and it looks like everything was o...
[ "First of all, use virtualenv to isolate packages for multiple Python installations. Most of your problems will go away immediately. \nSecond, as Ibp has recommended in his answer, change the shebang line to use the \"currently active\" python binary so that it will work across multiple interpreters. \n", "Instea...
[ 2, 1 ]
[]
[]
[ "python", "pythonpath" ]
stackoverflow_0007638886_python_pythonpath.txt
Q: Execute Python Script as Root (seteuid vs c-wrapper) I have a quick one off task in a python script that I'd like to call from Django (www user), that's going to need to root privileges. At first I thought I would could use Python's os.seteuid() and set the setuid bit on the script, but then I realized that I wou...
Execute Python Script as Root (seteuid vs c-wrapper)
I have a quick one off task in a python script that I'd like to call from Django (www user), that's going to need to root privileges. At first I thought I would could use Python's os.seteuid() and set the setuid bit on the script, but then I realized that I would have to set the setuid bit on Python itself, which I as...
[ "sudo does not require setuid bit on Python. You can enable sudo for one command only, no arguments:\n www ALL=(ALL) NOPASSWD: /root/bin/reload-stuff.py \"\"\n\nThis would be secure if your script does not take any arguments, cannot be overridden by www user, and sudo does \"env_reset\" (the default...
[ 14, 3, 1 ]
[]
[]
[ "c", "django", "freebsd", "python" ]
stackoverflow_0007639141_c_django_freebsd_python.txt
Q: Conditionally evaluated debug statements in Python Python has a few ways of printing "trace" output. print, import logging, stdout.write can be used to print debugging info, but they all have one drawback: even if the logger's threshold is too high or the stream is closed, Python will still evaluate the arguments ...
Conditionally evaluated debug statements in Python
Python has a few ways of printing "trace" output. print, import logging, stdout.write can be used to print debugging info, but they all have one drawback: even if the logger's threshold is too high or the stream is closed, Python will still evaluate the arguments to the print statement. (Strict Evaluation) This could c...
[ "if all your debug function will take is a string, why not change it to take a format string and the arguments: \ndebug(lambda:\"Working on {0}\".format(currentItem))\n\nbecomes \ndebug(\"Working on {0}\", currentItem)\n\nand\nif __debug__:\n def debug(format, *values):\n print format.format(*values)\nel...
[ 4, 3, 1, 1 ]
[]
[]
[ "debugging", "logging", "python" ]
stackoverflow_0007634457_debugging_logging_python.txt
Q: Python 3, how to convert a string into "iso-8859-1" to use in html When I type the text "gå" in a swedish web page, the html generates the following field: g%E5. That is, the letter a-ring (å) is coded as %E5. I assume that they are using ISO-8859-1. If I generate the same html address using a Python 3.0 script th...
Python 3, how to convert a string into "iso-8859-1" to use in html
When I type the text "gå" in a swedish web page, the html generates the following field: g%E5. That is, the letter a-ring (å) is coded as %E5. I assume that they are using ISO-8859-1. If I generate the same html address using a Python 3.0 script the string "gå" is coded as g%C3%A5. Now the letter a-ring(å) is coded as ...
[ "I created this Python source file:\n#coding: utf-8\nprint repr(u\"gå\".encode(\"ISO-8859-1\"))\n\nand got\n'g\\xe5'\n\nas output.\nI'm using Python 2, but it should be the same for Python 3 without the u before the unicode literal, possibly without the coding line, and with ascii instead of repr.\nSo it should be ...
[ 2 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0007639907_python_python_3.x.txt
Q: Strange ClassNotMappedError with sqlalchemy and Python I'm building a rather simple model using sqlalchemy, using a many-to-many relationship defined by an association table and two classes that are to be associated using the declarative syntax. When generating instances elsewhere in my code, however, I keep on ge...
Strange ClassNotMappedError with sqlalchemy and Python
I'm building a rather simple model using sqlalchemy, using a many-to-many relationship defined by an association table and two classes that are to be associated using the declarative syntax. When generating instances elsewhere in my code, however, I keep on getting ClassNotMappedError. The model is defined as follows:...
[ "immature_product is not mapped, so the relationship within class ImmatureMirna can't be formed. Change immature_product to be a subclass of Base and I predict it will work fine.\n" ]
[ 0 ]
[]
[]
[ "many_to_many", "python", "sqlalchemy" ]
stackoverflow_0007635146_many_to_many_python_sqlalchemy.txt
Q: Python SHA1 DECODE function I cant find how to decode string encoded in sha1. I'm suprised that i can't find simple function in python docs or google doing sha1 decoding. I give up. I need help.. A: SHA1 is a hashing algorithm. Hashing is one-way, which means that you can't recover the input from the output for...
Python SHA1 DECODE function
I cant find how to decode string encoded in sha1. I'm suprised that i can't find simple function in python docs or google doing sha1 decoding. I give up. I need help..
[ "SHA1 is a hashing algorithm. Hashing is one-way, which means that you can't recover the input from the output for any non-trivial hash function. A simple example of a one-way hash function would be adding together all the digits of a number. 1234 would hash to 1 + 2 + 3 + 4 = 10, but so would 4321, 1900, 5050, and...
[ 18 ]
[]
[]
[ "decoding", "python", "sha1" ]
stackoverflow_0007640033_decoding_python_sha1.txt
Q: Trying to check if value already in MySQL DB I am writing a script that will run every 20 minutes that looks for files to download but I want to check if I have already dowloaded the file: First my code executes this command: cursor.execute("SELECT `file_id` FROM `reports`") file_ids = list(cursor.fetchall()) fil...
Trying to check if value already in MySQL DB
I am writing a script that will run every 20 minutes that looks for files to download but I want to check if I have already dowloaded the file: First my code executes this command: cursor.execute("SELECT `file_id` FROM `reports`") file_ids = list(cursor.fetchall()) file_ids is a longer version of this: [('735724',), (...
[ "The results from the database is not a string, it's a list of tuples. What you probably want to do is build a list with just the ids, then check if that numeric value is in the list. For example:\nfile_ids = [row[0] for row in cursor.fetchall()]\nis_in_list = test_id in file_ids\nif is_in_list:\n print \"true\"...
[ 1, 0 ]
[]
[]
[ "mysql", "mysql_python", "python" ]
stackoverflow_0007640061_mysql_mysql_python_python.txt
Q: python list comprehension products I'm trying to build a specific list comprehension to take data from list of lists/matrix A and matrix B to generate a third matrix, C. I've annotated the code and provided the expected outcome, but as written, the list comprehension doesn't do what's expected and can can be expr...
python list comprehension products
I'm trying to build a specific list comprehension to take data from list of lists/matrix A and matrix B to generate a third matrix, C. I've annotated the code and provided the expected outcome, but as written, the list comprehension doesn't do what's expected and can can be expressed in more elegant code than I've att...
[ "I'm not sure I understand what you're asking for, might be missing something.\nYour posted code is replete with syntax errors and undefined functions.\nHowever, this does what I think you're asking for, but with different results:\n>>> from operator import mul\n>>> A = [('Apple',0.95,0.99,0.89,0.87,0.93),('Bear',0...
[ 1 ]
[]
[]
[ "list", "list_comprehension", "python" ]
stackoverflow_0007638419_list_list_comprehension_python.txt
Q: Is there any better way to access twitter streaming api through python? I need to fetch twitter historical data for a given set of keywords. Twitter Search API returns tweets that are not more than 9 days old, so that will not do. I'm currently using Tweepy Library (http://code.google.com/p/tweepy/) to call Stream...
Is there any better way to access twitter streaming api through python?
I need to fetch twitter historical data for a given set of keywords. Twitter Search API returns tweets that are not more than 9 days old, so that will not do. I'm currently using Tweepy Library (http://code.google.com/p/tweepy/) to call Streaming API and it is working fine except the fact that it is too slow. For examp...
[ "How far back do you need? To fetch historical data, you might want to keep the stream on indefinitely (the stream API allows for this) and store the stream locally, then retrieve historical data from your db.\nI also use Tweepy for live Stream/Filtering and it works well. The latency is typically < 1s and Tweepy...
[ 1, 0 ]
[]
[]
[ "api", "python", "streaming", "tweepy", "twitter" ]
stackoverflow_0007564100_api_python_streaming_tweepy_twitter.txt
Q: writing some numbers into csv like comparision matrix I am using python to write some comparison value as below mentioned: ids = [1, 2, 3] vals = [0.0, 0.71, 0.89, 0.71, 0.0, 0.77, 0.89, 0.77, 0.0] where ids are id_number (int) of 3 chemical compounds derived from a database and vals are comparison values with e...
writing some numbers into csv like comparision matrix
I am using python to write some comparison value as below mentioned: ids = [1, 2, 3] vals = [0.0, 0.71, 0.89, 0.71, 0.0, 0.77, 0.89, 0.77, 0.0] where ids are id_number (int) of 3 chemical compounds derived from a database and vals are comparison values with each others ......but I want these ids and vals TO BE WRITTE...
[ "Using the csv module:\nimport csv\n\nids= [1, 2, 3] \nvals = [0.0, 0.71, 0.89, 0.71, 0.0, 0.77, 0.89, 0.77, 0.0]\n\nwith open('/tmp/test.csv','w') as f:\n writer=csv.writer(f, delimiter='\\t',lineterminator='\\n',)\n writer.writerow(['']+ids)\n for i,row in enumerate(zip(*[iter(vals)]*3),1):\n writ...
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0007640615_python.txt
Q: ModSecurity: Output filter: Failed to read bucket (rc 104): Connection reset by peer I'm doing a POST request to a rest service made with django and piston uploading a file, but when I do the request i get this (strange?) error: [Sun Jul 04 16:12:38 2010] [error] [client 79.39.191.166] ModSecurity: Output filter: ...
ModSecurity: Output filter: Failed to read bucket (rc 104): Connection reset by peer
I'm doing a POST request to a rest service made with django and piston uploading a file, but when I do the request i get this (strange?) error: [Sun Jul 04 16:12:38 2010] [error] [client 79.39.191.166] ModSecurity: Output filter: Failed to read bucket (rc 104): Connection reset by peer [hostname "url"] [uri "/api/odl/"...
[ "I believe you need to implement CRSF protection as per https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax\n", "Output filtering is a way for an administrator to check all text that go through Apache for a specific set a strings, and then block those requests. \nYou have two options:\n\nLook at the mod_...
[ 1, 1 ]
[]
[]
[ "apache", "django", "mod_security", "python", "rest" ]
stackoverflow_0003176536_apache_django_mod_security_python_rest.txt
Q: download a file with mechanize I have a browser instance that has opened a page . I would like to download and save down all the links ( they are PDFs ). Does someone know how to do it ? Thx A: import urllib, urllib2,cookielib, re #http://www.crummy.com/software/BeautifulSoup/ - required from BeautifulSoup imp...
download a file with mechanize
I have a browser instance that has opened a page . I would like to download and save down all the links ( they are PDFs ). Does someone know how to do it ? Thx
[ "import urllib, urllib2,cookielib, re\n#http://www.crummy.com/software/BeautifulSoup/ - required\nfrom BeautifulSoup import BeautifulSoup\n\nHOST = 'https://www.adobe.com/'\n\ncj = cookielib.CookieJar()\nopener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))\n\nreq = opener.open( HOST + 'pdf' )\nresponce = ...
[ 3, 1 ]
[]
[]
[ "mechanize", "python" ]
stackoverflow_0007640762_mechanize_python.txt
Q: Python date/time conversion between text files I have a hydrologic model text file output (export.txt) that looks like: Units CFS Type INST-VAL 1 01 Jan 1997, 02:00 1933.0 2 01 Jan 1997, 04:00 1918.0 3 01 Jan 1997, 06:00 1918.0 4 01 Jan 1997, 08:00 1904.0 5 01 Jan 1997, 10:00 1904.0 ... And have Python (2.6...
Python date/time conversion between text files
I have a hydrologic model text file output (export.txt) that looks like: Units CFS Type INST-VAL 1 01 Jan 1997, 02:00 1933.0 2 01 Jan 1997, 04:00 1918.0 3 01 Jan 1997, 06:00 1918.0 4 01 Jan 1997, 08:00 1904.0 5 01 Jan 1997, 10:00 1904.0 ... And have Python (2.6) coded the following to format for input to an opti...
[ "import datetime\ns = '''1 01 Jan 1997, 02:00 1933.0\n2 01 Jan 1997, 04:00 1918.0\n3 01 Jan 1997, 06:00 1918.0\n4 01 Jan 1997, 08:00 1904.0\n5 01 Jan 1997, 10:00 1904.0\n6 01 Jan 1997, 24:00 1000.0'''\nfor row in s.split('\\n'):\n prefix = row[:2]\n sdate = row[2:-7]\n suffix = row[-7:]\n if sdate[13:15...
[ 3, 0 ]
[]
[]
[ "date", "format", "python", "text", "time" ]
stackoverflow_0007638138_date_format_python_text_time.txt
Q: Django: base model signal handler doesn't fire In the following sample code: from django.db import models from django.db.models.signals import pre_save # Create your models here. class Parent(models.Model): name = models.CharField(max_length=64) def save(self, **kwargs): print "Parent save..." ...
Django: base model signal handler doesn't fire
In the following sample code: from django.db import models from django.db.models.signals import pre_save # Create your models here. class Parent(models.Model): name = models.CharField(max_length=64) def save(self, **kwargs): print "Parent save..." super(Parent, self).save(**kwargs) def pre_sa...
[ "There's an open ticket about this, #9318.\nYour workaround looks fine. Here are two others suggested on the ticket by benbest86 and alexr respectively.\n\nListen on the child class signal, and send the Parent signal there.\ndef call_parent_pre_save(sender, instance, created, **kwargs):\n pre_save.send(sender=Pa...
[ 6, 2 ]
[]
[]
[ "django", "python", "signals" ]
stackoverflow_0007640733_django_python_signals.txt
Q: References in python classes on self I expet that this code should output: 8 8 but it does not. class tree: def __init__(self, size=2): if size == 0: return None if size > 1: half = size//2 self.left = tree(size-half) self.right = tree(half) ...
References in python classes on self
I expet that this code should output: 8 8 but it does not. class tree: def __init__(self, size=2): if size == 0: return None if size > 1: half = size//2 self.left = tree(size-half) self.right = tree(half) else: self.left = self.ri...
[ "Karl's answer is entirely right about everything, but there is certainly a way to make resize act as you're expecting.\nThree steps:\n\nMake a copy of the tree\nRe-initialize the tree so it's the next size larger\nSet the enlarged tree's left to the copy of the original tree\ndef resize(self,n):\n while sel...
[ 4, 2 ]
[]
[]
[ "python", "reference" ]
stackoverflow_0007641484_python_reference.txt
Q: Trying to calculate large numbers in Python with gmpy. Python keeps crashing? I was recommended to use gmpy to assist with calculating large numbers efficiently. Before I was just using python and my script ran for a day or two and then ran out of memory (not sure how that happened because my program's memory usag...
Trying to calculate large numbers in Python with gmpy. Python keeps crashing?
I was recommended to use gmpy to assist with calculating large numbers efficiently. Before I was just using python and my script ran for a day or two and then ran out of memory (not sure how that happened because my program's memory usage should basically be constant throughout.. maybe a memory leak?) Anyways, I keep g...
[ "Disclaimer: I'm the maintainer of gmpy and gmpy2.\nI won't be able to test this until tonight. But a couple of comments and questions.\nInstead of using (s * s) % M, use pow(s, 2, M). It should be faster.\nWhat happens if you use gmpy2.mpz() instead of gmpy2.xmpz() ?\nAre you running a 64-bit version of Python and...
[ 7 ]
[]
[]
[ "gmp", "memory_leaks", "memory_management", "python" ]
stackoverflow_0007641185_gmp_memory_leaks_memory_management_python.txt
Q: Regular expression to remove endline space patterns I have a website updater that converts each p element to a textarea, the user types in the content then each textarea is converted back to p & I grab the resulting HTML & store that in my SQL database. My Problem: In Internet Explorer, when I go to grab the HTML ...
Regular expression to remove endline space patterns
I have a website updater that converts each p element to a textarea, the user types in the content then each textarea is converted back to p & I grab the resulting HTML & store that in my SQL database. My Problem: In Internet Explorer, when I go to grab the HTML back it has slightly changed the html. For example: // Fr...
[ "I would go about this a different way:\nfirstly spilt by line.\nhtml_content_list = HTML_CONTENT.split(\"\\n\"); // Split by line;\n\nthen remove all whitespace on the end with a .trim() (assuming we are talking about strings and one line each, test for null first)\nfor(var i in html_content_list)\n{\n html_con...
[ 0, 0 ]
[]
[]
[ "javascript", "python", "regex" ]
stackoverflow_0007641664_javascript_python_regex.txt