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/Tkinter: Loop iterations not completing
In the following case, I am trying to print all output of temp2 script (which is run through subprocess) on to a textbox widget in realtime basis.
The problem I am facing is this, in temp2, for i <= 468, the script is working fine and to me it appears to be real time.... | Python/Tkinter: Loop iterations not completing | In the following case, I am trying to print all output of temp2 script (which is run through subprocess) on to a textbox widget in realtime basis.
The problem I am facing is this, in temp2, for i <= 468, the script is working fine and to me it appears to be real time.
However, if i put i = 469 or above, the execution h... | [
"Your problem is that the call to test.stdout.readline is blocking - which means processing will stop there and only resume when there is a new line of data avalilable which is returned.\nThe same is true for test.stderr.readline of course.\nI think the simplest way of dealing with what you want is having your sub... | [
1,
0,
0
] | [] | [] | [
"loops",
"python",
"subprocess",
"textbox",
"tkinter"
] | stackoverflow_0008294294_loops_python_subprocess_textbox_tkinter.txt |
Q:
html forms to django
Possible Duplicate:
python/django adder
I am new to django and tryed to make a site that takes my number (inputted from an of html) and add/ subtract it to an other.
So i tryed this in views.py:
def calc(request):
try:
i1 = int(request.GET['i1'])
i2 = int(request.GE... | html forms to django |
Possible Duplicate:
python/django adder
I am new to django and tryed to make a site that takes my number (inputted from an of html) and add/ subtract it to an other.
So i tryed this in views.py:
def calc(request):
try:
i1 = int(request.GET['i1'])
i2 = int(request.GET['i2'])
except Multi... | [
"Ok, I'm going to answer this simply so we can be done with this question, which was also posted yesterday. I'm not trying to be rude here, but you really need to do some research, read some tutorials, etc, before asking a question that doesn't really make a whole lot of sense. I'm sticking the save logic of the fo... | [
3,
1
] | [] | [] | [
"django",
"html",
"python"
] | stackoverflow_0008433510_django_html_python.txt |
Q:
Is it possible 'step into' a method to make changes when needed
I’m working on a Python script that accesses number of websites. I don’t think writing a whole class for each website is a feasible option, so I am looking for a way to reduce the code and re-use code as much as I can and write it as efficiently as I ... | Is it possible 'step into' a method to make changes when needed | I’m working on a Python script that accesses number of websites. I don’t think writing a whole class for each website is a feasible option, so I am looking for a way to reduce the code and re-use code as much as I can and write it as efficiently as I can. Although the website share same or similar engine (e.g. Wordpres... | [
"Why can't you just call some process function from the main method, process can do whatever you want it to do, and you can even override it in derived classes e.g.\nclass WordPress(object):\n def newentry(self):\n data = get_data()\n data = process_data(data)\n\n # do moe generi cthings\n\n... | [
1
] | [] | [] | [
"code_reuse",
"python"
] | stackoverflow_0008433917_code_reuse_python.txt |
Q:
python classes adding numbers
I need to write a class, Numbers, with methods addNumbers and currentSum, that prints the current sum. Eg.:
numbers = Numbers()
numbers.addNumber(3)
numbers.addNumber(2)
print numbers.currentSum()
should print 5
I have made a class:
class Numbers:
def __init__(self, numbers):
... | python classes adding numbers | I need to write a class, Numbers, with methods addNumbers and currentSum, that prints the current sum. Eg.:
numbers = Numbers()
numbers.addNumber(3)
numbers.addNumber(2)
print numbers.currentSum()
should print 5
I have made a class:
class Numbers:
def __init__(self, numbers):
self.numbers=addNumbers
return... | [
"class Numbers:\n def __init__(self):\n self.__sum=0\n def addNumber(self, number):\n self.__sum += number\n def currentSum(self):\n return self.__sum\n\n",
"Hints:\n\nYou need to implement the currentSum() method\nYou also need to implement the addNumber() method\naddNumber() will need... | [
3,
2,
0
] | [] | [] | [
"class",
"python"
] | stackoverflow_0008434392_class_python.txt |
Q:
Error when post message from C# program with server using Twisted python
My Method to post a message to server using C# .NET 4.0
private String postHTTP(String url)
{
String result = "";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
s... | Error when post message from C# program with server using Twisted python | My Method to post a message to server using C# .NET 4.0
private String postHTTP(String url)
{
String result = "";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
string postData = "Data has Posted";
byte[] byteArray = Encoding.UTF8.G... | [
"So the problem you're hitting is:\nKeyError: 'the-field'\n\nThis is because your client is posting:\nData has Posted\n\nThere are no form fields in that post data. There are two things you probably want to do.\nFirst, make your server more robust against bad input. It's already somewhat robust: bad input generat... | [
1
] | [] | [] | [
"c#",
"httpwebrequest",
"python",
"twisted"
] | stackoverflow_0008431851_c#_httpwebrequest_python_twisted.txt |
Q:
What happens when import a module in ironpython?
In CPython, I think, import means compile the py file to a pyc file and execute the file in the current frame, and the next time CPython will load the pyc file directly without compiling again. What about import in ironpython? I guess ironpython don't have a pyc-lik... | What happens when import a module in ironpython? | In CPython, I think, import means compile the py file to a pyc file and execute the file in the current frame, and the next time CPython will load the pyc file directly without compiling again. What about import in ironpython? I guess ironpython don't have a pyc-like format. Does it compile every time when import?
| [
"Yes, IronPython recompiles the imported module on every run. Twice, actually.\nIt's complicated.\nOn the first pass, the Python code is parsed into an AST, the AST is converted into a DLR expression tree, and the expression tree is stored. When it is time to execute it, the expression tree is compiled into a set o... | [
7
] | [] | [] | [
"dynamic_language_runtime",
"import",
"ironpython",
"python"
] | stackoverflow_0008426999_dynamic_language_runtime_import_ironpython_python.txt |
Q:
How to efficiently build a Python dictionary in C++
For performance reasons I want to port parts of my python program to C++ and I therefore try to write a simple extension for my program. The C++ part will build a dictionary, which then needs to be delivered to the Python program.
One way I found seems to be to b... | How to efficiently build a Python dictionary in C++ | For performance reasons I want to port parts of my python program to C++ and I therefore try to write a simple extension for my program. The C++ part will build a dictionary, which then needs to be delivered to the Python program.
One way I found seems to be to build my dict-like object in C++, e.g. a boost::unordered_... | [
"\nUse the CPython API directly yes:\n\n\n PyObject *d = PyDict_New()\n for (...) {\n PyDict_SetItem(d, key, val);\n }\n return d;\n\n\nOr write a python object that emulate a dict, by overriding __setitem__ and __getitem__. In both method, use your original hashmap. At the end, no copy will happen... | [
10
] | [] | [] | [
"c++",
"dictionary",
"performance",
"python",
"python_extensions"
] | stackoverflow_0008434754_c++_dictionary_performance_python_python_extensions.txt |
Q:
Ping and Pong in a threaded WebSocket server (Python)
I've written a threaded websocket server in Python, using the lastest websocket spec and I'm trying to make it send a ping request to every client every x seconds. The only way I came up with to do this is overriding BaseServer.server_forever() like this:
# ove... | Ping and Pong in a threaded WebSocket server (Python) | I've written a threaded websocket server in Python, using the lastest websocket spec and I'm trying to make it send a ping request to every client every x seconds. The only way I came up with to do this is overriding BaseServer.server_forever() like this:
# override BaseServer's serve_forever to send a ping request eve... | [
"The codes does not set the properties __is_shut_down and __shutdown_request anywhere. Therefore, trying to access them fails. Create them in the constructor, like this:\nclass ModTCPServer(SocketServer.TCPServer):\n def __init__(self, *args, **kwargs):\n SocketServer.TCPServer.__init__(self, *args, **kwa... | [
3
] | [] | [] | [
"ping",
"python",
"sockets",
"websocket"
] | stackoverflow_0008434858_ping_python_sockets_websocket.txt |
Q:
SQLAlchemy and Pyramid, how to get resources out of context?
I'm having a problem wrapping my head around my Pyramid web application. I have it structured very much like the one described by Michael Merickel here, except I'm using pure traversal to find my views. (They are declared configured with context='path.to... | SQLAlchemy and Pyramid, how to get resources out of context? | I'm having a problem wrapping my head around my Pyramid web application. I have it structured very much like the one described by Michael Merickel here, except I'm using pure traversal to find my views. (They are declared configured with context='path.toResource' name='myView'), pretty standard fare according to what I... | [
"This is the issue everyone runs into when trying to mix SQLAlchemy with traversal. A requirement of traversal is having a persistent tree structure that you can traverse to get from one node to another.\nYou basically have 2 options.\n\nYou can build an actual tree in your database where each resource knows where ... | [
5
] | [] | [] | [
"pyramid",
"python",
"sqlalchemy",
"url_routing"
] | stackoverflow_0008427902_pyramid_python_sqlalchemy_url_routing.txt |
Q:
Does Python have any standard lib which can compare two files by omitting the first several lines?
Does Python have any standard lib which can compare two files by omitting the first several lines?
Thanks!
A:
Have a look at filecmp and difflib. They don't support skipping lines out-of-the-box but that you can im... | Does Python have any standard lib which can compare two files by omitting the first several lines? | Does Python have any standard lib which can compare two files by omitting the first several lines?
Thanks!
| [
"Have a look at filecmp and difflib. They don't support skipping lines out-of-the-box but that you can implement yourself.\n",
"What's wrong in write your own?\ndef skipNdCmp(f1, f2,skip1,skip2,bufsize = 8*1024):\n with open(f1, 'rb') as fp1, open(f2, 'rb') as fp2:\n for i in xrange(0,skip1): fp1.readli... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0008434703_python.txt |
Q:
How todo Pylons/Pyramid plugin system?
Does anyone have any ideas what the best way to make a plugin system for pylons/pyramid? Or may be any example like yapsy-pylons?
Upd:
I wrote an example of yapsy for creating plug-ins in the pylons. I think this approach can be used in other frameworks.
pylons_yapsy_plugin... | How todo Pylons/Pyramid plugin system? | Does anyone have any ideas what the best way to make a plugin system for pylons/pyramid? Or may be any example like yapsy-pylons?
Upd:
I wrote an example of yapsy for creating plug-ins in the pylons. I think this approach can be used in other frameworks.
pylons_yapsy_plugin
| [
"Pyramid offers the config.include('somemodule') mechanism for allowing addons to configure themselves with your application. It also contains access to the ZCA registry to create plug points for utilities and adapters.\nThe framework itself is very very unopinionated and flexible and so you could probably use some... | [
3
] | [] | [] | [
"plugins",
"pylons",
"pyramid",
"python"
] | stackoverflow_0008222793_plugins_pylons_pyramid_python.txt |
Q:
Sending POST request with multiples values for same key with requests library
How would you go about sending a request with multiples values with the same key?
r = requests.post('http://www.httpbin.org/post', data={1: [2, 3]})
print r.content
{
...
"form": {
"1": "3"
},
...
}
Edit:
Hmm, very odd. I ... | Sending POST request with multiples values for same key with requests library | How would you go about sending a request with multiples values with the same key?
r = requests.post('http://www.httpbin.org/post', data={1: [2, 3]})
print r.content
{
...
"form": {
"1": "3"
},
...
}
Edit:
Hmm, very odd. I tried echoing the post data using a simple Flask application and I'm getting:
[('1... | [
"Try the Werkzeug MultiDict. It's the same structure used for this purpose in Flask applications.\nimport requests\nfrom werkzeug.datastructures import MultiDict\n\ndata = MultiDict([('1', '2'), ('1', '3')])\nr = requests.post('http://www.httpbin.org/post', data=data)\nprint(r.content)\n\nResult:\n...\n\"form\": {... | [
4,
4
] | [] | [] | [
"http_post",
"python",
"python_requests"
] | stackoverflow_0008394267_http_post_python_python_requests.txt |
Q:
Get wikipedia abstract using python
I want to get the first paragraph of a Wikipedia article. So i'm using wikitools.
from wikitools import wiki
from wikitools import api
from wikitools import page
wikiobj = wiki.Wiki("http://en.wikipedia.org/w/api.php")
wikipage = page.Page(wikiobj, title="Office_Space")
wikida... | Get wikipedia abstract using python | I want to get the first paragraph of a Wikipedia article. So i'm using wikitools.
from wikitools import wiki
from wikitools import api
from wikitools import page
wikiobj = wiki.Wiki("http://en.wikipedia.org/w/api.php")
wikipage = page.Page(wikiobj, title="Office_Space")
wikidata = wikipage.getWikiText(True)
print wik... | [
"The template parser in wikipedia_utils (referenced in this article on how to scrape and parse Wikipedia) looks like it'll allow you to put everything wikitools returns into a Python data structure, from which you can extract just the bits you want.\nEdit: You might also find Python library mwlib useful for this pu... | [
0,
0
] | [] | [] | [
"mediawiki",
"python"
] | stackoverflow_0008429597_mediawiki_python.txt |
Q:
Iterative string formatting/parsing?
I'm reading positional records from a text file, for examle, it looks like this:
AB ATEA 000401550
Each record is assigned a specific number of characters, for example:
Code: AB (characters from 0 - 2)
Name: ATEA (characters from 3 - 7)
Value1: 00040 (characters from 8 - 13)
V... | Iterative string formatting/parsing? | I'm reading positional records from a text file, for examle, it looks like this:
AB ATEA 000401550
Each record is assigned a specific number of characters, for example:
Code: AB (characters from 0 - 2)
Name: ATEA (characters from 3 - 7)
Value1: 00040 (characters from 8 - 13)
Value2: 1550 (characters from 13 - 16)
I h... | [
"You can specify a converter for each item:\ndef float_converter(value):\n return float('{0}.{1}'.format(value[:1], value[1:]))\n\nalist = [('Code' , 0 , 2 , None),\n ('Name' , 3 , 7 , None),\n ('Value1', 8 , 13, float_converter),\n ('Value2', 13, 16, float_converter)]\n\nadict = {}\nfo... | [
3,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0008435676_python.txt |
Q:
grep prefix python strings
I'm having problems using findall in python.
I have a text such as:
the name of 33e4853h45y45 is one of the 33e445a64b65 and we want all the 33e5c44598e46 to be matched
So i'm trying to find all occurrences of of those alphanumeric strings in the text. the thing is I know they all have ... | grep prefix python strings | I'm having problems using findall in python.
I have a text such as:
the name of 33e4853h45y45 is one of the 33e445a64b65 and we want all the 33e5c44598e46 to be matched
So i'm trying to find all occurrences of of those alphanumeric strings in the text. the thing is I know they all have the "33e" prefix.
Right now, I h... | [
"try this\n>>> x=\"the name of 33e4853h45y45 is one of the 33e445a64b65 and we want all the 33e5c44598e46 to be matched\"\n>>> re.findall(\"33e\\w+\",x)\n['33e4853h45y45', '33e445a64b65', '33e5c44598e46']\n\n",
"Here's a slight variation:\n>>> string = '''the name of 33e4853h45y45 is one of the 33e445a64b65 and w... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0008435805_python.txt |
Q:
Creating infinity and negative infinity in python for any object
I'm working on a library that implements a data structure that works with any ordered data type--a rangeset. Many of the operations (like inversion) get interesting when you allow for positive and negative infinity.
One goal is to get datetime object... | Creating infinity and negative infinity in python for any object | I'm working on a library that implements a data structure that works with any ordered data type--a rangeset. Many of the operations (like inversion) get interesting when you allow for positive and negative infinity.
One goal is to get datetime objects to work with this module, and in supporting infinity with non-numeri... | [
"from the docs \n\nIn order to stop comparison from falling back to the default scheme of\n comparing object addresses, date comparison normally raises TypeError\n if the other comparand isn’t also a date object. However,\n NotImplemented is returned instead if the other comparand has a\n timetuple() attribute.... | [
5,
0,
0
] | [] | [] | [
"comparison",
"magic_methods",
"python"
] | stackoverflow_0008435193_comparison_magic_methods_python.txt |
Q:
pyQt4 QTabWidget setMovable crashes with custom QTabBar
I'm trying to make a tab widget with a custom tab bar movable. The program works fine if I don't subclass QTabBar and setMovable(True) but I need to access the mouseDoubleClickEvent that QTabBar offers thus the sub classing. When you run the program everyth... | pyQt4 QTabWidget setMovable crashes with custom QTabBar | I'm trying to make a tab widget with a custom tab bar movable. The program works fine if I don't subclass QTabBar and setMovable(True) but I need to access the mouseDoubleClickEvent that QTabBar offers thus the sub classing. When you run the program everything works until the point you try and move a tab with the mou... | [
"Use the QTabWidget.addTab method to add tabs, and make sure you associate a widget with each tab:\nclass CTabWidget(QTabWidget):\n def __init__(self, parent=None):\n super(CTabWidget, self).__init__(parent)\n self.tabBar = CTabBar(self)\n self.setTabBar(self.tabBar)\n self.setTabPosi... | [
1
] | [] | [] | [
"pyqt",
"pyqt4",
"python",
"qt",
"qtabwidget"
] | stackoverflow_0008435483_pyqt_pyqt4_python_qt_qtabwidget.txt |
Q:
How to check for a string format in python?
I would like to check for string "tDDDDD" where D has to be digits and should not be more than the length (minimum 4, maximum 5) of it.
No other characters allowed.
Currently my code checks like this,
m = re.match('^(t)(\d+)', changectx.branch())
But is also allows t12... | How to check for a string format in python? | I would like to check for string "tDDDDD" where D has to be digits and should not be more than the length (minimum 4, maximum 5) of it.
No other characters allowed.
Currently my code checks like this,
m = re.match('^(t)(\d+)', changectx.branch())
But is also allows t12345anythingafterit.
I changed the regular express... | [
"Your regular expression will work, but you could also use this regular expression:\nr'^t\\d{4,5}$'\n\nThe {4,5} is a quantifier that means the previous token must occur between 4 and 5 times.\nThe parentheses are only necessary here if you wish to capture the matching parts of the string.\n",
"how about this reg... | [
7,
2,
1,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0008436142_python_regex.txt |
Q:
Python Regex: Ignore Escaped Character
Alright, I'm currently using Python's regular expression library to split up the following string into groups of semicolon delimited fields.
'key1:"this is a test phrase"; key2:"this is another test phrase"; key3:"ok this is a gotcha\; but you should get it";'
Regex: \s*([^;... | Python Regex: Ignore Escaped Character | Alright, I'm currently using Python's regular expression library to split up the following string into groups of semicolon delimited fields.
'key1:"this is a test phrase"; key2:"this is another test phrase"; key3:"ok this is a gotcha\; but you should get it";'
Regex: \s*([^;]+[^\\])\s*;
I'm currently using the pcre ab... | [
"The basic version of this is where you want to ignore any ; that's preceded by a backslash, regardless of anything else. That's relatively simple:\n\\s*([^;]*[^;\\\\]);\n\nWhat will make this tricky is if you want escaped backslashes in the input to be treated as literals. For example:\n\"You may want to split her... | [
2,
1
] | [] | [] | [
"pcre",
"python",
"regex"
] | stackoverflow_0008435368_pcre_python_regex.txt |
Q:
Python on Windows Phone?
Can I execute Python on Windows Phone? I have heard about IronPython but is it the way to go when I need to compile to a lot of existing Python code for Windows Mobile?
A:
Only (some) mananged .net languages are supported on Windows Phone (note. this is not the same as Windows Mobile).
I... | Python on Windows Phone? | Can I execute Python on Windows Phone? I have heard about IronPython but is it the way to go when I need to compile to a lot of existing Python code for Windows Mobile?
| [
"Only (some) mananged .net languages are supported on Windows Phone (note. this is not the same as Windows Mobile).\nIronPython is the only option available to you when it comes to executing python code on the phone.\n"
] | [
2
] | [] | [] | [
".net",
"python",
"windows_phone_7"
] | stackoverflow_0008436112_.net_python_windows_phone_7.txt |
Q:
Send Values to BaseHTTPRequestHandler
I am creating a simple web server using HTTPServer and BaseHTTPRequestHandler in Python. Here is what I have so far:
from handler import Handler #my BaseHTTPRequestHandler
def run(self):
httpd = HTTPServer(('', 7214), Handler)
try:
httpd.serve_forever()
ex... | Send Values to BaseHTTPRequestHandler | I am creating a simple web server using HTTPServer and BaseHTTPRequestHandler in Python. Here is what I have so far:
from handler import Handler #my BaseHTTPRequestHandler
def run(self):
httpd = HTTPServer(('', 7214), Handler)
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
ht... | [
"Since no one wanted to answer your question...\nJust replace the part in the code with the comment \"yourpath\".\nimport os\nimport posixpath\nimport socket\nimport urllib\nfrom BaseHTTPServer import HTTPServer\nfrom SimpleHTTPServer import SimpleHTTPRequestHandler\n\n\nclass MyFileHandler(SimpleHTTPRequestHandler... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0008405764_python.txt |
Q:
How to import modules from alternate locations when using Python IDLE?
I've been trying to figure this out for more than 2 days, screening the internet and the tutorial, but yet I don't have solved my problem. I'm a real newb and don't yet really know what I'm doing..
Software I use:
Mac OS X 10.6
Python v3.2.2
I... | How to import modules from alternate locations when using Python IDLE? | I've been trying to figure this out for more than 2 days, screening the internet and the tutorial, but yet I don't have solved my problem. I'm a real newb and don't yet really know what I'm doing..
Software I use:
Mac OS X 10.6
Python v3.2.2
Interactive interpreter (IDLE)
Problem:
IDLE's default directory is /Users/ME... | [
"It's not totally clear to me what you mean by load. That could mean Open and Close files in the IDLE editor. Or it could mean being able to use the Python import statement to load existing Python modules from other files. I'll assume the latter, that by load you mean import.\nThere are two general ways to launc... | [
7,
0
] | [] | [] | [
"macos",
"python",
"python_idle",
"pythonpath"
] | stackoverflow_0008432820_macos_python_python_idle_pythonpath.txt |
Q:
How to fit powerlaw to a histogram with matplotlib
I am trying to fit a power law to a histogram (more exact Pareto distribution). I did it with my own function, where I check for smallest sum of squares of difference. But this means I need to loop threw all the coefitients, which can take some time. Another probl... | How to fit powerlaw to a histogram with matplotlib | I am trying to fit a power law to a histogram (more exact Pareto distribution). I did it with my own function, where I check for smallest sum of squares of difference. But this means I need to loop threw all the coefitients, which can take some time. Another problem is that I need to make my own data list so that I hav... | [
"I think you are looking for the values and the bin sizes.\nThe matplotlib.pyplot.hist() function returns a tupe with (n, bins, patches)\nFor more information about this function click this link\nFor example to plot some 'data', 150 bins:\nimport matplotlib.pyplot as plt\nhist = plt.hist(data,150)\nbinsize = hist[0... | [
3
] | [] | [] | [
"curve_fitting",
"power_law",
"python"
] | stackoverflow_0008050699_curve_fitting_power_law_python.txt |
Q:
Regular expression to extract URLs with difficult formatting
My question is similar to this one, but more complicated.
I am trying to figure out a regex to extract URLs from a text document. The tricky thing is that some of the URLs are embedded in sentences with harder to parse formatting. Here's an example of te... | Regular expression to extract URLs with difficult formatting | My question is similar to this one, but more complicated.
I am trying to figure out a regex to extract URLs from a text document. The tricky thing is that some of the URLs are embedded in sentences with harder to parse formatting. Here's an example of text I would like to extract URLs from:
<p>There are several links o... | [
"You can forbid period as the last symbol like that:\nm = re.findall(\"((http:|https:)//[^ \\<]*[^ \\<\\.])\",line)\n\n"
] | [
3
] | [] | [] | [
"hyperlink",
"python",
"regex",
"url"
] | stackoverflow_0008436818_hyperlink_python_regex_url.txt |
Q:
Debugging trick when working with lists
I came accross this snippet:
li = ['a', 'b', 'c']
print "\n".join(li)
The author says:
This is also a useful debugging trick when you're working with lists.
What is the trick here?
source
A:
The "trick" is printing each of the elements of a list in separate lines, that'... | Debugging trick when working with lists | I came accross this snippet:
li = ['a', 'b', 'c']
print "\n".join(li)
The author says:
This is also a useful debugging trick when you're working with lists.
What is the trick here?
source
| [
"The \"trick\" is printing each of the elements of a list in separate lines, that's all.\n",
"The \"trick\" is that \"\\n\".join(li) takes less time to write all the elements of li on the display than the following code:\nfor x in li:\n print li\n\nIf li has few elements, the difference isn't really perceived.... | [
2,
1,
1
] | [] | [] | [
"debugging",
"list",
"python"
] | stackoverflow_0008436373_debugging_list_python.txt |
Q:
PyQt4 : Drag and Drop in QTreeView
I make a UI with PyQt4. It has a treeView and I want to deal with it.
The treeView is made up with model-base. I create a data in .py file and import it.
So, I can see the data tree in my treeView.
But I can't drag and drop it, so can't change the order.
I referred some articles ... | PyQt4 : Drag and Drop in QTreeView | I make a UI with PyQt4. It has a treeView and I want to deal with it.
The treeView is made up with model-base. I create a data in .py file and import it.
So, I can see the data tree in my treeView.
But I can't drag and drop it, so can't change the order.
I referred some articles so add it in my script, but they couldn'... | [
"The QTreeView.dragMoveEvent and QTreeView.dragEnterEvent methods both check the object returned by event.mimeData() to see if it can return data for any of the formats supported by the model (i.e. those returned by model.mimeTypes()).\nBut your PyMimeData subclass doesn't support any formats, because it never succ... | [
2
] | [] | [] | [
"drag_and_drop",
"pyqt",
"python",
"qtreeview"
] | stackoverflow_0008409139_drag_and_drop_pyqt_python_qtreeview.txt |
Q:
mpylayer, PyQt4 and lineEdit
Consider the minimal example below. It works perfectly until I uncomment the following lines:
# self.mainwi = QtGui.QWidget(self)
# self.lineEdit1 = QtGui.QLineEdit(self.mainwi)
# self.setCentralWidget(self.lineEdit1)
If those lines are uncommented, I can write text in the LineE... | mpylayer, PyQt4 and lineEdit | Consider the minimal example below. It works perfectly until I uncomment the following lines:
# self.mainwi = QtGui.QWidget(self)
# self.lineEdit1 = QtGui.QLineEdit(self.mainwi)
# self.setCentralWidget(self.lineEdit1)
If those lines are uncommented, I can write text in the LineEdit-field, but the buttons don't r... | [
"You do not need the mainwi at all in this simple example. Just do\nself.lineEdit1 = QtGui.QLineEdit(self)\nself.setCentralWidget(self.lineEdit1)\n\nIn case you really wanted it, then you need to set the mainwi as the centralwidget\nself.mainwi = QtGui.QWidget(self)\nself.lineEdit1 = QtGui.QLineEdit(self.mainwi)\ns... | [
2
] | [] | [] | [
"mplayer",
"pyqt4",
"python"
] | stackoverflow_0008436212_mplayer_pyqt4_python.txt |
Q:
Qt / PyQt: Low level text rendering
[Note: I prefer PyQt, but an answer for Qt is the same as far as I am concerned. I understand both languages.]
Question:
I would like to render a string, for example: 'Hello world!' (nothing fancy). I DO NOT want to do this through a proxy, such as QTextEdit or QWebKit. Rather, ... | Qt / PyQt: Low level text rendering | [Note: I prefer PyQt, but an answer for Qt is the same as far as I am concerned. I understand both languages.]
Question:
I would like to render a string, for example: 'Hello world!' (nothing fancy). I DO NOT want to do this through a proxy, such as QTextEdit or QWebKit. Rather, I want full control of the rendering on a... | [
"Implementing a custom QWidget by overloading the QWidget::paintEvent and using a painter is about the lowest level in Qt using the widget system.\nHere is a full working example using C++ I've put together for you, I don't know PyQt but hopefully you can port this!\nwidget.h\n#ifndef _WIDGET_H_\n#define _WIDGET_H_... | [
1
] | [] | [] | [
"pyqt",
"python",
"qt",
"rendering",
"text"
] | stackoverflow_0008429834_pyqt_python_qt_rendering_text.txt |
Q:
how to setup android-scripting + python on Android phones?
I've downloaded the latest available version of python interpreter here. Now, how can i start scripting in python on my phone? The apk (r4) that i've installed is has not any other option than download python interpreter and browse modules.
any help? What'... | how to setup android-scripting + python on Android phones? | I've downloaded the latest available version of python interpreter here. Now, how can i start scripting in python on my phone? The apk (r4) that i've installed is has not any other option than download python interpreter and browse modules.
any help? What's next?
| [
"refer here or here or to this popular question on stackoverflow.\n",
"Okay, now I figured out what i was doing wrong. On the user guide they didn't mention to download the this file before install the interpreter. They presume that the user has it installed and give you the link only for the interpreter, as you ... | [
0,
0
] | [] | [] | [
"android",
"android_scripting",
"python"
] | stackoverflow_0008436386_android_android_scripting_python.txt |
Q:
extracting data from a dictionary
I have two tab delimited files, file 1 contains identifiers and file 2 has values related to these identifiers (or say it is a very big dictionary).
file 1
Ronny
Rubby
Suzie
Paul
file 1 has only one column.
file 2
Alistar Barm Cathy Paul Ronny Rubby Suzie Tom Uma Vai Zai
12 ... | extracting data from a dictionary | I have two tab delimited files, file 1 contains identifiers and file 2 has values related to these identifiers (or say it is a very big dictionary).
file 1
Ronny
Rubby
Suzie
Paul
file 1 has only one column.
file 2
Alistar Barm Cathy Paul Ronny Rubby Suzie Tom Uma Vai Zai
12 13 14 12 11 11 12 23 ... | [
"NOTE\nyour example output is NOT correct, since there you have \"Ruby\" but in your file1 example you had \"Rubby\" Ruby =/= Rubby\nkent$ awk 'NR==FNR{t[$0]++;next}\n{if(FNR==1){\n for(i=1;i<=NF;i++)\n if($i in t){\n v[i]++;\n printf $i\"\\t\";... | [
4,
2,
2,
1,
1,
1,
1
] | [] | [] | [
"bash",
"perl",
"python",
"shell"
] | stackoverflow_0008431917_bash_perl_python_shell.txt |
Q:
sorting data that is read in from file
I have a python question, but i think any programer would know enough to send me in the right direction.I have found some really good code for sorting data. Here is an example of one i want to use:
from operator import itemgetter, attrgetter
data = [('red', 1,80), ('blue', 1... | sorting data that is read in from file | I have a python question, but i think any programer would know enough to send me in the right direction.I have found some really good code for sorting data. Here is an example of one i want to use:
from operator import itemgetter, attrgetter
data = [('red', 1,80), ('blue', 1,900), ('red', 2,50), ('blue', 2,300)]
ss=s... | [
"I think you just want to convert it into a list of tuples, before sorting, right? You can do this by using the zip function:\nl = zip(name, idc, startD, ...)\nl.sort(key=...)\n\nbut I do not understand why you do not sort the rows as they are straight away...\nl = []\nfor name, idc, ... in reader:\n if name != ... | [
1
] | [] | [] | [
"python",
"sorting"
] | stackoverflow_0008431759_python_sorting.txt |
Q:
Compile (but do not run) a Python script
Possible Duplicate:
How can I check the syntax of Python script without executing it?
How do I compile a Python script without running it? I just want to check the script for syntax errors. I was hoping for a simple command line switch, but I didn't see anything in pyth... | Compile (but do not run) a Python script |
Possible Duplicate:
How can I check the syntax of Python script without executing it?
How do I compile a Python script without running it? I just want to check the script for syntax errors. I was hoping for a simple command line switch, but I didn't see anything in python --help. I'd like an answer for both Pytho... | [
"python -m py_compile script.py\n\n",
"py_compile — Compile Python source files\nimport py_compile\npy_compile.compile('my_script.py')\n\n",
"You can use pylint to find syntax errors as well as more subtle errors, such as accessing undefined variables in some rarely-used conditional branch.\n",
"One way is to... | [
394,
54,
17,
8
] | [] | [] | [
"python",
"syntax_checking"
] | stackoverflow_0004537411_python_syntax_checking.txt |
Q:
Modify a large list without any loops in python
My list is:
a=[1,2,3,4]
Now I want my list to be:
a=[-1,-2,-3,-4]
How can I change my list this way without using any loops?
Update: this may be a large list, on the order of 10000 elements.
A:
Use Python's map functionality
a[:] = map(lambda x: -x, a)
Here's th... | Modify a large list without any loops in python | My list is:
a=[1,2,3,4]
Now I want my list to be:
a=[-1,-2,-3,-4]
How can I change my list this way without using any loops?
Update: this may be a large list, on the order of 10000 elements.
| [
"Use Python's map functionality\na[:] = map(lambda x: -x, a)\n\nHere's the description of the map function from the above link:\n\nmap(function, iterable, ...)\n Apply function to every item of iterable and return a list of the\n results. If additional iterable arguments are passed, function must\n take that man... | [
14,
9,
4,
3,
3,
1,
1,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0008437024_list_python.txt |
Q:
Best solution to get and store user's real time position?
Hi I'm writing an Android lbs game, I need to:
store user's real time position(lat, lon)
get users that are near to a given position
I've wrote some back-end api with django and mysql(for example, get user name and age by his id).
what's the best ... | Best solution to get and store user's real time position? | Hi I'm writing an Android lbs game, I need to:
store user's real time position(lat, lon)
get users that are near to a given position
I've wrote some back-end api with django and mysql(for example, get user name and age by his id).
what's the best solution to do what I said above (with django/python)?
Should I... | [
"Well, I am a enthusiast of Redis, but considering your specific problem, there is a NoSQL database engine that better supports geospatial queries: MongoDB.\nI have never used MongoDB, but in conferences I've seen people talking about this feature: http://www.mongodb.org/display/DOCS/Geospatial+Indexing\nI read thr... | [
2,
1
] | [] | [] | [
"django",
"nosql",
"python",
"redis"
] | stackoverflow_0008432460_django_nosql_python_redis.txt |
Q:
How do you to post a diff to ReviewBoard through its API?
I have been struggling to post a diff to ReviewBoard through their API. I've managed to login to the server and create a new post, but I've failed to post correctly the contents of the diff file.
I'm new to writing this kind of application, but my goal is ... | How do you to post a diff to ReviewBoard through its API? | I have been struggling to post a diff to ReviewBoard through their API. I've managed to login to the server and create a new post, but I've failed to post correctly the contents of the diff file.
I'm new to writing this kind of application, but my goal is to have a one step script to:
diff a file (pre-commit) with th... | [
"Reviewboard have already a python tool for posting diff with their API, it's called postreview.py. You can found it at : \nhttp://reviewboard.googlecode.com/svn/trunk/wxpostreview/postreview.py\nGrab and use their ReviewBoardServer for login and post a diff !\n(In addition, in your request, the authentification is... | [
2
] | [] | [] | [
"http",
"python",
"review_board"
] | stackoverflow_0008190275_http_python_review_board.txt |
Q:
Python: How to handle method calls on a class that could not initialize correctly?
If an object relies on a module that is not included with Python (like win32api, gstreamer, gui toolkits, etc.), and a class/function/method from that module may fail, what should the object do?
Here's an example:
import guimodule ... | Python: How to handle method calls on a class that could not initialize correctly? | If an object relies on a module that is not included with Python (like win32api, gstreamer, gui toolkits, etc.), and a class/function/method from that module may fail, what should the object do?
Here's an example:
import guimodule # Just an example; could be anything
class RandomWindow(object):
def __init__(self... | [
"Rather than creating an invalid object, you should have allowed the exception raised in __init__ to propogate out so the error could be handled in an appropriate manner. Or you could have raised a different exception.\nSee also Python: is it bad form to raise exceptions within __init__?\n",
"You may find it usef... | [
3,
1,
0,
0
] | [] | [] | [
"coding_style",
"module",
"oop",
"python",
"refactoring"
] | stackoverflow_0008437811_coding_style_module_oop_python_refactoring.txt |
Q:
High performance computing projects using Python
For a paper I want to argue why I have used Python for the implementation of my algorithm. Besides the typical arguments that it is fast -using suitable libraries- and it is easy to implement the algorithm with it, I thought maybe there are some big HPC projects tha... | High performance computing projects using Python | For a paper I want to argue why I have used Python for the implementation of my algorithm. Besides the typical arguments that it is fast -using suitable libraries- and it is easy to implement the algorithm with it, I thought maybe there are some big HPC projects that are using it.
Does anyone know a famous project tha... | [
"To be honest, as great a language as python is, it wouldn't be a suitable environment for scientific computing and in particular high performance computing, if those libraries weren't available. So you can see python as one pieces of a larger puzzle - much as MATLAB can be. \nThe two key reasons to use python for ... | [
2,
1,
0
] | [] | [] | [
"hpc",
"parallel_processing",
"python"
] | stackoverflow_0008437220_hpc_parallel_processing_python.txt |
Q:
Non blocking python sockets
I'd like to write a small Bluetooth server application to my Nokia phone in PyS60. It needs to be able to send response to the client's request and be able to push data to the client as well.
option 1:
if I use socket.recv(1024), the program waits until something is received, therefore ... | Non blocking python sockets | I'd like to write a small Bluetooth server application to my Nokia phone in PyS60. It needs to be able to send response to the client's request and be able to push data to the client as well.
option 1:
if I use socket.recv(1024), the program waits until something is received, therefore the server can't push data to the... | [
"Found the solution finally!\nThe select function wasn't working with the btsocket module of the newer PyS60 ports.\nSomeone wrote a new_btsocket (available here) with a working select function.\n",
"Here is a simple example based on an echo server\n#!/usr/bin/python ... | [
3,
1,
0
] | [] | [] | [
"pys60",
"python",
"sockets"
] | stackoverflow_0008404704_pys60_python_sockets.txt |
Q:
Colorbar does not show values when using LogNorm()
I am trying to make a contour plot with the contour levels scaled by the log of the values. However, the colorbar does not show enough values next to the colors. Here is a simple example.
import numpy as N
import matplotlib as M
import matplotlib.pyplot as PLT
# ... | Colorbar does not show values when using LogNorm() | I am trying to make a contour plot with the contour levels scaled by the log of the values. However, the colorbar does not show enough values next to the colors. Here is a simple example.
import numpy as N
import matplotlib as M
import matplotlib.pyplot as PLT
# Set up a simple function to plot
values = N.empty((10,1... | [
"Add a format to the call to PLT.colorbar:\nimport numpy as N\nimport matplotlib as M\nimport matplotlib.pyplot as PLT\n\n# Set up a simple function to plot \nx,y = N.meshgrid(range(10),range(10))\nvalues = N.exp(x*y/10. - 1)\n\nlevels = N.logspace(-1, 4, 10)\nlog_norm = M.colors.LogNorm() \n# Currently not used - ... | [
5
] | [] | [] | [
"colorbar",
"contour",
"matplotlib",
"numpy",
"python"
] | stackoverflow_0008438010_colorbar_contour_matplotlib_numpy_python.txt |
Q:
Push notification from python to iPhone, how to debug?
How do one debug the connection from a provider to Apple push notification server?
I'm using a library called PyAPNs (github repo) and have the code below:
from apns import APNs, Payload
print "start"
apns = APNs(use_sandbox=True, cert_file='apns-prod.pem', ... | Push notification from python to iPhone, how to debug? | How do one debug the connection from a provider to Apple push notification server?
I'm using a library called PyAPNs (github repo) and have the code below:
from apns import APNs, Payload
print "start"
apns = APNs(use_sandbox=True, cert_file='apns-prod.pem', key_file='apns-prod.pem')
# Send a notification
token_hex =... | [
"USE THIS CODE:\n#!/usr/bin/python2.7\n\nimport socket\nimport ssl\nimport json\nimport struct\nimport argparse\n\n\n\nAPNS_HOST = ( 'gateway.sandbox.push.apple.com', 2195 )\n\n\nclass Payload:\n PAYLOAD = '{\"aps\":{${MESSAGE}${BADGE}${SOUND}}}'\n def __init__(self):\n pass\n\n def set_message(self... | [
1
] | [] | [] | [
"iphone",
"push_notification",
"python"
] | stackoverflow_0007010949_iphone_push_notification_python.txt |
Q:
When I write a python script to run Devenv with configure "Debug|Win32" it does nothing
Update: When I use the subprocess.call instead of subprocess.Popen, the problem is solved - does anybody know what's the cause? And there came another problem: I can't seem to find a way to control the output... Is there a way ... | When I write a python script to run Devenv with configure "Debug|Win32" it does nothing | Update: When I use the subprocess.call instead of subprocess.Popen, the problem is solved - does anybody know what's the cause? And there came another problem: I can't seem to find a way to control the output... Is there a way to redirect the output from subprocess.call to a string or something like that? Thanks!
I'm t... | [
"There is a difference between devenv.exe and devenv.com, both of which are executable and live in the same directory (sigh). The command lines used in the question and some answers don't say which they want so I'm not sure which will get used.\nIf you want to call from the command line then you need to ensure you ... | [
5,
1,
0,
0,
0
] | [] | [] | [
"python",
"subprocess"
] | stackoverflow_0001049784_python_subprocess.txt |
Q:
Python Regular Expression- Selecting value based on surounding patterns
I have scraped a webpage using Scrapy and need to extract the background color from certain objects. Because inline-css is not part of the DOM, or so I have read, I need to create a regex that will augment my current XPath and select the neede... | Python Regular Expression- Selecting value based on surounding patterns | I have scraped a webpage using Scrapy and need to extract the background color from certain objects. Because inline-css is not part of the DOM, or so I have read, I need to create a regex that will augment my current XPath and select the needed value within an object's style attribute. My current XPath returns the enti... | [
"The following regex should do what you want, the stuff you want to grab will be in the first capture group:\nbackground:(.*?);\n\nIn Python\nbackground = re.search(r'background:(.*?);', some_string).group(1)\n\n. matches any character, * means repeat the previous element any number of times, and the ? makes it a l... | [
3
] | [] | [] | [
"python",
"regex",
"scrapy"
] | stackoverflow_0008438454_python_regex_scrapy.txt |
Q:
Example where lambdas are very useful in Python
I met lambda expressions in Python. I have seen already many easy examples (including examples on SE) where lambda expressions produce functions like adders of whatever but I can't see the real usefulness of them yet, e.g. some example where it would be pain to write... | Example where lambdas are very useful in Python | I met lambda expressions in Python. I have seen already many easy examples (including examples on SE) where lambda expressions produce functions like adders of whatever but I can't see the real usefulness of them yet, e.g. some example where it would be pain to write the same peace of code without lambdas.
Could you sh... | [
"IN this case, it would have been painful to write out all lambda expressions as separate function. \nWhat does this code does in briefly? Converts a custom excel table into insert statements for a custom database table. There is mapping between the excel table fields and the database fields and also there is a map... | [
5,
4,
2,
1,
0,
0,
0
] | [] | [] | [
"functional_programming",
"lambda",
"python"
] | stackoverflow_0008434838_functional_programming_lambda_python.txt |
Q:
Script to compare a string in two different files
I am brand new to stackoverflow and to scripting. I was looking for help to get started in a script, not necessarily looking for someone to write it.
Here's what I have:
File1.csv - contains some information, I am only interested in MAC addresses.
File2.csv - has ... | Script to compare a string in two different files | I am brand new to stackoverflow and to scripting. I was looking for help to get started in a script, not necessarily looking for someone to write it.
Here's what I have:
File1.csv - contains some information, I am only interested in MAC addresses.
File2.csv - has some different information, but also contains MAC addre... | [
"Here's the approach I'd take:\n\nIterate over each csv file (python has a handy csv module for accomplishing this), capturing the mac-address and placing it in a set (one per file). And once again, python has a great builtin set type. Here's a good example of using the csv module and of-course, the docs.\nNext, ... | [
5,
1,
1,
1
] | [] | [] | [
"bash",
"perl",
"python"
] | stackoverflow_0008435912_bash_perl_python.txt |
Q:
python replace \r\n in elements of array
I have a list. one element is a large string containing \r\n. I want to remove it so that when I write elements to a new file a new line will begin when new list is written into it.
Somehow replace("\r\n",""), does not work.
For example:
['1','Smth\r\nmoretext']
This has t... | python replace \r\n in elements of array | I have a list. one element is a large string containing \r\n. I want to remove it so that when I write elements to a new file a new line will begin when new list is written into it.
Somehow replace("\r\n",""), does not work.
For example:
['1','Smth\r\nmoretext']
This has to be in a new file:
1,smthmoretext
Thank yo... | [
"You can use list comprehensions to do an operation on each element in a list, and put the results in a new list.\nitems = ['abc', 'abc\\r\\ndef', 'foo\\r\\n bar\\r\\n']\nnewItems = [s.replace('\\r\\n', '') for s in items]\nprint newItems\n# ['abc', 'abcdef', 'foo bar']\n\n",
"What's wrong with replace? How do yo... | [
4,
1,
1,
1
] | [] | [] | [
"arrays",
"element",
"python",
"replace"
] | stackoverflow_0008438334_arrays_element_python_replace.txt |
Q:
Google apps login in django
I'm developing a django app that integrates with google apps. I'd like to let the users login with their google apps accounts (accounts in google hosted domains, not google accounts) so they can access their docs, calendar, and whatnot.
In order to do it, I downloaded and started using ... | Google apps login in django | I'm developing a django app that integrates with google apps. I'd like to let the users login with their google apps accounts (accounts in google hosted domains, not google accounts) so they can access their docs, calendar, and whatnot.
In order to do it, I downloaded and started using django_openid_auth (and thus, pyt... | [
"According to http://groups.google.com/group/google-federated-login-api/web/openid-discovery-for-hosted-domains, Google changed the way of IdP Discovery and user XRDS check a little bit to give Google Apps users openid in http://example.com/openid?id=108441225163454056756 kind of format without asking the users to ... | [
8,
1
] | [] | [] | [
"django",
"django_openid_auth",
"google_apps",
"python"
] | stackoverflow_0002313573_django_django_openid_auth_google_apps_python.txt |
Q:
Path location of rbenv and MacPorts
I have been using python for months & I have python & git installed on a Mac via MacPorts in bash_login @ export PATH="opt/local/bin:/opt/local/bin/mysql5/bin:/opt/local/lib/postgresql90/bin:/usr/local/bin:/usr/local/sbin:$PATH"
Today I wanted to try ruby so I installed Rbenv & ... | Path location of rbenv and MacPorts | I have been using python for months & I have python & git installed on a Mac via MacPorts in bash_login @ export PATH="opt/local/bin:/opt/local/bin/mysql5/bin:/opt/local/lib/postgresql90/bin:/usr/local/bin:/usr/local/sbin:$PATH"
Today I wanted to try ruby so I installed Rbenv & ruby 1.9.2-p290 via ruby-build. It create... | [
"You should consolidate all paths in your bash_profile file. The macports path and rbenv are distinct and can be pulled together without conflict of order.\nI use both Macports, Python and Rbenv & Ruby.\nMy consolidated path looks like this:\n/Users/user1/.rvm/gems/ruby-1.9.2-p290/bin:\n/Users/user1/.rvm/gems/ruby-... | [
1
] | [] | [] | [
"macports",
"python",
"rbenv",
"ruby",
"unix"
] | stackoverflow_0008438710_macports_python_rbenv_ruby_unix.txt |
Q:
Can an abstract class force the inheriting class to implement a method as static?
Python 3.2 in case that matters...
The following code shows that the "concrete class" can either implement some_method as a static method or an instance method:
import abc
class SomeAbstractClass(metaclass=abc.ABCMeta):
@abc.ab... | Can an abstract class force the inheriting class to implement a method as static? | Python 3.2 in case that matters...
The following code shows that the "concrete class" can either implement some_method as a static method or an instance method:
import abc
class SomeAbstractClass(metaclass=abc.ABCMeta):
@abc.abstractmethod
def some_method(self): pass
class ValidConcreteClass1(SomeAbstractCla... | [
"I think some clarification is needed;\nFirst, in Python every method is virtual - really virtual; so whether a method is static, or bound to a class or instance, that's a matter of the subclass, not of the parent one. You don't have a real reason for wanting to prevent that - what's your purpose?\nSecond, ABCs che... | [
2
] | [] | [] | [
"abstract_class",
"python"
] | stackoverflow_0008437792_abstract_class_python.txt |
Q:
How to properly parse request strings with Twisted (python)
I am trying to implement a simple twisted HTTP server which would respond to requests for loading tiles from a database and return them. However I find that the way it interprets request strings quite odd.
This is what I POST to the server:
curl -d "reque... | How to properly parse request strings with Twisted (python) | I am trying to implement a simple twisted HTTP server which would respond to requests for loading tiles from a database and return them. However I find that the way it interprets request strings quite odd.
This is what I POST to the server:
curl -d "request=loadTiles&grid[0][x]=17&grid[0][y]=185&grid[1][x]=18&grid[1][y... | [
"I don't know why you would expect your urlencoded data to be decoded according to some ad-hoc non-standard rules, or why you would consider the standard treatment \"odd\"; [ isn't special in query strings. What software decodes them this way?\nIn any event, this isn't really Twisted, but Python (and more generall... | [
4,
1
] | [] | [] | [
"arrays",
"parsing",
"python",
"request",
"twisted"
] | stackoverflow_0008438179_arrays_parsing_python_request_twisted.txt |
Q:
Django 3rd Party Auth Systems
I am considering a 3rd part Authentication system for logging in (new/old) users. Much like how StackOverflow authenticates it's users. This scheme is good as it frees me from doing authentication from my side. I need this -
Login using Google, Facebook, Twitter, Yahoo, OpenID Authen... | Django 3rd Party Auth Systems | I am considering a 3rd part Authentication system for logging in (new/old) users. Much like how StackOverflow authenticates it's users. This scheme is good as it frees me from doing authentication from my side. I need this -
Login using Google, Facebook, Twitter, Yahoo, OpenID Authentication Systems.
Provide the same ... | [
"For an all-in-one solution, I had good results with django-socialregistration. It has auth backends for Twitter, Facebook and OpenID (Google, Yahoo!, ...).\nAnother possibility would be JanRain Engage (formerly RPX) which provides a single point of authentication for all the major authentication providers. There's... | [
5,
1,
0
] | [] | [] | [
"django",
"django_authentication",
"python"
] | stackoverflow_0003788631_django_django_authentication_python.txt |
Q:
Redirect all url request to one handler
In a Google App Engine application with google webapp framework, how do I redirect every request to one handler?
Check this code:
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
class MainPage(webapp.RequestHandler):
def... | Redirect all url request to one handler | In a Google App Engine application with google webapp framework, how do I redirect every request to one handler?
Check this code:
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
class MainPage(webapp.RequestHandler):
def get(self):
self.response.headers['Co... | [
"application = webapp.WSGIApplication([('/.*', MainPage)], ...\n"
] | [
5
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0008439016_google_app_engine_python.txt |
Q:
iterating in a dictionary.. (double iteration) python
I have a dictionary
example: A = {1:'one',2:'two' , 3: 'three}
so what I want is basically like a 2 for loops sort of stuff..
so that I can get the following order..
# 1 2
# 1 3
# 2 3
... and so on if more elements are there
so basically that o(n2) operation... | iterating in a dictionary.. (double iteration) python | I have a dictionary
example: A = {1:'one',2:'two' , 3: 'three}
so what I want is basically like a 2 for loops sort of stuff..
so that I can get the following order..
# 1 2
# 1 3
# 2 3
... and so on if more elements are there
so basically that o(n2) operation.. where we have a loop withing a loop
how do we achieve th... | [
">>> import itertools\n>>> list(itertools.combinations([1, 2, 3], 2))\n[(1, 2), (1, 3), (2, 3)]\n\n",
">>> import itertools as it\n>>> A = {1:'one', 2:'two', 3: 'three'}\n>>> list(it.combinations(A.keys(), 2))\n[(1, 2), (1, 3), (2, 3)]\n\n",
"If you need to iterate over all pairs of keys, you can do it with sim... | [
5,
5,
1
] | [] | [] | [
"python"
] | stackoverflow_0008439042_python.txt |
Q:
Python and pubsubhubbub
I wrote a quick http server script to first acknowledge a subscription and receive updates. I was able to verify the subscription and start receiving updates. With this method I'm able to print the updated feed items to the console but google's subscriber diagnostics says the receipt failed... | Python and pubsubhubbub | I wrote a quick http server script to first acknowledge a subscription and receive updates. I was able to verify the subscription and start receiving updates. With this method I'm able to print the updated feed items to the console but google's subscriber diagnostics says the receipt failed.
Shouldn't this be enough?:
... | [
"So it seems with status code 204 it's fine. I guess because I have no body in the response? Anyway, working fine now.\nI'd be greatful to get a comment if someone knows why I needed that particular status code. The spec just says 2xx.\n"
] | [
0
] | [] | [] | [
"python",
"websub"
] | stackoverflow_0008426156_python_websub.txt |
Q:
Multiple threads reading from single folder on Linux
My projects needs multiple threads reading files from the same folder. This folder has incoming files and the file should only be processed by any one of those threads. Later, this file reading thread, deletes the file after processing it.
EDIT after the first a... | Multiple threads reading from single folder on Linux | My projects needs multiple threads reading files from the same folder. This folder has incoming files and the file should only be processed by any one of those threads. Later, this file reading thread, deletes the file after processing it.
EDIT after the first answer: I don't want a single thread in charge of reading f... | [
"You should probably use the Queue module. From the docs:\n\nThe Queue module implements multi-producer, multi-consumer queues. It is especially useful in threaded programming when information must be exchanged safely between multiple threads.\n\nI would use a FIFO approach, with a thread in charge of checking for ... | [
2,
1
] | [] | [] | [
"linux",
"multithreading",
"python"
] | stackoverflow_0008438815_linux_multithreading_python.txt |
Q:
gevent multiple StreamServer listeners
I have daemon which has connection pool to handlerSocket. I have 2 types of clients and their protocol differs. I want to setup 2 listeners which handles each protocol and shares connection pool between them. In twisted this is relatively easy to accomplish, but couldn't find... | gevent multiple StreamServer listeners | I have daemon which has connection pool to handlerSocket. I have 2 types of clients and their protocol differs. I want to setup 2 listeners which handles each protocol and shares connection pool between them. In twisted this is relatively easy to accomplish, but couldn't find out how to do this in gevent.
Thanks!
| [
"first instance of StreamServer could be started with: server.start() and second with server2.serve_forever()\n",
"In addition to frx's answer, here's a class to manage multiple servers: https://gist.github.com/1008826\n",
"I think the problem will come from the StreamServer's stop() method.\nIt kills the pool,... | [
5,
5,
0
] | [] | [] | [
"gevent",
"python"
] | stackoverflow_0005322445_gevent_python.txt |
Q:
In a descriptor, does __call__ have access to the class where the decorator is being used?
Consider the following code:
class MyCustomDescriptor:
def __init__(self,foo):
self._foo = foo
def __call__(self,decorated_method):
# Here's my question... Is there any way to get a reference to the... | In a descriptor, does __call__ have access to the class where the decorator is being used? | Consider the following code:
class MyCustomDescriptor:
def __init__(self,foo):
self._foo = foo
def __call__(self,decorated_method):
# Here's my question... Is there any way to get a reference to the
# type (ClassA or ClassB) here?
return self
def __get__(self,instance,type... | [
"At the point where the decorator is being applied, some_value is just a function, not a method. So, no, there is no way for the function to know it is associated with a particular class.\nTwo alternatives are:\n\nPass the class name to MyCustomDescriptor (along with foo), or\nUse a class decorator to create the de... | [
4,
1
] | [] | [] | [
"decorator",
"python"
] | stackoverflow_0008438987_decorator_python.txt |
Q:
What exactly does "self" do in classes and methods
Possible Duplicate:
python 'self' explained
Ok So programming in python, and just started using classes. Now is it that "self" keeps the information going instead of being passed or taken by the garbage collector?
I searched around and came to some... interestin... | What exactly does "self" do in classes and methods |
Possible Duplicate:
python 'self' explained
Ok So programming in python, and just started using classes. Now is it that "self" keeps the information going instead of being passed or taken by the garbage collector?
I searched around and came to some... interesting things, but I'm not sure if I'm understanding it corr... | [
"The self in Python is equivalent to the this pointer in C++ and the this reference in Java and C#.\n"
] | [
3
] | [] | [] | [
"python"
] | stackoverflow_0008439377_python.txt |
Q:
__getitem__ invocation in for loop
I am learning Python I don't get one thing. Consider this code:
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def __getitem__(self,index):
print "in... | __getitem__ invocation in for loop | I am learning Python I don't get one thing. Consider this code:
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def __getitem__(self,index):
print "index",index
return self.items[inde... | [
"The for loop doesn't know how to iterate over your object specifically because you have not implemented __iter__(), so it uses the default iterator. This starts at index 0 and goes until it gets an IndexError by asking for index 3. See http://effbot.org/zone/python-for-statement.htm.\nYour implementation would be ... | [
14
] | [] | [] | [
"python"
] | stackoverflow_0008439482_python.txt |
Q:
Is it possible to remove a class definition from Python?
Is it possible to remove a class definition from a running instance of Python?
I have a Python interpreter built into my C++ that I'd like to add and remove classes depending on the current state of the application. For example, if I have a Menu hierarchy t... | Is it possible to remove a class definition from Python? | Is it possible to remove a class definition from a running instance of Python?
I have a Python interpreter built into my C++ that I'd like to add and remove classes depending on the current state of the application. For example, if I have a Menu hierarchy that has a corresponding class defined for that menu, I'd like ... | [
"Use del on the reference to the class.\n>>> class Example(object):\n... pass\n... \n>>> Example\n<class '__main__.Example'>\n>>> del Example\n>>> Example\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nNameError: name 'Example' is not defined\n\n"
] | [
10
] | [] | [] | [
"class",
"python"
] | stackoverflow_0008439990_class_python.txt |
Q:
Selelum Headless in Ubuntu Server, minor error "The browser seems to have exited before we could connect"
So I am running Selenium on a Ubuntu Server VM and have a minor issue. When I start-up my VM and run a Selenium test script I get this error: selenium.common.exceptions.WebDriverException: Message: 'The browse... | Selelum Headless in Ubuntu Server, minor error "The browser seems to have exited before we could connect" | So I am running Selenium on a Ubuntu Server VM and have a minor issue. When I start-up my VM and run a Selenium test script I get this error: selenium.common.exceptions.WebDriverException: Message: 'The browser seems to have exited before we could connect'. Now if I execute this export DISPLAY=:99 in the terminal befor... | [
"This isn't going to work:\nos.system(\"export DISPLAY=:99\")\n\nBecause system() starts a new shell and the shell will close when finished, this influences the environment of exactly one process that is very short lived. (Child processes cannot influence the environments of their parents. Parents can only influenc... | [
1
] | [] | [] | [
"headless",
"python",
"selenium",
"ubuntu"
] | stackoverflow_0008439985_headless_python_selenium_ubuntu.txt |
Q:
Programmatically load/unload plugins and change settings in Gedit 3
We are building a plugin for Gedit 3 using python. The idea is to have preset configuration of plugins and configurations that you can load or unload.
The problem is that we cannot seem to find any documentation that is usefull.
Has anyone tried t... | Programmatically load/unload plugins and change settings in Gedit 3 | We are building a plugin for Gedit 3 using python. The idea is to have preset configuration of plugins and configurations that you can load or unload.
The problem is that we cannot seem to find any documentation that is usefull.
Has anyone tried this? Is it doable?
| [
"All settings for gedit and gedit plugins can be modified using GSettings API along with Python introspection (PyGObject). Which plugins are loaded is at the key org.gnome.gedit.plugins.active-plugins. All of the gedit settings and plugin settings are also found under org.gnome.gedit, including some that are not p... | [
3
] | [] | [] | [
"api",
"gedit",
"plugins",
"python"
] | stackoverflow_0008342624_api_gedit_plugins_python.txt |
Q:
noob queries on unicode and str methods in Python
I wish to seek some clarifications on Unicode and str methods in Python. After reading some explanation on Unicode, there are still couple of doubts I hope folks can help me on:
Am I right to say that when declaring a unicode string e.g word=u'foo', python uses th... | noob queries on unicode and str methods in Python | I wish to seek some clarifications on Unicode and str methods in Python. After reading some explanation on Unicode, there are still couple of doubts I hope folks can help me on:
Am I right to say that when declaring a unicode string e.g word=u'foo', python uses the encoding of the terminal and decodes foo in e.g UTF-8... | [
"First we should be clear we are talking about Python 2 only. Python 3 is different.\n\nYou're right. But if you write u\"abcd\" in a py file, the declaration of the encoding of the source file will determine how the interpreter decode you string.\nYou need to decode it first, and then encode it and print. In Pytho... | [
2,
0,
0,
0
] | [] | [] | [
"python",
"unicode"
] | stackoverflow_0008436522_python_unicode.txt |
Q:
How to check for rebase commits in the hook?
Below is my hook for commit message it works fine for all merges and commits which is manually done. When I try to use it with rebase it stop saying
"This branch is only for Merge Commits, cannot commit the code directly here" .
It is directly committing the code to d... | How to check for rebase commits in the hook? | Below is my hook for commit message it works fine for all merges and commits which is manually done. When I try to use it with rebase it stop saying
"This branch is only for Merge Commits, cannot commit the code directly here" .
It is directly committing the code to default. Is that not a merge?
The need of hook is t... | [
"Seems like RebaseExtension manual clearly shows what happens.\nRebase is not merge (not hg merge). If it was, why rebase, why not merge? Actually, in most cases it is closer to using the patch queue to take some revisions from their place and move to another parent. For the revision history it looks like if you've... | [
1
] | [] | [] | [
"hook",
"mercurial",
"python",
"rebase"
] | stackoverflow_0008437649_hook_mercurial_python_rebase.txt |
Q:
stopping a python thread waiting for popen?
I have a thread which calls Popen to get a string back from a command line utility. This command line function does not return until some very, very laggy network data arrives. Sometimes it could take minutes, other times under a second.
If the user wants, they can can... | stopping a python thread waiting for popen? | I have a thread which calls Popen to get a string back from a command line utility. This command line function does not return until some very, very laggy network data arrives. Sometimes it could take minutes, other times under a second.
If the user wants, they can can cancel waiting for this data. In this case, wha... | [
"You can terminate the child process by invoking p.terminate(). This can be done from another thread.\n",
"Use Popen.terminate() here's the document http://docs.python.org/library/subprocess.html\nyou code should be like this:\ndef run(self):\n if self.command is not None:\n self.process = Popen( self.c... | [
3,
2
] | [] | [] | [
"multithreading",
"popen",
"python"
] | stackoverflow_0008440565_multithreading_popen_python.txt |
Q:
psycopg in wrong python - Ubuntu
I'm running Ubuntu. I installed python2.7 and the latest version of Postgresql.
When I installed psycopg, the package showed up in the default Ubuntu version of python instead of the 2.7 version that I want to use.
I tried to reinstall from within the directory I wanted, but it st... | psycopg in wrong python - Ubuntu | I'm running Ubuntu. I installed python2.7 and the latest version of Postgresql.
When I installed psycopg, the package showed up in the default Ubuntu version of python instead of the 2.7 version that I want to use.
I tried to reinstall from within the directory I wanted, but it still referenced the other python. When ... | [
"apt works with the Python it installed in the first place.\nYou need to use easy_install (or, better, pip) to install additional libraries to the Python you installed yourself.\n",
"Jabs, you're going to have to familiarize yourself with installing and configuring projects yourself. Afterwards, the difference be... | [
1,
1
] | [] | [] | [
"psycopg",
"python",
"ubuntu"
] | stackoverflow_0008420212_psycopg_python_ubuntu.txt |
Q:
uploading java application using google app engine java sdk
I am trying to upload java application using google app engine via command line. I have typed email and password correctly but I got an unauthorized error message.
C:\j\bin>appcfg.cmd update facebook/https_www.facebook.com_login.php_login_attem
pt=1/war
R... | uploading java application using google app engine java sdk | I am trying to upload java application using google app engine via command line. I have typed email and password correctly but I got an unauthorized error message.
C:\j\bin>appcfg.cmd update facebook/https_www.facebook.com_login.php_login_attem
pt=1/war
Reading application configuration data...
Dec 10, 2011 2:45:39 AM ... | [
"If you really have an app engine project in a directory named\nfacebook/https_www.facebook.com_login.php_login_attempt=1\n\nthen the first thing I'd try is renaming that to something that doesn't include an =.\n"
] | [
2
] | [] | [] | [
"google_app_engine",
"java",
"python"
] | stackoverflow_0008440823_google_app_engine_java_python.txt |
Q:
About MIT 6.00 course lec06--Newton's method
I have tried to code in my own way, but found I got the wrong answer.
I have read this page. And try to start the process:
f(x)=x^2-e
The math:
So there is my code:
def sqrtRootNR(num, count, epsl):
"""
for test
"""
num = float(num)
guess = num / 2... | About MIT 6.00 course lec06--Newton's method | I have tried to code in my own way, but found I got the wrong answer.
I have read this page. And try to start the process:
f(x)=x^2-e
The math:
So there is my code:
def sqrtRootNR(num, count, epsl):
"""
for test
"""
num = float(num)
guess = num / 2.0
diff = guess ** 2.0 - num
_cnt = 0
... | [
"One important skill in programming is knowing which information where will be most useful. If you add some simple debugging information:\nwhile abs(diff) > epsl and _cnt < count:\n guess = guess - (guess ** 2.0 + epsl) / (guess * 2.0)\n diff = guess ** 2.0 - num\n print guess, _cnt\n _cnt = _cnt +1\npr... | [
6,
2,
1,
1
] | [] | [] | [
"math",
"newtons_method",
"python"
] | stackoverflow_0008440299_math_newtons_method_python.txt |
Q:
C# to Python converter
I have a large C# library that I need to convert to Python. Python is a customer requirement, I can not use any other language.
Any automatic C# to Python converter?
Edit: I need a pure Python solution. .Net is not an option for me.
A:
Assuming IronPython will meet their requirement, Shar... | C# to Python converter | I have a large C# library that I need to convert to Python. Python is a customer requirement, I can not use any other language.
Any automatic C# to Python converter?
Edit: I need a pure Python solution. .Net is not an option for me.
| [
"Assuming IronPython will meet their requirement, SharpDevelop can do that for you. I have a feeling it will still be quite painful.\nHere's a link:\nhttp://community.sharpdevelop.net/blogs/mattward/archive/2009/05/11/ConvertingCSharpVBNetCodeToIronPython.aspx\n",
"You should convince your costumer that Python l... | [
6,
3
] | [] | [] | [
"c#",
"python"
] | stackoverflow_0008440502_c#_python.txt |
Q:
how to give two value for a string
import re
mysentence = 'have a dog a cute cat and a big cow '
myanimal = 'dog', 'cat' , 'cow'
print re.finditer('have(.*?)myanimal',mysentence)
this is not working , as my animal strings are not taken . Any idea to make it work ?
A:
Q> my animal strings are not taken
As you ha... | how to give two value for a string | import re
mysentence = 'have a dog a cute cat and a big cow '
myanimal = 'dog', 'cat' , 'cow'
print re.finditer('have(.*?)myanimal',mysentence)
this is not working , as my animal strings are not taken . Any idea to make it work ?
| [
"Q> my animal strings are not taken\nAs you have myanimal inside the quotations ('have(.*?)myanimal') it would be considered as part of the string, it's actual values won't be substituted.\nA regex needs to be formed, and since myanimal is list:\nfor animal in myanimal:\n regex = re.compile('have a .*%s'%animal)... | [
1,
1
] | [] | [] | [
"python",
"string"
] | stackoverflow_0008441199_python_string.txt |
Q:
Pyaudio for external interfaces (Mac OSX)
Using Python and PyAudio, I can't seem to record sound to a wav file from an external audio interface (RME Fireface), but i am able to do so with the in built mic on my iMac. I set the default device to Fireface in System preferences, and when i run the code, the wav file ... | Pyaudio for external interfaces (Mac OSX) | Using Python and PyAudio, I can't seem to record sound to a wav file from an external audio interface (RME Fireface), but i am able to do so with the in built mic on my iMac. I set the default device to Fireface in System preferences, and when i run the code, the wav file is created but no sound comes out when i play i... | [
"A couple shots in the dark - Verify if you're opening the device correctly - looks like the Fireface can be both half or full duplex (pref pane configurable?), and pyaudio apparently cares (i.e. you can't specify an output if you specify an input or vise versa.)\nAnother thing to check out is the audio routing - u... | [
1
] | [] | [] | [
"audio",
"macos",
"python"
] | stackoverflow_0007379439_audio_macos_python.txt |
Q:
Accessing variables within a gui
Hi all I have this code that doesnt seem to be working. I think its because my birthCalc method is trying to access variables within an init method. My question is how should I change this so that my program can access those gui elements and their stored values.
*Note that im tryin... | Accessing variables within a gui | Hi all I have this code that doesnt seem to be working. I think its because my birthCalc method is trying to access variables within an init method. My question is how should I change this so that my program can access those gui elements and their stored values.
*Note that im trying to access the variables at the begin... | [
"Inside __init__ function you should add your elements into class as atributes. \nI.e. change monthMenu=OptionMenu(self.app,month, *months) into self.monthMenu=OptionMenu(self.app,month, *months)\n"
] | [
2
] | [] | [] | [
"class",
"methods",
"python",
"user_interface"
] | stackoverflow_0008441527_class_methods_python_user_interface.txt |
Q:
Can Python select what network adapter when opening a socket?
The target machine running the python application will have three network interfaces available to it. In general all three networks will be vastly different, however there is a possibility that two of the three could be on similar networks.
In the exa... | Can Python select what network adapter when opening a socket? | The target machine running the python application will have three network interfaces available to it. In general all three networks will be vastly different, however there is a possibility that two of the three could be on similar networks.
In the example below I do not have control over the destination address on ET... | [
"I can't speak much for Windows, but on Linux the interface is normally not chosen until a routing decision is made, therefore you usually don't have a say on which interface your packets leave. \nYou do have the option though, of using SO_BINDTODEVICE (see man 7 socket) on Linux. This binds a socket to a device, h... | [
24,
19
] | [
"SO_BINDTODEVICE sounds reasonable, but normally you'll indirectly select a device by what IP address you bind to. More often than that, you'll just bind to '', to bind to all address of the machine.\n"
] | [
-1
] | [
"linux",
"python",
"sockets",
"windows"
] | stackoverflow_0008437726_linux_python_sockets_windows.txt |
Q:
Whats the best data structure for a calendar / day planner?
I'm an intermediate programmer. I know C very well, Java somewhat well, and have just done some very basic programming with Python, Shell, and Applescript. I'm writing the program for Mac OSX.
I'd like a create an application that plans my day for me, a... | Whats the best data structure for a calendar / day planner? | I'm an intermediate programmer. I know C very well, Java somewhat well, and have just done some very basic programming with Python, Shell, and Applescript. I'm writing the program for Mac OSX.
I'd like a create an application that plans my day for me, and lets me schedule due dates for different projects.
The idea b... | [
"I'd recommend using sqlite3. Take a look at the api for python here http://www.python.org/dev/peps/pep-0249/.\nYou could use another relational db with the same api, but for the scale of your app sqlite3 gives some ease of use benefits, and you could always switch dbs. It's straight forward and simple for your a... | [
1
] | [] | [] | [
"c",
"data_structures",
"database",
"python"
] | stackoverflow_0008441104_c_data_structures_database_python.txt |
Q:
In Django Extending User Form for Custom User
I extended my User Model as described in this SO Posting:
Extending the User model with custom fields in Django
However, I'm trying to create a User Create form but I get the following:
'Members' object has no attribute 'set_password'
Here is my model form:
class Membe... | In Django Extending User Form for Custom User | I extended my User Model as described in this SO Posting:
Extending the User model with custom fields in Django
However, I'm trying to create a User Create form but I get the following:
'Members' object has no attribute 'set_password'
Here is my model form:
class Members(models.Model):
user = models.OneToOneField(U... | [
"The method you chose to extend your User model is by creating a UserProfile (which you've called Member). A Member is not a subclass of User, so you can't call User methods (like set_password) on it.\nInstead, your SignUpForm's Meta model should still be User, and to get the extended UserProfile, you should call u... | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008441956_django_python.txt |
Q:
Django: variable parameters in URLconf
I've been looking for this question and couldn't find any, sorry if it's duplicated.
I'm building some kind of ecommerce site, similar to ebay. The problem i have arise when i'm trying to browse through "categories" and "filters". For example. You can browse the "Monitor" cat... | Django: variable parameters in URLconf | I've been looking for this question and couldn't find any, sorry if it's duplicated.
I'm building some kind of ecommerce site, similar to ebay. The problem i have arise when i'm trying to browse through "categories" and "filters". For example. You can browse the "Monitor" category. That will show you lots of monitors, ... | [
"Ben, I hope this will help you\nurls.py\nfrom catalog.views import catalog_products_view\n\nurlpatterns = patterns(\n '',\n url(r'^(?P<category>[\\w-]+)/$', catalog_products_view, name=\"catalog_products_view\"),\n url(r'^(?P<category>[\\w-]+)/(?P<filter1>[\\w-]+)/$', catalog_products_view, name=\"catalog... | [
3,
1,
0
] | [] | [] | [
"django",
"python",
"url",
"urlconf"
] | stackoverflow_0008432363_django_python_url_urlconf.txt |
Q:
Python stops reading file using read
I'm trying to read a binary file and am getting confusing results.
f = open('foo.dat','r')
data = f.read()
print len(data), f.tell()
The output is:
61, 600
What is going on here? Only the first 61 bytes are read, but the file object is telling me that I'm at the end of the... | Python stops reading file using read | I'm trying to read a binary file and am getting confusing results.
f = open('foo.dat','r')
data = f.read()
print len(data), f.tell()
The output is:
61, 600
What is going on here? Only the first 61 bytes are read, but the file object is telling me that I'm at the end of the file (the file is 600 bytes long). What ... | [
"It's probably on Windows and you have a Ctrl-Z (the CP/M end-of-file marker, which was inherited by Windows via MS-DOS). Do this:\nf = open('foo.dat','rb') # NOTE b for binary\ndata = f.read() \nprint len(data), f.tell() \nprint repr(data[60:70])\n\nand show us the output. Ctrl-Z is '\\x1a' aka chr(26).\n"
] | [
7
] | [
"data is a str object, thus len(data) tells you about the length of this string, not the file length in bytes.\n"
] | [
-1
] | [
"python"
] | stackoverflow_0008440819_python.txt |
Q:
How to add lower function to this code
I want to print my output in lowercase, but I am not getting the correct results. Here's my code. Please help!
import csv
mags = csv.reader(open("mags.csv","rU"))
for row in mags:
print [row[index] for index in (1, 0)]
print [item.lower( ) for item in row]
A:
L... | How to add lower function to this code | I want to print my output in lowercase, but I am not getting the correct results. Here's my code. Please help!
import csv
mags = csv.reader(open("mags.csv","rU"))
for row in mags:
print [row[index] for index in (1, 0)]
print [item.lower( ) for item in row]
| [
"List comprehension can be nested, like so\nprint [item.lower() for item in [row[index] for index in (1, 0)]]\n\nDon't have an interpreter handy to test this, tho.\n",
"Are you sure that the row is a list of strings here ?\nI see correct output :\n>>> row = [ \"alpA\", \"bETA\",\"gammA\" ]\n>>> print [item.lower(... | [
2,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0008441675_python.txt |
Q:
Google App Engine, Handling of Python Lists - Error accessing List Index[0][0]
I'm having an issue on Google App Engine that is pretty weird. I have small text file, its 311kbs. The text inside needs parsed. My code works fine running local, but when I push it out to GAE, it fails. I've shortened it to the belo... | Google App Engine, Handling of Python Lists - Error accessing List Index[0][0] | I'm having an issue on Google App Engine that is pretty weird. I have small text file, its 311kbs. The text inside needs parsed. My code works fine running local, but when I push it out to GAE, it fails. I've shortened it to the below simple example, to show what breaks. The code below fails at writing out what sho... | [
"Is it possible that something happened to your text file when uploading?\nIt looks like split is not recognizing the '\\n\\n\\n\\n'. \n"
] | [
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0008442595_google_app_engine_python.txt |
Q:
Accessing certain information through jquery/javascript
I am working in django templates. I have a form which contains 2 drop downs i.e FROM and DESIGN. After the form ends there is a checkbox which would require the values of the form in javascript.
<form method="POST" action="." class="frm-download">
<select id=... | Accessing certain information through jquery/javascript | I am working in django templates. I have a form which contains 2 drop downs i.e FROM and DESIGN. After the form ends there is a checkbox which would require the values of the form in javascript.
<form method="POST" action="." class="frm-download">
<select id="abc">
<option>download</option>
<option>uplo... | [
"If you need to access them on client side, use jquery selector:\n$('#abc :selected').text()\n\nhttp://jsfiddle.net/vJG2z/\n",
"To get the values of your dropdowns use .val():\nvar abc_val = $(\"#abc\").val();\nvar action_val = $(\"action\").val();\n\n"
] | [
0,
0
] | [] | [] | [
"django",
"django_templates",
"javascript",
"jquery",
"python"
] | stackoverflow_0008442655_django_django_templates_javascript_jquery_python.txt |
Q:
Which simple python based WSGI compatible jsonrpc library to use in server side for 'pyjamas'?
Recently, I came across pyjamas framework. It encourages radically different web application development approach by seperating the whole 'view' component of 'MVC' into some html + javascript (generated with compiled pyt... | Which simple python based WSGI compatible jsonrpc library to use in server side for 'pyjamas'? | Recently, I came across pyjamas framework. It encourages radically different web application development approach by seperating the whole 'view' component of 'MVC' into some html + javascript (generated with compiled python), instead of using traditional templating. This client side 'view' is supposed to communicate wi... | [
"You might have chosen some library by now. But anyways.\nI use flask and and jsonrpc2. Here is some psudo code. My code is very similar.\nimport jsonrpc2\n\nmapper = jsonrpc2.JsonRpc()\nmapper['echo'] = str\n\n@app.route('/rpc', methods=['GET', 'POST'])\ndef rpc():\n #req {\"jsonrpc\": \"2.0\", \"method\": meth... | [
1,
1
] | [] | [] | [
"json_rpc",
"pyjamas",
"python",
"web_applications"
] | stackoverflow_0006415365_json_rpc_pyjamas_python_web_applications.txt |
Q:
Python: 'module' object has no attribute 'getuid'
I am trying to write my first django webapp, and it work fine with a simple view but as soon as I include my model, it starts to give the following error
'module' object has no attribute 'getuid'
Request Method: POST
Request URL: http://localhost:8080/photos/
Dj... | Python: 'module' object has no attribute 'getuid' | I am trying to write my first django webapp, and it work fine with a simple view but as soon as I include my model, it starts to give the following error
'module' object has no attribute 'getuid'
Request Method: POST
Request URL: http://localhost:8080/photos/
Django Version: 1.2.5
Exception Type: AttributeError
Exce... | [] | [] | [
"Try to check version of python and check python installation and PYTHONPATH variable. May be problim with enveroment, not code.\n"
] | [
-2
] | [
"django",
"python"
] | stackoverflow_0008442778_django_python.txt |
Q:
Python re.sub: ignore backreferences in the replacement string
I want to replace a pattern with a string. The string is given in a variable. It might, of course, contains '\1', and it should not be interpreted as a backreference - but simply as \1.
How can I achieve that?
A:
The previous answer using re.escape()... | Python re.sub: ignore backreferences in the replacement string | I want to replace a pattern with a string. The string is given in a variable. It might, of course, contains '\1', and it should not be interpreted as a backreference - but simply as \1.
How can I achieve that?
| [
"The previous answer using re.escape() would escape too much, and you would get undesirable backslashes in the replacement and the replaced string.\nIt seems like in Python only the backslash needs escaping in the replacement string, thus something like this could be sufficient:\nreplacement = replacement.replace(\... | [
6,
5
] | [] | [] | [
"python",
"python_3.x",
"regex"
] | stackoverflow_0008441984_python_python_3.x_regex.txt |
Q:
Read all lines in .txt that are all upper or all lower case Python 2.7.1?
I'm trying to read all lines of a file that are either all upper or all lower case.
If file.txt contains:
Rememberr 8? when you
. Tellingmee THAT one
didntrememberthat
onethingtoday
I would want it to read:
didntrememberthat
ONETHINGTODAY
... | Read all lines in .txt that are all upper or all lower case Python 2.7.1? | I'm trying to read all lines of a file that are either all upper or all lower case.
If file.txt contains:
Rememberr 8? when you
. Tellingmee THAT one
didntrememberthat
onethingtoday
I would want it to read:
didntrememberthat
ONETHINGTODAY
So far I have:
def function(file_name):
data=[]
f=open(file_name,'r')
... | [
"You are getting the error because j is a string, not an integer (you don't have to call str(j), by the way; it's already a string).\nYou can remove lines with a mix of upper- and lower-case like this:\nall_one_case = [ line\n for line in f.readlines()\n if line.isupper() or line.isl... | [
5,
2,
1,
1,
1,
1
] | [] | [] | [
"element",
"lines",
"python",
"skip"
] | stackoverflow_0008442959_element_lines_python_skip.txt |
Q:
Getting Tornado URL's matched groups
In Tornado, you can link Regexes to RequestHandlers. The matched groups from the Regexes get passed into the RequestHandler's get() or post() method as arguments.
The problem is, I want to read the values of these matched groups before the get() or post() is called. Does Torn... | Getting Tornado URL's matched groups | In Tornado, you can link Regexes to RequestHandlers. The matched groups from the Regexes get passed into the RequestHandler's get() or post() method as arguments.
The problem is, I want to read the values of these matched groups before the get() or post() is called. Does Tornado have a way of accessing these matched ... | [
"Unfortunately, there does not seem to be a way to access the url regex match from \"prepare\".\nLooking at the code in tornado/web.py, especially line 949, prepare is called without parameters at all.\nI've hacked together a solution, that works, but it's not robust at all... Here it is.\nimport tornado.ioloop\nim... | [
3
] | [] | [] | [
"arguments",
"python",
"tornado"
] | stackoverflow_0008334882_arguments_python_tornado.txt |
Q:
Select strings by positions of words
For the following tuple
mysentence = 'i have a dog and a cat', 'i have a cat and a dog', 'i have a cat',
'i have a dog'
How to select only the strings 'i have a cat' , 'i have a dog', i.e exclude strings having the word dog or cat in the middle.
A:
You can do t... | Select strings by positions of words | For the following tuple
mysentence = 'i have a dog and a cat', 'i have a cat and a dog', 'i have a cat',
'i have a dog'
How to select only the strings 'i have a cat' , 'i have a dog', i.e exclude strings having the word dog or cat in the middle.
| [
"You can do this with regular expressions. The regex .+(dog|cat).+ will match one or more characters, followed by dog or cat, and one of more characters afterwards. You can then use filter to find strings which don't match this regex:\nimport re\nregex.compile(r'.+(dog|cat).+')\nsentence = 'i have a dog and a cat',... | [
4,
1,
0,
0,
0,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0008443286_python_string.txt |
Q:
Uploading and reading csv file in Python
I've got a program that reads and sorts information from a CSV file but I can't find out how to upload a file and either read it directly (which I don't think is possible) or upload it to a server.
Everything I try to Google either doesn't work or seems too ambiguous.
Has a... | Uploading and reading csv file in Python | I've got a program that reads and sorts information from a CSV file but I can't find out how to upload a file and either read it directly (which I don't think is possible) or upload it to a server.
Everything I try to Google either doesn't work or seems too ambiguous.
Has anyone got any idea how to upload the file from... | [
"The problem with this was that I was using Pylons, so it was almost ignoring the CGI.\nSo instead I should have been using:\nrequest.POST['myfile'].value\n\n",
"That you get the error means the upload works - sort of: Your CGI script is called but there is something wrong with the parameters. Steps to debug this... | [
1,
0
] | [] | [] | [
"csv",
"forms",
"html",
"python",
"upload"
] | stackoverflow_0008246179_csv_forms_html_python_upload.txt |
Q:
Call a python main from another python script
I have been giving some huge command line tool from a colleague. The main reads a bunch of arguments, parses those using the elegant import OptionParser later on and does the job.
if __name__ == '__main__':
main(sys.argv)
I can either dig into the code and copy pa... | Call a python main from another python script | I have been giving some huge command line tool from a colleague. The main reads a bunch of arguments, parses those using the elegant import OptionParser later on and does the job.
if __name__ == '__main__':
main(sys.argv)
I can either dig into the code and copy paste loads of code, or find a way to use a "command ... | [
"You don't need to do cut and paste or launch a new Python interpreter. You should be able to import the other script.\nFor example, if your colleague's script is called somescript.py you could do:\nimport somescript\nargs = ['one','two']\nsomescript.main(args)\n\n"
] | [
8
] | [] | [] | [
"python"
] | stackoverflow_0008443880_python.txt |
Q:
Indentation issues with Eclipse (using Python)
It seems like no matter what settings I use for Python indentation, Eclipse is always causing its own problems.
It keeps missing out entire areas of code, telling me there is an indentation error when there is no white space or incorrect tabs etc and sometimes I have ... | Indentation issues with Eclipse (using Python) | It seems like no matter what settings I use for Python indentation, Eclipse is always causing its own problems.
It keeps missing out entire areas of code, telling me there is an indentation error when there is no white space or incorrect tabs etc and sometimes I have to spend hours just going back over to delete lines ... | [
"It seems you're probably mixing spaces and tabs or you're currently editing a file with a different tab length from your current settings... It'd be nice if you can show a file where you're having those issues and what you were expecting.\nNote that if you do have such as issue i.e.: you configured it to have 4 wh... | [
2,
0
] | [] | [] | [
"eclipse",
"python",
"tabs"
] | stackoverflow_0008214312_eclipse_python_tabs.txt |
Q:
type of the data from mysql
Here is my code in Python:
queryuniq = "SELECT COUNT(distinct src_ip), COUNT(distinct video_id)FROM video"
cur.execute(queryuniq)
uniq = []
uniq = cur.fetchall()
print uniq
ip = str(uniq[0])
video = str(uniq[1])
fd2.write("There are %d ip addresses and %d video in total" %(int(ip), int(... | type of the data from mysql | Here is my code in Python:
queryuniq = "SELECT COUNT(distinct src_ip), COUNT(distinct video_id)FROM video"
cur.execute(queryuniq)
uniq = []
uniq = cur.fetchall()
print uniq
ip = str(uniq[0])
video = str(uniq[1])
fd2.write("There are %d ip addresses and %d video in total" %(int(ip), int(video)))
This is the value of "u... | [
"uniq is a tuple of tuples (each entry at the outer level represents a database row, within which there is a tuple of column values).\nYou query always returns one row. Therefore the outer tuple always contains one element, and you could fix your code by replacing:\nuniq = cur.fetchall()\n\nwith\nuniq = cur.fetchal... | [
2,
2
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0008444011_mysql_python.txt |
Q:
scipy starts slow for the first time
I am using scipy intensively for various purposes. I have noticed that the first time the python code is compiled, it starts very slow. later on, it is very fast.Is there any work around for this trouble?
A:
Some of the libraries that scipy links to are quite large, especiall... | scipy starts slow for the first time | I am using scipy intensively for various purposes. I have noticed that the first time the python code is compiled, it starts very slow. later on, it is very fast.Is there any work around for this trouble?
| [
"Some of the libraries that scipy links to are quite large, especially the linear algebra libraries. On slow disks or network file systems, simply loading these libraries into memory takes a long time. However, once they are read, they go into the filesystem cache so subsequent loads are pretty fast. You will have ... | [
4
] | [] | [] | [
"python",
"scipy"
] | stackoverflow_0008441203_python_scipy.txt |
Q:
How to set a value to a Jinja2 variable by Java script
I am trying to populate an HTML table using a set of Jason Data Objects. In order to do this i am using jinja template. For data population purpose um going to iterate a jinja data list and i want to set the list value from a java script function .
HTML TEMP... | How to set a value to a Jinja2 variable by Java script | I am trying to populate an HTML table using a set of Jason Data Objects. In order to do this i am using jinja template. For data population purpose um going to iterate a jinja data list and i want to set the list value from a java script function .
HTML TEMPLATE:
{% for object in list %}
<td>object.name</td>
<td>ob... | [
"You should think about what you're asking here. Jinja2 is a server-side technology, and the template is rendered before it gets sent to the browser. Your Ajax function runs on the client side, after the list variable has been turned into HTML. There is no way to do what you're asking.\nEither get your Ajax functio... | [
10
] | [] | [] | [
"ajax",
"jinja2",
"jquery_ui",
"python"
] | stackoverflow_0008444273_ajax_jinja2_jquery_ui_python.txt |
Q:
dependencies between compiled modules in python
Let's say I have two modules in a python project that are written in C++ and exposed with boost::python.
mod1.hpp
#ifndef MOD1_HPP
#define MOD1_HPP
#include <boost/python.hpp>
int square(int x);
#endif
mod1.cpp
#include "mod1.hpp"
using namespace boost::python;
... | dependencies between compiled modules in python | Let's say I have two modules in a python project that are written in C++ and exposed with boost::python.
mod1.hpp
#ifndef MOD1_HPP
#define MOD1_HPP
#include <boost/python.hpp>
int square(int x);
#endif
mod1.cpp
#include "mod1.hpp"
using namespace boost::python;
int square(int x)
{
return x*x;
}
BOOST_PYTHON_... | [
"Since mod1 is a Python extension, the clean approach would be to use it just like any other Python module:\nobject mod1 = import(\"mod1\");\nobject square = mod1.attr(\"square\");\nint y = extract<int>(square(x));\n\n"
] | [
1
] | [] | [] | [
"boost_python",
"c++",
"python"
] | stackoverflow_0008443652_boost_python_c++_python.txt |
Q:
test for clicking on a rect in Python
I can't figure out a way to detect whether the player has clicked within a rect in Pygame. I tried
self.mouserect=(pygame.mouse.get_pos(), 8,8)
and then later
if self.click: #(this is true if mouse button is down)
if self.mouserect.colliderect(self.a_thing_to_... | test for clicking on a rect in Python | I can't figure out a way to detect whether the player has clicked within a rect in Pygame. I tried
self.mouserect=(pygame.mouse.get_pos(), 8,8)
and then later
if self.click: #(this is true if mouse button is down)
if self.mouserect.colliderect(self.a_thing_to_click_on.rect):
do_stuff
but t... | [
"Did you try to use rect.collidepoint() ?\nif self.click: #(this is true if mouse button is down)\n if self.a_thing_to_click_on.rect.collidepoint(pygame.mouse.get_pos()):\n\n",
"You are assigning a tuple to self.mouserect, not a Rect. The solution is to wrap a Rect around it:\nself.mouserect=pygame.Rect(pygame.... | [
1,
0
] | [] | [] | [
"click",
"pygame",
"python"
] | stackoverflow_0008444330_click_pygame_python.txt |
Q:
Compare old and updated fields in Django model
I want to compare old and updated field in model. I have did this issue for one field but i want do this for all fields:
class MyUser(User)
def save(self, **kwargs):
if self.pk is not None:
orig = MyUser.objects.get(pk=self.pk)
orig_field_... | Compare old and updated fields in Django model | I want to compare old and updated field in model. I have did this issue for one field but i want do this for all fields:
class MyUser(User)
def save(self, **kwargs):
if self.pk is not None:
orig = MyUser.objects.get(pk=self.pk)
orig_field_names = orig._meta.get_all_field_names()
fi... | [
"Here's my go-to function for comparing fields. Gets a little hairy when dealing with foreign keys, but it's not too bad overall:\ndef get_changes_between_objects(object1, object2, excludes=[]):\n \"\"\"\n Finds the changes between the common fields on two objects\n\n :param object1: The first object\n ... | [
3,
1,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0008443688_django_django_models_python.txt |
Q:
how to stop a loop when a a value is < 0 in python
how can i stop my loop if prod_Available < 0 (negative value) and returns status = 0 else it returns status = 1?. Is it possible that when my loop encounters prod_Available < 0 it will stop looping and returns status = 0.?
here is my code :
def get_hotel_sum_qu... | how to stop a loop when a a value is < 0 in python | how can i stop my loop if prod_Available < 0 (negative value) and returns status = 0 else it returns status = 1?. Is it possible that when my loop encounters prod_Available < 0 it will stop looping and returns status = 0.?
here is my code :
def get_hotel_sum_quantity(self, product_id, checkin_date, checkout_date, qu... | [
"Mayb you could use the break statement of python to stop your loop :\nif prod_Available < 0:\n status = 0\nelse:\n status=1\n\ndata = {'available': prod_Available, 'status': status, 'sumquantity': sumOfQuantity, 'quanity': quantity}\narray.append(data) \nif status == 0:\n break\n\nthen, when prod_a... | [
3,
0,
0
] | [] | [] | [
"django",
"for_loop",
"python"
] | stackoverflow_0008442966_django_for_loop_python.txt |
Q:
Aggregate items in dict
I have a list like this:
A = [{u'CI': {u'RP': 1}}, {u'CI': {u'RP': 1}}, {u'JI': {u'RP': 1}}]
and I want merge same keys and increment value in dict.
Example:
From these values :
{u'CI': {u'RP': 1}}, {u'CI': {u'RP': 1}}
I will have:
{u'CI': {u'RP': 2}}
final list result is:
A = [{u'CI... | Aggregate items in dict | I have a list like this:
A = [{u'CI': {u'RP': 1}}, {u'CI': {u'RP': 1}}, {u'JI': {u'RP': 1}}]
and I want merge same keys and increment value in dict.
Example:
From these values :
{u'CI': {u'RP': 1}}, {u'CI': {u'RP': 1}}
I will have:
{u'CI': {u'RP': 2}}
final list result is:
A = [{u'CI': {u'RP': 2}}, {u'JI': {u'RP... | [
"You can use a defaultdict from collections to help here. This is a dict that will create default values for missing keys. Firstly you'll want a defaultdict that has a default value of 0 to do your aggregation. Next you'll need a defaultdict that has the first kind of defaultdict as its default so you can build ... | [
7,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0008443087_python.txt |
Q:
Sending email with python smtplib not working, confused about the "from" field
I'm trying to send an email in python. Here is my code.
import smtplib
if __name__ == '__main__':
SERVER = "localhost"
FROM = "sender@example.com"
TO = ["wmh1993@gmail.com"] # must be a list
SUBJECT = "Hello!"
TEXT = "This message w... | Sending email with python smtplib not working, confused about the "from" field | I'm trying to send an email in python. Here is my code.
import smtplib
if __name__ == '__main__':
SERVER = "localhost"
FROM = "sender@example.com"
TO = ["wmh1993@gmail.com"] # must be a list
SUBJECT = "Hello!"
TEXT = "This message was sent with Python's smtplib."
# Prepare actual message
message = """\
From: %s
T... | [
"\nThis runs without error, but no email is sent to wmh1993@gmail.com.\n\nThis usually means, the message was transferred to your MTA (mailserver) on 'localhost', but this server could not relay it to gmail. it probably tried to send a bounce message to \"sender@example.com\" and that failed as well. or it sent the... | [
8,
1
] | [] | [] | [
"email",
"python"
] | stackoverflow_0008440446_email_python.txt |
Q:
What's the best way to generate a UML diagram from Python source code?
A colleague is looking to generate UML class diagrams from heaps of Python source code.
He's primarily interested in the inheritance relationships, and mildly interested in compositional relationships, and doesn't care much about class attribu... | What's the best way to generate a UML diagram from Python source code? | A colleague is looking to generate UML class diagrams from heaps of Python source code.
He's primarily interested in the inheritance relationships, and mildly interested in compositional relationships, and doesn't care much about class attributes that are just Python primitives.
The source code is pretty straightforwa... | [
"You may have heard of Pylint that helps statically checking Python code. Few people know that it comes with a tool named Pyreverse that draws UML diagrams from the Python code it reads. Pyreverse uses Graphviz as a backend.\nIt is used like this:\npyreverse -o png -p yourpackage .\n\nwhere the . can also be a sing... | [
216,
105,
12,
8,
7,
6,
5,
5,
5
] | [] | [] | [
"diagram",
"python",
"uml"
] | stackoverflow_0000260165_diagram_python_uml.txt |
Q:
Reverse sort and argsort in python
I'm trying to write a function in Python (still a noob!) which returns indices and scores of documents ordered by the inner products of their tfidf scores. The procedure is:
Compute vector of inner products between doc idx and all other documents
Sort in descending order
Return ... | Reverse sort and argsort in python | I'm trying to write a function in Python (still a noob!) which returns indices and scores of documents ordered by the inner products of their tfidf scores. The procedure is:
Compute vector of inner products between doc idx and all other documents
Sort in descending order
Return the "scores" and indices from the second... | [
"I don't think there's any real need to skip the toarray. The v array will be only n_docs long, which is dwarfed by the size of the n_docs × n_terms tf-idf matrix in practical situations. Also, it will be quite dense since any term shared by two documents will give them a non-zero similarity. Sparse matrix represen... | [
11
] | [] | [] | [
"information_retrieval",
"numpy",
"python",
"scipy",
"sparse_matrix"
] | stackoverflow_0008445323_information_retrieval_numpy_python_scipy_sparse_matrix.txt |
Q:
In Python how to call subprocesses under a different user?
For a Linux system, I am writing a program in Python, who spawns child processes. I am using the "multiprocessing" library and I am wondering if there is a method to call sub-processes with a different user than the current one. I'd like to be able to run ... | In Python how to call subprocesses under a different user? | For a Linux system, I am writing a program in Python, who spawns child processes. I am using the "multiprocessing" library and I am wondering if there is a method to call sub-processes with a different user than the current one. I'd like to be able to run each subprocess with a different user (like Postfix, for example... | [
"modified python documentation example, I've added setuid in the function to be called, I'm not sure it fits to your needs and you may also need setgid, sedeuid setegid\nfrom multiprocessing import Process\nimport os\n\ndef info(title):\n print title\n print 'module name:', __name__\n print 'parent process... | [
5,
2
] | [] | [] | [
"multiprocessing",
"python",
"subprocess"
] | stackoverflow_0008419558_multiprocessing_python_subprocess.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.