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:
What causes the print function to hang? What should I be using to safely print?
I just had a heap of trouble understanding what was happening while debugging a UnicodeDecodeError with print statements.
I was confusing myself with crazy theories but in the end the problem was just that printing a particular string ... | What causes the print function to hang? What should I be using to safely print? | I just had a heap of trouble understanding what was happening while debugging a UnicodeDecodeError with print statements.
I was confusing myself with crazy theories but in the end the problem was just that printing a particular string hangs:
print '\xe6\x9c\xaa\xe5\x91\xbd\xe5\x90\x8d.jpg'
What causes it to hang?
Wha... | [
"It works ok on linux for me\nPython 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) \n[GCC 4.4.3] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> print '\\xe6\\x9c\\xaa\\xe5\\x91\\xbd\\xe5\\x90\\x8d.jpg' \n未命名.jpg\n\nWhat console are you using? perhaps it has a bug\n",
"T... | [
2,
0
] | [] | [] | [
"character_encoding",
"debugging",
"python"
] | stackoverflow_0006605354_character_encoding_debugging_python.txt |
Q:
Position the number below the barcode, using pyBarcode
I'm using pyBarcode to generate PNGs and the number below the barcode is getting cut off on the right. How do I nudge it left a few pixels?
According to the documentation I need to do something like this:
barcode.writer.BaseWriter(paint_text=my_callback)
And... | Position the number below the barcode, using pyBarcode | I'm using pyBarcode to generate PNGs and the number below the barcode is getting cut off on the right. How do I nudge it left a few pixels?
According to the documentation I need to do something like this:
barcode.writer.BaseWriter(paint_text=my_callback)
And define a callback like this:
my_callback(xpos, ypos)
and:
... | [
"Edit: After answering I noticed you've got a factory that's setting the quiet_zone to 1.0. Change that back to 6.5 and I'd imagine it will look fine.\nEdit2: I misunderstood the exact problem you were experiencing.\nFor whatever reason the author of pyBarcode is putting the text centered in the middle of the bar c... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006603977_django_python.txt |
Q:
how to open a new bash window from python and insert commands into the new bash window
I have been attempting, with little success, to open a terminal or konsole window from python and to insert commands into the terminal or konsole window.
So far, I have the following:
import os
os.system('konsole')
I cannot se... | how to open a new bash window from python and insert commands into the new bash window | I have been attempting, with little success, to open a terminal or konsole window from python and to insert commands into the terminal or konsole window.
So far, I have the following:
import os
os.system('konsole')
I cannot seem to figure out how to pipe the commands from the python prompt window to the terminal or k... | [
"If all that you need python for is to send commands to R, why not use RPy2 ? Else, try writing your commands to a temp file, invoke R in batch mode with the file and then flush it. \nPS: You might want to check this question as well for pointers.\n"
] | [
6
] | [] | [] | [
"bash",
"python",
"r"
] | stackoverflow_0006605430_bash_python_r.txt |
Q:
argparse module not working in Python
I'm trying to get the argparse module working in Python. My problem is that on a fresh install, I get the following:
File "test.py", line 3, in <module>
import argparse
File "/home/jon/Pythons/realmine/argparse.py", line 3, in <module>
parser = argparse.ArgumentParser(descript... | argparse module not working in Python | I'm trying to get the argparse module working in Python. My problem is that on a fresh install, I get the following:
File "test.py", line 3, in <module>
import argparse
File "/home/jon/Pythons/realmine/argparse.py", line 3, in <module>
parser = argparse.ArgumentParser(description='Short sample app')
AttributeError: 'mo... | [
"Usually this symptom is the result of shadowing a builtin module with one of your own. And from the error message:\nFile \"/home/jon/Pythons/realmine/argparse.py\", line 3, in <module>\n\nit looks like you have your own module argparse.py, which is causing the problem, because it's the one which test.py is trying... | [
77
] | [] | [] | [
"argparse",
"python"
] | stackoverflow_0006605851_argparse_python.txt |
Q:
Defining __repr__(self) to be created dynamically in python
I have a class
class FooBar(object):
def __repr__(self):
pass
and I want to implement the __repr__ function. Since I am using FooBar as sort of a handy container and I add some attributes dynamically I thought of generating __repr__ dynamical... | Defining __repr__(self) to be created dynamically in python | I have a class
class FooBar(object):
def __repr__(self):
pass
and I want to implement the __repr__ function. Since I am using FooBar as sort of a handy container and I add some attributes dynamically I thought of generating __repr__ dynamically, too. (If this is bad praxis, please explain and enlighten me ... | [
">>> '<FooBar({!r})>'.format({'a':1, 'b':2})\n\"<FooBar({'a': 1, 'b': 2})>\"\n\non Python2.6 you'd have to use {0!r}\nI think\n'<FooBar({!r})>'.format(vars(self))\n\nis nicer than referring to .__dict__\n"
] | [
1
] | [] | [] | [
"instance_variables",
"printing",
"python"
] | stackoverflow_0006605631_instance_variables_printing_python.txt |
Q:
Why the Segmentation Fault! When I attempt to run / use Python Package gensim?
Am attempting to use [gensim][1], a Vector Space Modelling package for python in some Machine Learning experiments of mine. I followed their installation instructions as said here, though installation of scipy on my OpenSuse 11.3 failed... | Why the Segmentation Fault! When I attempt to run / use Python Package gensim? | Am attempting to use [gensim][1], a Vector Space Modelling package for python in some Machine Learning experiments of mine. I followed their installation instructions as said here, though installation of scipy on my OpenSuse 11.3 failed when using easy_install as they recommend, so I resorted to installing it from a pa... | [
"You are probably trying to run a 64-bit binary (or use a 64-bit library) on a 32-bit system.\nUse python -v when you run the task that produces the segmentation fault to see if you can pinpoint where it is. If this isn't clear enough, then try strace python instead of just python. If the segmentation fault appears... | [
1
] | [] | [] | [
"gensim",
"python",
"segmentation_fault"
] | stackoverflow_0006522580_gensim_python_segmentation_fault.txt |
Q:
Two-way Socket I/O with asyncore or alternative in Python
Am working on the back-end of Django web app that also has to do socket I/O with sensor devices in the field via GPRS using TCP communication.
I'd managed to succeed in obtaining data from the devices using the python module asyncore. What I've been doing w... | Two-way Socket I/O with asyncore or alternative in Python | Am working on the back-end of Django web app that also has to do socket I/O with sensor devices in the field via GPRS using TCP communication.
I'd managed to succeed in obtaining data from the devices using the python module asyncore. What I've been doing was configuring the devices to send data via TCP to the server, ... | [
"If you are implementing a protocol which has some commands and some data exchange, then it is better to use the asynchat library along with asyncore.\n"
] | [
0
] | [] | [] | [
"asyncore",
"python",
"socket.io",
"two_way"
] | stackoverflow_0006423171_asyncore_python_socket.io_two_way.txt |
Q:
How to find the find reason for a python daemon process dying?
I've got a daemon implemented in python using the python-daemon library.
The daemon appears to periodically die (or is killed) however, where periodically varies from one day to several months.
I've tried to find the reason for the daemon dying by catc... | How to find the find reason for a python daemon process dying? | I've got a daemon implemented in python using the python-daemon library.
The daemon appears to periodically die (or is killed) however, where periodically varies from one day to several months.
I've tried to find the reason for the daemon dying by catching exceptions, logging them to a file, and mailing them to me. Th... | [
"While you are mailing stuff, check the memory consumption. Maybe it has a memory leak and dies when it consumes all available RAM. The resource module will let the app find out its maxrss, ixrss, idrss, and isrss and if you log those once every 5 minutes or so, it should be obvious whether or not there is a memory... | [
2
] | [] | [] | [
"daemon",
"python",
"python_daemon"
] | stackoverflow_0006328327_daemon_python_python_daemon.txt |
Q:
Google Breakpad fails to compile
I am attempting to build google-breakpad and I am getting the error
File "C:\google-breakpad\src\tools\gyp\pylib\gyp\generator\msvs.py", line 907, in _GetPathDict
parent_dict = _GetPathDict(root, parent)
File "C:\google-breakpad\src\tools\gyp\pylib\gyp\generator\msvs.py", ... | Google Breakpad fails to compile | I am attempting to build google-breakpad and I am getting the error
File "C:\google-breakpad\src\tools\gyp\pylib\gyp\generator\msvs.py", line 907, in _GetPathDict
parent_dict = _GetPathDict(root, parent)
File "C:\google-breakpad\src\tools\gyp\pylib\gyp\generator\msvs.py", line 906, in _GetPathDict
parent, ... | [
"I don't know if it'll fix your problem or not, but you could always consider raising the maximum recursion depth. Python allows you to configure it by using a function called sys.setrecursionlimit(). The default limit from what I can gather is 1000, so you might have luck by increasing it to, say, 1500 or 2000.\... | [
0,
0
] | [] | [] | [
"crash_dumps",
"crash_reports",
"google_breakpad",
"python"
] | stackoverflow_0005640220_crash_dumps_crash_reports_google_breakpad_python.txt |
Q:
Accessing unknown query arguments in Python
I'm using Jinja2 to generate a form with a variable number of inputs, labelled input_1, input_2, etc. Using Google App Engine (python), I'm then trying to access the values of these inputs in my request handler using self.request.args.get().
However, depending on the nu... | Accessing unknown query arguments in Python | I'm using Jinja2 to generate a form with a variable number of inputs, labelled input_1, input_2, etc. Using Google App Engine (python), I'm then trying to access the values of these inputs in my request handler using self.request.args.get().
However, depending on the number of inputs generated by the form, the script ... | [
"You can do this with string formatting, like so:\nnum = 5\ntag = 'input_%d' % num\n\nSo to assemble a list of the values of all the input_x tags, you could do something like this:\ninput_values = []\nfor i in range(1, number_of_values + 1):\n input_values.append(self.request.get('input_%d' % i))\n\nThis assumes y... | [
4,
0
] | [] | [] | [
"google_app_engine",
"jinja2",
"python",
"tipfy"
] | stackoverflow_0006605882_google_app_engine_jinja2_python_tipfy.txt |
Q:
question about pexpect in python
I tried both pexpect and subprocess.Popen from python to call an external long term background process (this process use socket to communicate with external applications), with following details.
subprocess.Popen(launchcmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=sub... | question about pexpect in python | I tried both pexpect and subprocess.Popen from python to call an external long term background process (this process use socket to communicate with external applications), with following details.
subprocess.Popen(launchcmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
This works fine. I do no... | [
"I think that you are making this too complicated.\nYes, it is a good idea to use a pty instead of a pipe to communicate with the background process because most applications recognize tty/pty devices and switch to using unbuffered output, (or at least line-buffered).\nBut why pexpect? Just use Python's pty module.... | [
1
] | [] | [] | [
"pexpect",
"python",
"stdout"
] | stackoverflow_0004376640_pexpect_python_stdout.txt |
Q:
How can I decode this utf-8 string, picked on a random website and saved by the Django ORM, using Python?
I parsed a file and saved its content in a database using Django. The website was 100% in English, so I naively assumed it would be ASCII all along, and saved the text happily as unicode.
You guess the rest of... | How can I decode this utf-8 string, picked on a random website and saved by the Django ORM, using Python? | I parsed a file and saved its content in a database using Django. The website was 100% in English, so I naively assumed it would be ASCII all along, and saved the text happily as unicode.
You guess the rest of the story :-)
When I print, I get the usual encoding error:
UnicodeEncodeError: 'ascii' codec can't encode cha... | [
"You are fine. You have the proper data. Yes, the original data is UTF-8 (based on context u2019 makes perfect sense as an apostrophe between \"son\" and \"s\"). The weird ? error character probably just means your terminal configuration's font doesn't have a glyph for this character (fancy apostrophe). No big de... | [
6,
1,
1
] | [] | [] | [
"django",
"encoding",
"python",
"utf_8"
] | stackoverflow_0006606291_django_encoding_python_utf_8.txt |
Q:
How can I show a "Hello"+username Screen to All other users who are not superuser in Django admin?
I want only superuser to see all models and edit/add them.But if a normal user like staff status user logs in i want him to show a screen saying "Hello"+username.
A:
You should really restrict access to the admin.
... | How can I show a "Hello"+username Screen to All other users who are not superuser in Django admin? | I want only superuser to see all models and edit/add them.But if a normal user like staff status user logs in i want him to show a screen saying "Hello"+username.
| [
"You should really restrict access to the admin.\nYou can create a decorator to do add the functionality of @superuser_required to the admin site, or simply just all people that are is_staff as otherwise.\n"
] | [
0
] | [] | [] | [
"django",
"django_admin",
"django_views",
"python"
] | stackoverflow_0006606224_django_django_admin_django_views_python.txt |
Q:
Lightweight setup to generate Web pages in pure Python
I'm totally new to Python and I'd like to start building Web pages with it (but not using a Web framework or a templating module). What are the minimum requirements? Could you suggest a simple setup?
Thank you!
EDIT: I'm not trying to be minimalist at all cost... | Lightweight setup to generate Web pages in pure Python | I'm totally new to Python and I'd like to start building Web pages with it (but not using a Web framework or a templating module). What are the minimum requirements? Could you suggest a simple setup?
Thank you!
EDIT: I'm not trying to be minimalist at all cost. What I'm looking for is a simple, common solution, that st... | [
"Clean WSGI app, without a fully-fledged framework:\nfrom wsgiref.simple_server import make_server\n\ndef application(environ, start_response):\n\n # Sorting and stringifying the environment key, value pairs\n response_body = ['%s: %s' % (key, value)\n for key, value in sorted(environ.items()... | [
5,
4,
4,
3
] | [] | [] | [
"http",
"python"
] | stackoverflow_0006606431_http_python.txt |
Q:
How to provide an API to extend a Python program with plugins?
I was wondering how I can provide an API for my Python program to enable others to extend it with plugins.
I thought about something like from myProgram.plugins import aClassToExtendByOthers, registerThatClass.
But I have no idea how to provide this.
I... | How to provide an API to extend a Python program with plugins? | I was wondering how I can provide an API for my Python program to enable others to extend it with plugins.
I thought about something like from myProgram.plugins import aClassToExtendByOthers, registerThatClass.
But I have no idea how to provide this.
I could use an exec statement within my loadPlugins function for ever... | [
"For a system that I use in several of my programs, I define a directory of plugins, and provide a base plugin class for all plugins to subclass. I then import all modules in the directory, and selectively initialize (by checking to see if they subclass my base plugin class), and store instances of plugins in a dic... | [
2,
0
] | [] | [] | [
"api",
"extend",
"plugins",
"python"
] | stackoverflow_0006574798_api_extend_plugins_python.txt |
Q:
When I create a virtualenv, python runs in 64-bit even when already set to 32-bit in OSX
My setup is: 2.6.1 python (apple default, snow leopard), virtualenv, and using virtualenvwrapper
Outside the environment, everything runs in 32-bit which is fine. But with a new project I'm going to work on needs django 1.3 an... | When I create a virtualenv, python runs in 64-bit even when already set to 32-bit in OSX | My setup is: 2.6.1 python (apple default, snow leopard), virtualenv, and using virtualenvwrapper
Outside the environment, everything runs in 32-bit which is fine. But with a new project I'm going to work on needs django 1.3 and tons of dependencies, so I made a virtualenv.
I've managed to install everything well, excep... | [
"Much of the \"magic\" that Apple used to implement their Prefer-32-bit for the system Pythons in OS X 10.6 is in /usr/bin/python which then calls the real Python interpreters which are symlinked at /usr/bin/python2.6 and /usr/bin/python2.5. virtualenv copies the real interpreter into the virtualenv bin directory ... | [
8
] | [] | [] | [
"32bit_64bit",
"macos",
"mysql_python",
"python",
"virtualenv"
] | stackoverflow_0006594558_32bit_64bit_macos_mysql_python_python_virtualenv.txt |
Q:
Equivalent of models.Manager for SqlAlchemy
I'm using SQLAlchemy and I what I liked with Django ORM was the Manager I could implement to override the initial query of an object.
Is something like this exist in SQLAlchemy? I'd like to always exclude items that have "visible = False", when I do something like :
sess... | Equivalent of models.Manager for SqlAlchemy | I'm using SQLAlchemy and I what I liked with Django ORM was the Manager I could implement to override the initial query of an object.
Is something like this exist in SQLAlchemy? I'd like to always exclude items that have "visible = False", when I do something like :
session.query(BlogPost).all()
Is it possible?
Thanks... | [
"EDIT: the original version almost worked. The following version actually works.\nIt sounds like what you're trying to do is arrange for the query entity to be something other than SELECT table.* FROM table. In sqlalchemy, you can map any \"selectable\" to a class; There are some caveats, though; if the selecta... | [
10,
1
] | [] | [] | [
"django",
"python",
"sqlalchemy"
] | stackoverflow_0006606745_django_python_sqlalchemy.txt |
Q:
Python Multi-Processing -- Array Sharing?
When sharing a rawarray between different processes using multiprocessing, is it a problem to have all the children write / modify the raw array?
Does one need to handle lockings etc in such a case?
A:
From python documentation:
multiprocessing.sharedctypes.RawArray(t... | Python Multi-Processing -- Array Sharing? | When sharing a rawarray between different processes using multiprocessing, is it a problem to have all the children write / modify the raw array?
Does one need to handle lockings etc in such a case?
| [
"From python documentation:\n\nmultiprocessing.sharedctypes.RawArray(typecode_or_type,\n size_or_initializer)\nReturn a ctypes array allocated from shared memory.\n\ntypecode_or_type determines the type of the elements of the returned\n\narray: it is either a ctypes type or a\n one character typecode of the kind\... | [
2
] | [] | [] | [
"multiprocessing",
"python"
] | stackoverflow_0006605707_multiprocessing_python.txt |
Q:
How do Python dictionary hash lookups work?
How do Python dictionary lookup algorithms work internally?
mydi['foo']
If the dictionary has 1,000,000 terms, is a tree search executed? Would I expect performance in terms of the length of the key string, or the size of the dictionary? Maybe stuffing everything in... | How do Python dictionary hash lookups work? | How do Python dictionary lookup algorithms work internally?
mydi['foo']
If the dictionary has 1,000,000 terms, is a tree search executed? Would I expect performance in terms of the length of the key string, or the size of the dictionary? Maybe stuffing everything into a dictionary is just as good as writing a tree... | [
"Here's some pseudo-code closer to what actually happens. Imagine the dictionary has a data attribute containing the key,value pairs and a size which is the number of cells allocated.\ndef lookup(d, key):\n perturb = j = hash(key)\n while True:\n cell = d.data[j % d.size]\n if cell.key is EMPTY:... | [
19,
7,
5,
1,
0
] | [] | [] | [
"algorithm",
"dictionary",
"python"
] | stackoverflow_0006605279_algorithm_dictionary_python.txt |
Q:
Best way to integrate SqlAlchemy into a Django project
I changed my Django application to use SQLAlchemy, and it works now.
But I'm wondering where I should put these lines:
engine = sqlalchemy.create_engine(settings.DATABASE_URL)
Session = sqlalchemy.orm.sessionmaker(bind=engine)
session = Session()
The reason I... | Best way to integrate SqlAlchemy into a Django project | I changed my Django application to use SQLAlchemy, and it works now.
But I'm wondering where I should put these lines:
engine = sqlalchemy.create_engine(settings.DATABASE_URL)
Session = sqlalchemy.orm.sessionmaker(bind=engine)
session = Session()
The reason I'm asking is because I want to use SQLAlchemy at many place,... | [
"for the first two, engine and Session, you can put them in settings.py; they are, configuration, after all. \nActually creating a session requires slightly more care, since a session is essentially a 'transaction'. The simplest thing to do is to create it in each view function when needed, and commit them just b... | [
25
] | [] | [] | [
"django",
"python",
"sqlalchemy"
] | stackoverflow_0006606725_django_python_sqlalchemy.txt |
Q:
Problem with Cython, module import, and Pickling
I use a custom random number generator build with Cython. I don't understand why, but it no longer works... I guess it is related to Python 2.7, or maybe a new version of Cython.
In dcmtrand.pyx, I have:
...
import dcmt
...
cdef class RandomState:
...
def __... | Problem with Cython, module import, and Pickling | I use a custom random number generator build with Cython. I don't understand why, but it no longer works... I guess it is related to Python 2.7, or maybe a new version of Cython.
In dcmtrand.pyx, I have:
...
import dcmt
...
cdef class RandomState:
...
def __reduce__(self):
return (dcmt.__RandomState_cto... | [
"Yes, you have 3 choices:\n\nSet PYTHONPATH to have dmct in it: PYTHONPATH=$PYTHONPATH:prng\nUse sys.path: \nfrom os.path import dirname, join\nimport sys\nsys.path.append(join(dirname(__file__), 'prng')\n\nDo the same inclusion as in your .py: from prng import dcmt\n\n"
] | [
2
] | [] | [] | [
"cython",
"pickle",
"python"
] | stackoverflow_0006445221_cython_pickle_python.txt |
Q:
Standardised JSON response from views
When my page POSTs a form to my Django view, the view returns a response with some data but soon I ran into the issue that my views returned data in different formats and different sets of information. I've thought of using JSON as a standard format to return my data.
There a... | Standardised JSON response from views | When my page POSTs a form to my Django view, the view returns a response with some data but soon I ran into the issue that my views returned data in different formats and different sets of information. I've thought of using JSON as a standard format to return my data.
There are two types of statuses, success and failu... | [
"been there. I wrote the solution my own (since it's simple. I dont know if theres a module out there for this). This is just a json response wrapper\nfrom django.utils import simplejson\nfrom django.http import HttpResponse\n\nclass JsonResponse(HttpResponse):\n def __init__(self, data):\n content = simp... | [
8,
0,
0,
0
] | [] | [] | [
"django",
"django_views",
"json",
"python",
"response"
] | stackoverflow_0006607443_django_django_views_json_python_response.txt |
Q:
Negative lookbehind RE in Python
I am unable to write the negative lookbehind RE in Python. These are some of the sample strings (I have more than 80,000 text messages like this):
patient 100/64 bp is 120/90 *some string*
100H/64 patient bp 120/90
location 100c/64 patient bp120/90 *some string*
*some string*... | Negative lookbehind RE in Python | I am unable to write the negative lookbehind RE in Python. These are some of the sample strings (I have more than 80,000 text messages like this):
patient 100/64 bp is 120/90 *some string*
100H/64 patient bp 120/90
location 100c/64 patient bp120/90 *some string*
*some string* 100/64 patient *this string with no '... | [
"If the blood pressure is always after your expression than just turn your idea around and match only if \"bp\" is following. For the look ahead it is allowed to have quantifiers.\n(\\b[0-9]{1,3}[a-zA-Z]?)\\/([0-9]{1,3}[a-zA-Z]?\\b)(?=.*\\bbp)\n\nSee it here at Regexr\nThat means\n(?=.*\\bbp) a positive lookahead t... | [
2,
0
] | [] | [] | [
"python",
"regex",
"string_formatting"
] | stackoverflow_0006606958_python_regex_string_formatting.txt |
Q:
How to recognise a particular user in a long multi-user internet chat log?
Here is an online programming contest we are planning to have.
What could be possible approaches to solving the same?
From a random IRC (Internet Relay Chat) log, a small percentage of the user nicknames will be randomly deleted. The parti... | How to recognise a particular user in a long multi-user internet chat log? | Here is an online programming contest we are planning to have.
What could be possible approaches to solving the same?
From a random IRC (Internet Relay Chat) log, a small percentage of the user nicknames will be randomly deleted. The participant’s code must be able to fill in the missing user nicks. In other words, th... | [
"Two things spring to my mind: authorship attribution and chat disentaglement. Neither are exactly what you describe, but they both come pretty close.\nAuthorship attribution is the problem of trying to find which of a known set of authors wrote a particular document. Classic authorship attribution is typically use... | [
3,
0
] | [] | [] | [
"machine_learning",
"nlp",
"nltk",
"opennlp",
"python"
] | stackoverflow_0006602664_machine_learning_nlp_nltk_opennlp_python.txt |
Q:
Is my Python code a mess?
There are two files in the scope of this problem, let's call them file1.py and file2.py.
I've imported file2.py into file1.py.
I instantiate a class in file1.py and I'd like to access it in file2.py. I've tried referencing the object directly (just the class name) but that doesn't work. ... | Is my Python code a mess? | There are two files in the scope of this problem, let's call them file1.py and file2.py.
I've imported file2.py into file1.py.
I instantiate a class in file1.py and I'd like to access it in file2.py. I've tried referencing the object directly (just the class name) but that doesn't work. How can I reference the object... | [
"no, it's not a mess, i just think you're accessing the object the wrong way\nfirst, import the file in file1.py\nimport file2\n\nthen, call the object without forgetting the scope:\nfile2.object.method\n\nif you want a direct call to object.method, your import must change\nfrom file2 import object\n\nthen you can ... | [
0,
0
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0006608944_oop_python.txt |
Q:
Can't find vcvarsall.bat file
I'm trying to install Scrapy on my computer using pip. For the most part it works, but after a short while in the installation I get an error saying "unable to find vcvarsall.bat. I've looked around for help, and most sources say just to install Visual Express 2008. However, even afte... | Can't find vcvarsall.bat file | I'm trying to install Scrapy on my computer using pip. For the most part it works, but after a short while in the installation I get an error saying "unable to find vcvarsall.bat. I've looked around for help, and most sources say just to install Visual Express 2008. However, even after doing this, when I navigate to C:... | [
"Issue with disutils not finding vcvarsall.bat. It should be fixed in some release\nThere is a workaorund for compiling. Try this blog \n",
"UPDATED\nWe can install Microsoft Visual C++ Compiler for Python 2.7 to solve this vcvarsall.bat problem.\nFirst install lxml by Windows Installer from PyPI, it would save a... | [
2,
1,
0
] | [] | [] | [
"python",
"visual_studio_2008"
] | stackoverflow_0006126737_python_visual_studio_2008.txt |
Q:
I have a very big list of dictionaries and I want to sum the insides
Something like
{A: 3, 45, 34, 4, 2, 5, 94, 2139, 230345, 283047, 230847}, {B: 92374, 324, 345, 345, 45879, 34857987, 3457938457), {C: 23874923874987, 2347}
How can I reduce that to
{A: 2304923094820398}, {B: 2374923784897}, {C: 2934823984723984... | I have a very big list of dictionaries and I want to sum the insides | Something like
{A: 3, 45, 34, 4, 2, 5, 94, 2139, 230345, 283047, 230847}, {B: 92374, 324, 345, 345, 45879, 34857987, 3457938457), {C: 23874923874987, 2347}
How can I reduce that to
{A: 2304923094820398}, {B: 2374923784897}, {C: 29348239847239847}
Values obviously not exact. I just want to add up all the values in a ... | [
"d = [{'A': [3, 45, 34, 4, 2, 5, 94, 2139, 230345, 283047, 230847]}, {'B': [92374, 324, 345, 345, 45879, 34857987, 3457938457]}, {'C': [23874923874987, 2347]}]\n[{x.keys()[0]:sum(x.values()[0])} for x in d]\n\n",
"Something like this:\na={'a':range(100), 'b':range(200)}\nb={}\n\nfor k,v in a.iteritems():\n b[k... | [
2,
1,
0,
0,
0,
0
] | [] | [] | [
"dictionary",
"list",
"python",
"sum"
] | stackoverflow_0006602678_dictionary_list_python_sum.txt |
Q:
Python List Help (Find Biggest number)
Ok, I have this script that i wrote:
i=1024;
a=[0]*i;
for k in range(0,i):
a[k]=(k*k*k*k-74*k*k+173) % 1000033
print a
I don't understand how to find the biggest number in the list AND its position.
A:
Here's one way:
value = max(a)
index = a.index(value)
In your exam... | Python List Help (Find Biggest number) | Ok, I have this script that i wrote:
i=1024;
a=[0]*i;
for k in range(0,i):
a[k]=(k*k*k*k-74*k*k+173) % 1000033
print a
I don't understand how to find the biggest number in the list AND its position.
| [
"Here's one way:\nvalue = max(a)\nindex = a.index(value)\n\nIn your example, value is 999926 and index is 2.\n",
"# create the list with a list comprehension\nm = [(k*k*k*k-74*k*k+173) % 1000033 for k in range(i)]\n# enumerate the values and pick the largest by value\npos, val = max(enumerate(m), key=lambda (pos,... | [
6,
3,
1,
1,
1
] | [] | [] | [
"list",
"numbers",
"python",
"string"
] | stackoverflow_0006590678_list_numbers_python_string.txt |
Q:
django internationalizing images of the layout
am building a website that will be in multi language, I was wondering how would I implement different images from static folder based on language?
for example, when visiting the main site the layout will load in english but when changed to french the logo and images ... | django internationalizing images of the layout | am building a website that will be in multi language, I was wondering how would I implement different images from static folder based on language?
for example, when visiting the main site the layout will load in english but when changed to french the logo and images attached to the layout will change based on the requ... | [
"In the template, LANGUAGE_CODE might help you out, then you can provide alternate image paths or whatever to your correct images. Sorry that I don't know a more elegant way.\nI got that information from the Django Book. The link shows where exactly I got it from.\n",
"I'm not sure, but what if try to take advant... | [
2,
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006608611_django_python.txt |
Q:
How do you save models in Elixir
I've got a database created using Django models which I'm now accessing using SQLAlchemy and Elixir. The querying works and I can pull items out of the database perfectly happily but when I edit them and try to save them it throws the following exception:
>>> p = Problem.query.firs... | How do you save models in Elixir | I've got a database created using Django models which I'm now accessing using SQLAlchemy and Elixir. The querying works and I can pull items out of the database perfectly happily but when I edit them and try to save them it throws the following exception:
>>> p = Problem.query.first()
>>> p
<Problem('Test Problem', 'Th... | [
"I'm no Elixir expert, but from the documentation it looks like it uses something called a global session. \nTo save the changes to the database, you do a session.commit(), there's no save() method like in Django.\n"
] | [
0
] | [] | [] | [
"python",
"python_elixir",
"sqlalchemy"
] | stackoverflow_0006609517_python_python_elixir_sqlalchemy.txt |
Q:
Why aren't Python dicts unified?
After reading this question, I noticed that S. Lott might have liked to use an “ordered defaultdict”, but it doesn't exist. Now, I wonder: Why do we have so many dict classes in Python?
dict
blist.sorteddict
collections.OrderedDict
collections.defaultdict
weakref.WeakKeyDictionar... | Why aren't Python dicts unified? | After reading this question, I noticed that S. Lott might have liked to use an “ordered defaultdict”, but it doesn't exist. Now, I wonder: Why do we have so many dict classes in Python?
dict
blist.sorteddict
collections.OrderedDict
collections.defaultdict
weakref.WeakKeyDictionary
weakref.WeakValueDictionary
others?
... | [
"One issue is that making this change would break backward-compatibility, due to this type of constructor usage that exists now:\n>>> dict(one=1, two=2)\n{'two': 2, 'one': 1}\n\n",
"Those extra options don't come for free. Since 99.9% of Python is built on dict, it is very important to make it as minimal and fast... | [
12,
8,
4,
0
] | [] | [] | [
"python"
] | stackoverflow_0006602816_python.txt |
Q:
How can I create a Python wrapper around Perl code?
I'm hoping to write a Python wrapper around an existing Perl API for a site I'm intending to build using the RESTful web services framework. Has anyone been able to do this (build a Python-to-Perl wrapper) with much success?
I have seen the page here http://wiki.... | How can I create a Python wrapper around Perl code? | I'm hoping to write a Python wrapper around an existing Perl API for a site I'm intending to build using the RESTful web services framework. Has anyone been able to do this (build a Python-to-Perl wrapper) with much success?
I have seen the page here http://wiki.python.org/moin/IntegratingPythonWithOtherLanguages#Perl,... | [
"Use subprocess\nsubprocess.Popen( \"perl some_code.pl\" )\n\nWorks really well.\n",
"PyPerlish is no longer developed and Inline::Python is for using python code in perl, so... I'd go with PyPerl.\n"
] | [
2,
1
] | [] | [] | [
"integration",
"perl",
"python",
"rest",
"wrapper"
] | stackoverflow_0006607838_integration_perl_python_rest_wrapper.txt |
Q:
Django installation - trouble with creating a mysite directory
I have installed django on windows but I am having trouble with the step where you are supposed to create a new project directory and then run django-admin.py startproject mysite. When I do this, I get the output below but no new mysite directory is c... | Django installation - trouble with creating a mysite directory | I have installed django on windows but I am having trouble with the step where you are supposed to create a new project directory and then run django-admin.py startproject mysite. When I do this, I get the output below but no new mysite directory is created in my project directory. What is going on here?
| [
"You should remove dot from the end of a string.\npython django-admin.py startproject mysite\n\n",
"Clearly you have .py in %PATHEXTS%. But in all probability it's not set up to pass on command line arguments - the default only registers .py files to run python.exe $1, not python.exe $1 $2 $3 $4 $5 $6 $7 $8 $9 (u... | [
1,
1,
0
] | [] | [] | [
"django",
"installation",
"python",
"python_2.6"
] | stackoverflow_0006606971_django_installation_python_python_2.6.txt |
Q:
Python function argument list formatting
What is the best way to format following piece of code accordingly to PEP8:
oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer,
token=token, verifier=verifier, http_url=ACCESS_TOKEN_URL)
The problem is that if I place more than one parameter on the fir... | Python function argument list formatting | What is the best way to format following piece of code accordingly to PEP8:
oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer,
token=token, verifier=verifier, http_url=ACCESS_TOKEN_URL)
The problem is that if I place more than one parameter on the first line, the line exceeds 79 characters. If I ... | [
"My reading of the documentation suggests that 2 and 3 are both acceptable, but it looks like 2 is preferred (I say this because it looks like 2 vs. 3 is handled this way in the examples, I don't think that the style specification is very specific here). 1 is out (look at the docs under the line Arguments on first ... | [
46
] | [] | [] | [
"formatting",
"indentation",
"pep8",
"python"
] | stackoverflow_0006609956_formatting_indentation_pep8_python.txt |
Q:
Get a list of all shortcuts from another application
I'm wondering if there's a straightforward way of getting a list of all keyboard shortcuts present in the menubar of an other application (if possible also from closed applications).
I'd like to use this in a simple Python application that I'm writing to simplif... | Get a list of all shortcuts from another application | I'm wondering if there's a straightforward way of getting a list of all keyboard shortcuts present in the menubar of an other application (if possible also from closed applications).
I'd like to use this in a simple Python application that I'm writing to simplify the process of configuring my Wacom-tablet for different... | [
"You'll probably have to use gui scripting which means the application will have to be open. I tried this with Safari. If you look under the \"File\" menu, the 6th menu item is the \"Close Window\" menu item which has a keyboard shortcut of shift-cmd-w. I targeted that one to see if I can get it...\ntell applicatio... | [
3,
0
] | [] | [] | [
"applescript",
"keyboard_shortcuts",
"macos",
"python"
] | stackoverflow_0005841956_applescript_keyboard_shortcuts_macos_python.txt |
Q:
Missing bytes in Python when writing binary files?
When writing binary files in Python I seem to be missing some bytes. I've tried this with the "write" function and with the "array.tofile" function. Here is some example code:
import zlib, sys, os, array
from struct import unpack
from array import array
inputFile... | Missing bytes in Python when writing binary files? | When writing binary files in Python I seem to be missing some bytes. I've tried this with the "write" function and with the "array.tofile" function. Here is some example code:
import zlib, sys, os, array
from struct import unpack
from array import array
inputFile = 'strings.exe'
print "Reading data from: ", inputFil... | [
"You are not closing your output file before you call os.path.getsize on it. Your 135168 bytes written is 33 x 4096 byte blocks ... try copyFile.close() instead of copyFile.close.\n",
"If you actually try to compare the two binary files (if you are under unix you use the cmp command) you will see the two files ar... | [
5,
4
] | [] | [] | [
"binary_data",
"python"
] | stackoverflow_0006609168_binary_data_python.txt |
Q:
Python string processing based on the numeric part: '5a+6b' + '2a+3b+9c' = '7a+9b+9c'
I need to add two simple polynomials (represented as strings). The following example would clarify my requirement.
input1 = '5a+6b'
input2 = '2a+3b+9c'
The required sum should be as follows:
'7a+9b+9c'
Currently I have created... | Python string processing based on the numeric part: '5a+6b' + '2a+3b+9c' = '7a+9b+9c' | I need to add two simple polynomials (represented as strings). The following example would clarify my requirement.
input1 = '5a+6b'
input2 = '2a+3b+9c'
The required sum should be as follows:
'7a+9b+9c'
Currently I have created a function (of 20 lines) to perform this task for me, but I think this can be improved.
ED... | [
"sympy does close to what you want\n>>> import sympy\n>>> a,b,c = sympy.symbols('abc')\n>>> 5*a+6*b + 2*a+9*b+9*c\n7*a + 9*c + 15*b\n\n",
"You could either use sympy:\n>>> import sympy\n>>> from sympy import *\n>>> a = Symbol('a')\n>>> b = Symbol('b')\n>>> c = Symbol('c')\n>>> eval('5*a+6*b')\n5*a + 6*b\n>>> eval... | [
8,
4,
4,
3,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0006609982_python.txt |
Q:
Jinja2: How to create multidimensional javascript array?
I am using Flask with Jinja2 as templating language.
How do you convert a multidimensional Python structure to a corresponding structure in javascript using Jinja2?
Example (Python/Flask):
pyStruct = [{key1:value1, key2:value2, [{subkey1:subvalue1, subkey2:s... | Jinja2: How to create multidimensional javascript array? | I am using Flask with Jinja2 as templating language.
How do you convert a multidimensional Python structure to a corresponding structure in javascript using Jinja2?
Example (Python/Flask):
pyStruct = [{key1:value1, key2:value2, [{subkey1:subvalue1, subkey2:subvalue2,}]},
{key1:value1, key2:value2, [{subkey1... | [
"You can use the json module, either as a Jinja filter ou directly passing the results of json.dumps() to your template.\npyStruct = [{key1:value1, key2:value2, [{subkey1:subvalue1, subkey2:subvalue2,}]},\n {key1:value1, key2:value2, [{subkey1:subvalue1, subkey2:subvalue2,}]},]\n\nrender_template('jinjat... | [
6,
2
] | [] | [] | [
"flask",
"javascript",
"jinja2",
"python"
] | stackoverflow_0006609833_flask_javascript_jinja2_python.txt |
Q:
Django query for ManyToManyField
class UserProfile(models.Model):
user = models.ForeignKey(User, unique = True, related_name = 'user')
likes = models.ManyToManyField(Product, null = True, blank = True)
class Product(models.Model):
user = models.ForeignKey(User)
price = models.FloatField(default = ... | Django query for ManyToManyField | class UserProfile(models.Model):
user = models.ForeignKey(User, unique = True, related_name = 'user')
likes = models.ManyToManyField(Product, null = True, blank = True)
class Product(models.Model):
user = models.ForeignKey(User)
price = models.FloatField(default = 0)
I've:
p1 = Product.objects.get(pk ... | [
"UserProfile.objects.filter(likes=p1).count()\n\nassuming that a product can only be liked one time by each profile.\n"
] | [
1
] | [] | [] | [
"django",
"django_orm",
"django_queryset",
"python"
] | stackoverflow_0006610595_django_django_orm_django_queryset_python.txt |
Q:
Missing output from subprocess command
I am working on a project to run PEP8 style check on local projects. I’ve tried to use the subprocess method and I am able to get the generated terminal output of the tips to improve style and save it to a string.
My code to generate the PEP8 style is as below:
def run_pep8_s... | Missing output from subprocess command | I am working on a project to run PEP8 style check on local projects. I’ve tried to use the subprocess method and I am able to get the generated terminal output of the tips to improve style and save it to a string.
My code to generate the PEP8 style is as below:
def run_pep8_style(target):
pep_tips = subprocess.Pope... | [
"According to the docs, pep8.py --count prints to stderr:\n--count print total number of errors and warnings to standard\n error and set exit code to 1 if total is not null\n\nSo you need to tell subprocss.Popen to direct stderr to subprocess.PIPE:\npep_tips = subprocess.Popen(\"p... | [
2
] | [] | [] | [
"pep8",
"python",
"subprocess"
] | stackoverflow_0006610503_pep8_python_subprocess.txt |
Q:
permutations of N balls in M boxes in C++
I asked a question last week about permutations in C++ (List of combinations of N balls in M boxes in C++).
The answers have helped me a lot but my problem has now changed.
What i would like to do is a translation from this python function to C++, keeping the same order in... | permutations of N balls in M boxes in C++ | I asked a question last week about permutations in C++ (List of combinations of N balls in M boxes in C++).
The answers have helped me a lot but my problem has now changed.
What i would like to do is a translation from this python function to C++, keeping the same order in the result :
def combinations_with_replacemen... | [
"You know python is interpreted, right? You can just type the lines you don't understand directly into python and see what happens ... start with small values first.\n\nI don't understand the itertools.combinations() algorithm\n\nThe documentation is here, and includes example output.\nNote that the value returned... | [
3,
2,
0
] | [] | [] | [
"c++",
"permutation",
"python"
] | stackoverflow_0006608212_c++_permutation_python.txt |
Q:
How do I get the current PyInterpreterState?
I'd like to create a PyThreadState since there doesn't appear to be one for the current thread.
How do I get the current PyInterpreterState to pass to PyThreadState_New(...), or is that something that I should only do if I'm embedding an interpreter (and thus have creat... | How do I get the current PyInterpreterState? | I'd like to create a PyThreadState since there doesn't appear to be one for the current thread.
How do I get the current PyInterpreterState to pass to PyThreadState_New(...), or is that something that I should only do if I'm embedding an interpreter (and thus have created it), rather than calling into a library from py... | [
"I guess that you might are doing multi-threads programming. Recently, I'm having the similar problems. Hope the following codes may help you.\n//in main thread\nPyThreadState * mainThreadState = NULL;\n\nPy_Initialize();\nPyEval_InitThreads();\nmainThreadState = PyThreadState_Get();\nPyEval_ReleaseLock();\n\n//in ... | [
4,
1,
1
] | [] | [] | [
"c",
"multithreading",
"python",
"python_c_api"
] | stackoverflow_0004987579_c_multithreading_python_python_c_api.txt |
Q:
Given the my code is open source and I'm running on a server, and I accept nearly-raw code, what's the worst that can happen to me?
I'm looking at several cases where it would be far, far, far easier to accept nearly-raw code. So,
What's the worst you can do with an expression if you can't lambda, and how?
What's... | Given the my code is open source and I'm running on a server, and I accept nearly-raw code, what's the worst that can happen to me? | I'm looking at several cases where it would be far, far, far easier to accept nearly-raw code. So,
What's the worst you can do with an expression if you can't lambda, and how?
What's the worst you can do with executed code if you can't use import and how?
(can't use X == string is scanned for X)
Also, B is unecessary... | [
"The worst you can do with an expression is on the order of\n__import__('os').system('rm -rf /')\n\nif the server process is running as root. Otherwise, you can fill up memory and crash the process with\n2**2**1024\n\nor bring the server to a grinding halt by executing a shell fork bomb:\n__import__('os').system(':... | [
13,
3,
2
] | [] | [] | [
"code_injection",
"python",
"security"
] | stackoverflow_0006609664_code_injection_python_security.txt |
Q:
Resizing frames in Tkinter
I have been making a small program with the Tkinter module in python, and I was wondering whether it was possible or not to resize a frame in my program with the mouse. As in, the user can drag the frame border and it will resize itself.
A:
Your use of terminology makes the question un... | Resizing frames in Tkinter | I have been making a small program with the Tkinter module in python, and I was wondering whether it was possible or not to resize a frame in my program with the mouse. As in, the user can drag the frame border and it will resize itself.
| [
"Your use of terminology makes the question unclear. Windows which may be resized by the user are called Toplevel windows. These are what appear as rectangular windows on the display, with a frame around them, typically a title bar, and edges or corners that can be grabbed and resized.\nThe term Frame refers to a c... | [
11
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0006610607_python_tkinter.txt |
Q:
Deciding which package manager was used to install a Python package
I want to remove a Python package, let's say Satchmo. But I don't remember which tool I used to install it.
I can think of the following ways:
Downloading source
distutils
distribute
SetupTools
Python package managers
EasyInstall
PyPM
pip
ap... | Deciding which package manager was used to install a Python package | I want to remove a Python package, let's say Satchmo. But I don't remember which tool I used to install it.
I can think of the following ways:
Downloading source
distutils
distribute
SetupTools
Python package managers
EasyInstall
PyPM
pip
apt-get
Is there a way to determine how it was installed? I think I need t... | [
"Each installation tool may keep a separate index of which packages it knows about/has installed. All Python cares about is that the files are in place. So basically, if you think it may have been installed with a certain tool, you'll have to ask the tool.\nFor apt/dpkg, you can check if the package appears in the ... | [
2
] | [] | [] | [
"distutils",
"package_managers",
"python",
"setuptools",
"uninstallation"
] | stackoverflow_0006610944_distutils_package_managers_python_setuptools_uninstallation.txt |
Q:
How do I print a python code on paper
I need to print a python source code on a paper. What is the easiest way to do that from the shell.
A:
$ cat yourFileName.py | lpr
in UNIX, if you have a printer configured.
A:
a2ps has a nice syntax highlighting (for Python and many other languages), configuration of hea... | How do I print a python code on paper | I need to print a python source code on a paper. What is the easiest way to do that from the shell.
| [
"$ cat yourFileName.py | lpr\n\nin UNIX, if you have a printer configured.\n",
"a2ps has a nice syntax highlighting (for Python and many other languages), configuration of headers+footers, etc.\n",
"I've used lgrind in the past for pretty-printed source output; I was pleased with it, but the Ubuntu Description ... | [
4,
4,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0006159015_python.txt |
Q:
Combining module files in Python
Is there a way to put together Python files, akin to JAR in Java? I need a way of packaging set of Python classes and functions, but unlike a standard module, I'd like it to be in one file.
A:
After looking for a solution to the same problem, I ended up writing a simple tool whic... | Combining module files in Python | Is there a way to put together Python files, akin to JAR in Java? I need a way of packaging set of Python classes and functions, but unlike a standard module, I'd like it to be in one file.
| [
"After looking for a solution to the same problem, I ended up writing a simple tool which combines multiple .py files into one: PyBreeder\nIt will only work with pure-Python modules and may require some trial-and-error to get the order of modules right, but it is quite handy whenever you want to deploy a script wit... | [
10,
7,
2,
1,
0
] | [] | [] | [
"packaging",
"python"
] | stackoverflow_0001104066_packaging_python.txt |
Q:
Send data from python-cgi to AJAX
I'm implementing a UI version of the find command in linux. I take the location and filename parameters for the find command in a cgi form implemented using python. On submit, I draw the form again and want to display the results in a div.
My issue is that the server times out if ... | Send data from python-cgi to AJAX | I'm implementing a UI version of the find command in linux. I take the location and filename parameters for the find command in a cgi form implemented using python. On submit, I draw the form again and want to display the results in a div.
My issue is that the server times out if the find command takes too much time. S... | [
"Refer to this one:\nhttp://www.degraeve.com/reference/simple-ajax-example.php\nHope it helps....\nIn server side, instead of storing on variable, try to store it on a file so that your python method can give it back the latest dynamic search results to every AJAX call.\n"
] | [
2
] | [] | [] | [
"ajax",
"cgi",
"python"
] | stackoverflow_0006609911_ajax_cgi_python.txt |
Q:
How to push on a EmbeddedDocument inside another EmbeddedDocument on MongoEngine?
My application is a simple TODO list, this are my classes with MongoEngine...
class Task(EmbeddedDocument):
content = StringField()
slug = StringField()
position = IntField()
priority = IntField()
status = IntFiel... | How to push on a EmbeddedDocument inside another EmbeddedDocument on MongoEngine? | My application is a simple TODO list, this are my classes with MongoEngine...
class Task(EmbeddedDocument):
content = StringField()
slug = StringField()
position = IntField()
priority = IntField()
status = IntField()
class List(EmbeddedDocument):
name = StringField()
slug = StringField()
... | [
"This isn't currently possible, either with MongoDB or MongoEngine.\nThe development branch of MongoEngine has some support for the $ positional operator, but MongoDB only supports using the positional operator once per update -- that is you cannot use it to update lists nested within lists (even if indirectly, as ... | [
2
] | [] | [] | [
"mongodb",
"mongoengine",
"orm",
"python"
] | stackoverflow_0006380868_mongodb_mongoengine_orm_python.txt |
Q:
Macports Port Select Commands
What are the new commands & or equivalents of:
python_select -L (shows available python versions)
python_select -s (sets the default version of your choice of python).
I know they have changed to --list, --set, --show but there doesn't seem to be an example of how to properly use ea... | Macports Port Select Commands | What are the new commands & or equivalents of:
python_select -L (shows available python versions)
python_select -s (sets the default version of your choice of python).
I know they have changed to --list, --set, --show but there doesn't seem to be an example of how to properly use each one. For example, if I use port ... | [
"To list:\nport select --list python\n\nTo show:\nport select --show python\n\nTo select:\nsudo port select --set python <the python version>\n\n"
] | [
51
] | [] | [] | [
"macports",
"python"
] | stackoverflow_0006612009_macports_python.txt |
Q:
mod_wsgi process getting killed and django stops working
I have mod_wsgi running in daemon mode on a custom Linux build.
I haven't included any number for processes or threads in the apache config. Here is my config:
WSGIDaemonProcess django user=admin
WSGIProcessGroup django
WSGIScriptAlias /django_apps /django/a... | mod_wsgi process getting killed and django stops working | I have mod_wsgi running in daemon mode on a custom Linux build.
I haven't included any number for processes or threads in the apache config. Here is my config:
WSGIDaemonProcess django user=admin
WSGIProcessGroup django
WSGIScriptAlias /django_apps /django/apache/django.wsgi
WSGIApplicationGroup %{GLOBAL}
On the syste... | [
"For a start, read:\nhttp://blog.dscpl.com.au/2009/11/save-on-memory-with-modwsgi-30.html\nand disable initialisation of Python interpreter within embedded processes if only using daemon mode. Those log messages are likely from embedded processes and showing up because of overly aggressive settings for Apache MPM t... | [
7
] | [] | [] | [
"django",
"mod_wsgi",
"python"
] | stackoverflow_0006608748_django_mod_wsgi_python.txt |
Q:
Adding two IDs to my urls dispatcher
I'm relatively new to python/django. I'm having an issue with sending to IDs through my urls.py.
I am trying to add an admin to a business profile page in my project.
My views.py:
@login_required
def make_admin(request, bus_id, user_id):
user = request.user
u = get_object_or... | Adding two IDs to my urls dispatcher | I'm relatively new to python/django. I'm having an issue with sending to IDs through my urls.py.
I am trying to add an admin to a business profile page in my project.
My views.py:
@login_required
def make_admin(request, bus_id, user_id):
user = request.user
u = get_object_or_404(User, pk = user_id)
b = get_object_or... | [
"The only thing i can see that seems wrong is {% if follow in b.admin.all %} there's no follow variable in your context in the code you posted.\nIf you posted more details of your error, or the stack trace, it would be most helpful.\nEDIT: Ok, your error is helpful :)\nCaught NoReverseMatch while rendering: Reverse... | [
1,
0
] | [] | [] | [
"django",
"django_models",
"django_templates",
"django_views",
"python"
] | stackoverflow_0006611905_django_django_models_django_templates_django_views_python.txt |
Q:
Test whether sync has happened (Python)
I have swf's which need to sync on a server which I have no access to. I can't know when this has happened by something on the server(there is a cron job which is supposed to run every 15 minutes, but it works... intermittently), so pretty much my only real option seems gues... | Test whether sync has happened (Python) | I have swf's which need to sync on a server which I have no access to. I can't know when this has happened by something on the server(there is a cron job which is supposed to run every 15 minutes, but it works... intermittently), so pretty much my only real option seems guess and check (wait 15 minutes... has it update... | [
"I would suggest checking whether the target server supports HEAD requests and whether the etag header and last modified header are set.\nIf this is the case, you could do (even every x seconds) a head request and compare the etag with an md5sum of a local file and if the last modified time is correct than you can ... | [
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0006612265_python_python_3.x.txt |
Q:
How should I use random.jumpahead in Python
I have a application that does a certain experiment 1000 times (multi-threaded, so that multiple experiments are done at the same time). Every experiment needs appr. 50.000 random.random() calls.
What is the best approach to get this really random. I could copy a random ... | How should I use random.jumpahead in Python | I have a application that does a certain experiment 1000 times (multi-threaded, so that multiple experiments are done at the same time). Every experiment needs appr. 50.000 random.random() calls.
What is the best approach to get this really random. I could copy a random object to every experiment and do than a jumpahea... | [
"\nI could copy a random object to every experiment and do than a jumpahead of 50.000 * expid. \n\nApproximately correct. Each thread gets their own Random instance.\nSeed all of them to the same seed value. Use a constant to test, use /dev/random when you \"run for the record\".\nEdit. Outside Python and in old... | [
5,
3,
3,
0
] | [] | [] | [
"python",
"random"
] | stackoverflow_0002546039_python_random.txt |
Q:
Compiling Python 2.6.6 and need for external packages wxPython, setuptools, etc... in Ubuntu
I compiled Python 2.6.6 with google-perf tools (tcmalloc) library to eliminate some of the memory issues I was having with the default 2.6.5. After getting 2.6.6 going it seems to not work becuase I think having issues wit... | Compiling Python 2.6.6 and need for external packages wxPython, setuptools, etc... in Ubuntu | I compiled Python 2.6.6 with google-perf tools (tcmalloc) library to eliminate some of the memory issues I was having with the default 2.6.5. After getting 2.6.6 going it seems to not work becuase I think having issues with the default 2.6.5 install in Ubuntu. Will none of the binaries installed from the software chann... | [
"A good general rule of thumb is to NEVER use the default system installed Python for any software development beyond miscellaneous system admin scripts. This applies on all UNIXes including Linux and OS/X.\nInstead, build a good Python distro that you control, with the libraries (Python and C) that you need, and i... | [
5,
0
] | [
"If you compiled 2.6.6 and installed 2.6.5 from the repos, then ubuntu is having a conflict in finding what python you're using. \nI'm flagging this to move to Superuser.\n"
] | [
-1
] | [
"ipython",
"ld",
"python",
"rpath",
"tcmalloc"
] | stackoverflow_0006079128_ipython_ld_python_rpath_tcmalloc.txt |
Q:
Calling python script from batch file opens second console
I have a batch file that runs a python script. When the python script is invoked, it starts a second windows console and then disappears when it is completed. This is a problem because I am editing the PYTHONPATH environment variable in the batch file, but... | Calling python script from batch file opens second console | I have a batch file that runs a python script. When the python script is invoked, it starts a second windows console and then disappears when it is completed. This is a problem because I am editing the PYTHONPATH environment variable in the batch file, but because the python script is running in a second window, it can... | [
"Have you tried changing the extension of the python script to .pyw, or just invoke it with pythonw.exe?\n",
"It could be that the .py filetype is associated to pythonw.exe, therefore causing it to open in a new process. Find any .py file, right click it, select properties, and check to see under \"Opens with:\... | [
0,
0,
0
] | [] | [] | [
"batch_file",
"command_prompt",
"python"
] | stackoverflow_0006602341_batch_file_command_prompt_python.txt |
Q:
Is this parallelizable?
I have a huge tab delimited file. (10,000 subjects as rows and >1-million assays as columns).
I have a mapping file which has information related to each of the 1 million columns.
I need to for every subject, for every assay, (for every cell)look into the mapping file and get some value for... | Is this parallelizable? | I have a huge tab delimited file. (10,000 subjects as rows and >1-million assays as columns).
I have a mapping file which has information related to each of the 1 million columns.
I need to for every subject, for every assay, (for every cell)look into the mapping file and get some value for it and replace the existing ... | [
"Simple parallelism\npython parse.py assays.txt | python lookup.py mapping.txt | python reformat.py >result.txt\n\nWhere parse.py reads the \"assays\" file of \"10,000 subjects as rows and >1-million assays as columns\" It parses and writes data to stdout.\nThe lookup.py reads the \"get some value for it\" mapping... | [
5,
1
] | [] | [] | [
"hadoop",
"parallel_processing",
"perl",
"python",
"r"
] | stackoverflow_0006603448_hadoop_parallel_processing_perl_python_r.txt |
Q:
What does timeit gain by turning off garbage collection?
I was reading the code for the timeit module and I noticed this segment:
gcold = gc.isenabled()
gc.disable()
timing = self.inner(it, self.timer)
if gcold:
gc.enable()
This just stores the state of garbage collection (on or off) and then turns it off. Th... | What does timeit gain by turning off garbage collection? | I was reading the code for the timeit module and I noticed this segment:
gcold = gc.isenabled()
gc.disable()
timing = self.inner(it, self.timer)
if gcold:
gc.enable()
This just stores the state of garbage collection (on or off) and then turns it off. The function inner executes the statement being timed. It then r... | [
"The nature of garbage collection is that its frequency and duration is somewhat unpredictable. At least from the point of view of the performance of a specific chunk of code, the garbage collector just adds noise to the statistics.\nFrom a whole-program point of view, you are correct in that if your program is run... | [
6,
6
] | [] | [] | [
"garbage_collection",
"python",
"timeit"
] | stackoverflow_0004523817_garbage_collection_python_timeit.txt |
Q:
best tool for building python distro with dependencies/resources
So I've been working on a python project and reached the point that I have to make some kind of installer/distribution. Now this project has quite a lot of dependencies and some resources. So far I'm struggling to create a setup.py but stuff like sci... | best tool for building python distro with dependencies/resources | So I've been working on a python project and reached the point that I have to make some kind of installer/distribution. Now this project has quite a lot of dependencies and some resources. So far I'm struggling to create a setup.py but stuff like scipy, matplotlib or even numpy are having some issues with easy_install.... | [
"I dont know if this is what you need, but for python based packaging\n\npip with requirement\nbuildout\n\nYou can use pastescript to generate your setup.py (or make project skeleton/templates)\nExample of setup.py\nsimple\nfrom setuptools import setup, find_packages\n\nsetup(\n name = \"google killer\",\n ve... | [
3
] | [] | [] | [
"packaging",
"python",
"setuptools"
] | stackoverflow_0006612548_packaging_python_setuptools.txt |
Q:
How can I run Python CGI scripts on my web server?
I want to run a Python CGI script on my web server (Apache 2.2). When I try to run the test.py file I get the following error:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>403 Forbidden</title>
</head><body>
<h1>Forbidden</h1>
<p>You don'... | How can I run Python CGI scripts on my web server? | I want to run a Python CGI script on my web server (Apache 2.2). When I try to run the test.py file I get the following error:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>403 Forbidden</title>
</head><body>
<h1>Forbidden</h1>
<p>You don't have permission to access /test.py
on this server.</p>... | [
"Add Options ExecCGI to a .htaccess file in the folder where the python file is located.\nBesides that, don't use CGI but WSGI to execute python apps...\n",
"The error log is telling you that your Web server isn't configured to allow running CGI scripts from that directory.\nSee How do I enable CGI execution in d... | [
0,
0,
0
] | [] | [] | [
"apache",
"cgi",
"python"
] | stackoverflow_0006611608_apache_cgi_python.txt |
Q:
Is there a more elegant way for unpacking keys and values of a dictionary into two lists, without losing consistence?
What I came up with is:
keys, values = zip(*[(key, value) for (key, value) in my_dict.iteritems()])
But I am not satisfied. What do the pythonistas say?
A:
keys, values = zip(*d.items())
A:
Wh... | Is there a more elegant way for unpacking keys and values of a dictionary into two lists, without losing consistence? | What I came up with is:
keys, values = zip(*[(key, value) for (key, value) in my_dict.iteritems()])
But I am not satisfied. What do the pythonistas say?
| [
"keys, values = zip(*d.items())\n\n",
"What about using my_dict.keys() and my_dict.values()?\nkeys, values = my_dict.keys(), my_dict.values()\n\n"
] | [
79,
43
] | [] | [] | [
"dictionary",
"iterable_unpacking",
"list",
"python"
] | stackoverflow_0006612769_dictionary_iterable_unpacking_list_python.txt |
Q:
How to make a copy of a list of objects not change when modifying the original list?
Possible Duplicates:
How to clone a list in python?
What is the best way to copy a list in Python?
original_list = [Object1(), Object2(), Object3()]
copy_list = original_list
original_list.pop()
If I remove an object from the o... | How to make a copy of a list of objects not change when modifying the original list? |
Possible Duplicates:
How to clone a list in python?
What is the best way to copy a list in Python?
original_list = [Object1(), Object2(), Object3()]
copy_list = original_list
original_list.pop()
If I remove an object from the original list, how can I keep the copy list from changing as well?
Original List
[<Object.... | [
"Use copy.deepcopy() for a deep copy:\nimport copy\ncopy_list = copy.deepcopy(original_list)\n\nFor a shallow copy use copy.copy():\nimport copy\ncopy_list = copy.copy(original_list)\n\nor slice with no endpoints specified :\ncopy_list = original_list[:]\n\nSee the copy docs for an explanation about deep & shallow ... | [
16,
8,
1
] | [] | [] | [
"list",
"object",
"python"
] | stackoverflow_0006612775_list_object_python.txt |
Q:
How to iterate over tuple index in django template
Suppose i have this
mylst = [(a, b, c), (x, y, z), (l, m, n)]
now instead of having this
{\% for item in mylst \%}
{{ item.0 }} {{ item.1}} {{ item.2 }}
{\% endfor \%}
can i have another loop like
{\% for item in mylst \%}
{\% for a in item... | How to iterate over tuple index in django template | Suppose i have this
mylst = [(a, b, c), (x, y, z), (l, m, n)]
now instead of having this
{\% for item in mylst \%}
{{ item.0 }} {{ item.1}} {{ item.2 }}
{\% endfor \%}
can i have another loop like
{\% for item in mylst \%}
{\% for a in item.length \%}
{{item.index }}
{\% endfo... | [
"No, and you don't want to. Iterate through the inner list in exactly the same way as the outer one.\n{% for item in mylst %}\n {% for a in item %}\n {{ a }}\n {% endfor %}\n{% endfor %}\n\n"
] | [
3
] | [] | [] | [
"django_templates",
"python",
"tuples"
] | stackoverflow_0006612877_django_templates_python_tuples.txt |
Q:
Using GAE users service - can't get "sign-in as a different user"
I'm using the GAE users service for login/logout mechanism, with create_login_url, etc, and it all works fine. BTW, I use the federated OpenID option.
But I have one problem - since the users service checks with user=users.get_current_user() then if... | Using GAE users service - can't get "sign-in as a different user" | I'm using the GAE users service for login/logout mechanism, with create_login_url, etc, and it all works fine. BTW, I use the federated OpenID option.
But I have one problem - since the users service checks with user=users.get_current_user() then if a user is logged in to his gmail, it automatically logs him into my se... | [
"Best I can think of is; you could try showing a link to /_ah/login_required which will trigger the OpenID signin page and (hopefully) also contain a \"sign in as someone else\" button.\nThis doesn't fully solve the issue, as the problem is complicated by multiple openid providers.\nIt's not possible to force someo... | [
2
] | [] | [] | [
"cookies",
"django",
"google_app_engine",
"openid",
"python"
] | stackoverflow_0006607320_cookies_django_google_app_engine_openid_python.txt |
Q:
How do I get Visual Express 2010 to find my python.h header file?
I already did a search, but I just couldn't find what I searched for.
I want to create a Python Module using C++ and Visual C++ Express 2010.
Now, I need to include Python.h, but when I compile it says it couldn't find Python.h. How do I give my VC ... | How do I get Visual Express 2010 to find my python.h header file? | I already did a search, but I just couldn't find what I searched for.
I want to create a Python Module using C++ and Visual C++ Express 2010.
Now, I need to include Python.h, but when I compile it says it couldn't find Python.h. How do I give my VC the Python header file ?
| [
"Tell IDE where header is located:\nProject -> Properties -> C/C++ -> Additional Include Directories\n",
"You either have to set the path to to the python include files in your IDE. Navigate to Tools | Options | Projects and Solutions | VC++ Directories and add the path under Include Directories.\n"
] | [
5,
0
] | [] | [] | [
"c++",
"python",
"visual_c++_2010_express"
] | stackoverflow_0006613039_c++_python_visual_c++_2010_express.txt |
Q:
python multiprocessing status of worker
I have a Python-interface class to a big C++ library, which does some work for me (with big amounts of data). I can gracefully stop the worker by sending it a signal, i.e. os.kill( pid,signal.SIGINT ).
So, I thought I should be able to run the worker in a p = Process(target=... | python multiprocessing status of worker | I have a Python-interface class to a big C++ library, which does some work for me (with big amounts of data). I can gracefully stop the worker by sending it a signal, i.e. os.kill( pid,signal.SIGINT ).
So, I thought I should be able to run the worker in a p = Process(target=worker.run() ) - which works - then at an arb... | [
"In multiprocessing, workers run as separate processes. Each process has its own address (memory) space. \nThis means that if a worker changes a variable, the change won't be visible to the parent, unless you've taken steps to make it visible.\n"
] | [
1
] | [] | [] | [
"backgroundworker",
"multiprocessing",
"python",
"state"
] | stackoverflow_0006613157_backgroundworker_multiprocessing_python_state.txt |
Q:
How do I write a generator's output to a text file?
The difflib.context_diff method returns a generator, showing you the different lines of 2 compared strings. How can I write the result (the comparison), to a text file?
In this example code, I want everything from line 4 to the end in the text file.
>>> s1 = ['ba... | How do I write a generator's output to a text file? | The difflib.context_diff method returns a generator, showing you the different lines of 2 compared strings. How can I write the result (the comparison), to a text file?
In this example code, I want everything from line 4 to the end in the text file.
>>> s1 = ['bacon\n', 'eggs\n', 'ham\n', 'guido\n']
>>> s2 = ['python\n... | [
"with open(..., \"w\") as output:\n diff = context_diff(...)\n output.writelines(diff)\n\nSee the documentation for file.writelines().\nExplanation:\n\nwith is a context manager: it handles closing the file when you are done. It's not necessary but is good practice -- you could just as well do\noutput = open(... | [
10,
0
] | [] | [] | [
"generator",
"python"
] | stackoverflow_0006613283_generator_python.txt |
Q:
django1.3 + django-formwizard + initial datas issue
i am using django 1.3, with django-formwizard.
I have a WizardView with 2 ModelForms which works fine in creation mode (as_view linked in the url conf)
but i can't make it work in edit mode.
When i do in a view:
return MyWizard.as_view([Form1,Form2], instance_dic... | django1.3 + django-formwizard + initial datas issue | i am using django 1.3, with django-formwizard.
I have a WizardView with 2 ModelForms which works fine in creation mode (as_view linked in the url conf)
but i can't make it work in edit mode.
When i do in a view:
return MyWizard.as_view([Form1,Form2], instance_dict={0:instance1, 1:instance2})(request)
the wizard instan... | [
"It appears the FormWizard constructor accepts a keyword argument named initial and nothing else, which is a dictionary mapping step to an initial data dict.\ndef __init__(self, form_list, initial=None):\n\nhttps://docs.djangoproject.com/en/1.3/ref/contrib/formtools/form-wizard/#providing-initial-data-for-the-forms... | [
0
] | [] | [] | [
"django",
"django_formwizard",
"python"
] | stackoverflow_0006612067_django_django_formwizard_python.txt |
Q:
Comparing two .txt files in Python and saving exact and similar matches to .txt file
What i need is:
text_file_1.txt:
apple
orange
ice
icecream
text_file_2.txt:
apple
pear
ice
When i use "set", output will be:
apple
ice
("equivalent of re.match")
but I want to get:
apple
ice
icecream
("equivalent of re.search"... | Comparing two .txt files in Python and saving exact and similar matches to .txt file | What i need is:
text_file_1.txt:
apple
orange
ice
icecream
text_file_2.txt:
apple
pear
ice
When i use "set", output will be:
apple
ice
("equivalent of re.match")
but I want to get:
apple
ice
icecream
("equivalent of re.search")
Is there any way how to do this? Files are large, so I can't just iterate over it and us... | [
"you might want to check out difflib\n",
"If all you want is to extract from the files words which are one a substring of the other (including those that are identical) you could do:\nfone = set(['apple', 'orange', 'ice', 'icecream'])\nftwo = set(['apple' ,'pear' ,'ice'])\n# transforming to sets saves to check tw... | [
2,
1
] | [] | [] | [
"compare",
"file_comparison",
"intersection",
"pattern_matching",
"python"
] | stackoverflow_0006613231_compare_file_comparison_intersection_pattern_matching_python.txt |
Q:
Scrapy, hash tag on URLs
I'm on the middle of a scrapping project using Scrapy.
I realized that Scrapy strips the URL from a hash tag to the end.
Here's the output from the shell:
[s] request <GET http://www.domain.com/b?ie=UTF8&node=3006339011&ref_=pe_112320_20310580%5C#/ref=sr_nr_p_8_0?rh=n%3A165796011%2Cn%... | Scrapy, hash tag on URLs | I'm on the middle of a scrapping project using Scrapy.
I realized that Scrapy strips the URL from a hash tag to the end.
Here's the output from the shell:
[s] request <GET http://www.domain.com/b?ie=UTF8&node=3006339011&ref_=pe_112320_20310580%5C#/ref=sr_nr_p_8_0?rh=n%3A165796011%2Cn%3A%212334086011%2Cn%3A%2123341... | [
"\nThis isn't something scrapy itself can change--the portion following the hash in the url is the fragment identifier which is used by the client (scrapy here, usually a browser) instead of the server.\nWhat probably happens when you fetch the page in a browser is that the page includes some JavaScript that looks ... | [
12,
1,
0
] | [] | [] | [
"python",
"scrapy",
"url",
"web_scraping"
] | stackoverflow_0006604690_python_scrapy_url_web_scraping.txt |
Q:
pySerial: opening multiple ports at once
EDIT: Found the problem: I tried referencing a variable, but mixed up its name, so instead I declared a new variable. Turns out pySerial is not limited to one open serial point at a time.
I'm trying to open two serial ports at once using the following code
ser0 = seria... | pySerial: opening multiple ports at once | EDIT: Found the problem: I tried referencing a variable, but mixed up its name, so instead I declared a new variable. Turns out pySerial is not limited to one open serial point at a time.
I'm trying to open two serial ports at once using the following code
ser0 = serial.Serial(
port = port... | [
"Without seeing the context of the code, this is only a guess.\nSerial ports will be closed when they are garbage collected and __del__ is run. Uner CPython, if your ser0 reference count drops to zero after that block of code is run, but somehow the ser1 doesn't, it will give the appearance of one port closing when... | [
0,
0,
0
] | [] | [] | [
"pyserial",
"python",
"serial_port"
] | stackoverflow_0006603475_pyserial_python_serial_port.txt |
Q:
" takes no arguments (1 given)" but I gave none
I am new to Python and I have written this simple script:
#!/usr/bin/python3
import sys
class Hello:
def printHello():
print('Hello!')
def main():
helloObject = Hello()
helloObject.printHello() # Here is the error
if __name__ == '__main__':
... | " takes no arguments (1 given)" but I gave none | I am new to Python and I have written this simple script:
#!/usr/bin/python3
import sys
class Hello:
def printHello():
print('Hello!')
def main():
helloObject = Hello()
helloObject.printHello() # Here is the error
if __name__ == '__main__':
main()
When I run it (./hello.py) I get the follo... | [
"The error is referring to the implicit self argument that is passed implicitly when calling a method like helloObject.printHello(). This parameter needs to be included explicitly in the definition of an instance method. It should look like this:\nclass Hello:\n def printHello(self):\n print('Hello!')\n\n",
... | [
40,
6,
6
] | [] | [] | [
"call",
"methods",
"python"
] | stackoverflow_0006614123_call_methods_python.txt |
Q:
How to best send binary file from Android to Python script on PC?
I need to send a binary file (or a Bitmap object) from Android to a PC, which runs a Python script to receive it.
Has anybody been in the same situation or has any hints, what could be best practice here? Options are sockets or Webservice (besides ... | How to best send binary file from Android to Python script on PC? | I need to send a binary file (or a Bitmap object) from Android to a PC, which runs a Python script to receive it.
Has anybody been in the same situation or has any hints, what could be best practice here? Options are sockets or Webservice (besides from workarounds with samba etc) I guess, but what is the easiest and f... | [
"Just doing a HTTP POST containing data to a web server should do the job. This way you have a myriad of frameworks to choose from, which saves you from doing the dirty work of pushing bits back and forth. Sure, there is some overhead, but unless you have specific reasons to avoid that (which were not mentioned in ... | [
1,
0
] | [] | [] | [
"android",
"binaryfiles",
"java",
"networking",
"python"
] | stackoverflow_0006151335_android_binaryfiles_java_networking_python.txt |
Q:
Merge several regular expressions into one RE
I have written 2 REs to match several string sequences in a String. for e.g. lets assume the two regular expressions are RE1, RE2. The strings can be in these 4 forms;
1) Match ONLY RE1 'one or more times'
2) Match ONLY RE2 'one or more times'
3) Match RE1 'one or mor... | Merge several regular expressions into one RE | I have written 2 REs to match several string sequences in a String. for e.g. lets assume the two regular expressions are RE1, RE2. The strings can be in these 4 forms;
1) Match ONLY RE1 'one or more times'
2) Match ONLY RE2 'one or more times'
3) Match RE1 'one or more times' AND match RE2 'one or more times'
4) Match... | [
"You say \"I know its very expensive as I am doing the matching for a particular string several times.\" That suggests to me that you are running each RE several times. In that case, you are making a mistake that can be resolved without writing a more complex RE.\nre1_matches = re.findall(re1, text)\nre2_matches = ... | [
7,
7,
3,
2,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0006613831_python_regex.txt |
Q:
crawler distributed over different geographical locations
I have a few desktop machines at different geographical locations. I need to create a crawler with clients at each desktop machine and a central server where data is indexed. Is it possible to create such a crawler in Nutch? Are there any alternatives. Py... | crawler distributed over different geographical locations | I have a few desktop machines at different geographical locations. I need to create a crawler with clients at each desktop machine and a central server where data is indexed. Is it possible to create such a crawler in Nutch? Are there any alternatives. Python based crawlers would be preferable.
| [
"If you use Nutch like buffer suggested, there is a script on the Nutch Wiki that may be able to help you. You would just need to get the linkdb, crawldb, and segments from each system to the central server before doing this - I think attempting to access those resources remotely would take a long time during the i... | [
1
] | [] | [] | [
"nutch",
"python",
"web_crawler"
] | stackoverflow_0006565329_nutch_python_web_crawler.txt |
Q:
Password hashing on 32bit system then migrating to 64bit systems
I came across a potential issue when migrating from a 32bit system to a 64bit system.
the system runs two 'one way' encryption algos on the string.
However when I tried the same code on a 64 bit system the hashes were different, now thats fine but d... | Password hashing on 32bit system then migrating to 64bit systems | I came across a potential issue when migrating from a 32bit system to a 64bit system.
the system runs two 'one way' encryption algos on the string.
However when I tried the same code on a 64 bit system the hashes were different, now thats fine but does anyone have any method on how to ensure the the hash can still be ... | [
"Basically, just make sure that you're using the same algorithm. If your hashes were different with the same inputs, you were using a different algorithm; there may be some unstated dependencies upon the underlying word size. Make sure you don't use those types of algorithms, or if you do, that they have very cle... | [
3
] | [] | [] | [
"encryption",
"java",
"php",
"python"
] | stackoverflow_0006615529_encryption_java_php_python.txt |
Q:
Making Python RegEx use variables for string expressions
I have a .csv file with the regular expression patterns that I want to match as well as the replacement patterns that I want. Some are extremely simple, such as "." -> "" or "," -> "".
When I run the following code, however, it doesn't seem to recognize the ... | Making Python RegEx use variables for string expressions | I have a .csv file with the regular expression patterns that I want to match as well as the replacement patterns that I want. Some are extremely simple, such as "." -> "" or "," -> "".
When I run the following code, however, it doesn't seem to recognize the variables and the pattern is never matched.
f... | [
"If you remove the r'' around the pattern, it will work.\nSo the pattern that matches . should be as simple as '\\.' instead of \"r'\\.'\"\nThe problem is r in your pattern is taken as a literal r instead of it raw string meaning.\nSo you can also try:\n v=re.sub(eval(row['Pattern']), row['Replacement'], v)\n",
... | [
2,
2
] | [] | [] | [
"python",
"regex",
"string",
"syntax",
"variables"
] | stackoverflow_0006614456_python_regex_string_syntax_variables.txt |
Q:
Eclipse + PyDev ImportError
I am having trouble getting PyDev on Eclipse to recognize installed modules (gensim), which work fine in IDLE. I am using Windows Vista, 32-bit. Python 2.7.
I have found this question asked: here, here, here, and here.
The recommended solution is to go to preferences > pydev > interpret... | Eclipse + PyDev ImportError | I am having trouble getting PyDev on Eclipse to recognize installed modules (gensim), which work fine in IDLE. I am using Windows Vista, 32-bit. Python 2.7.
I have found this question asked: here, here, here, and here.
The recommended solution is to go to preferences > pydev > interpreter - python, and remove and re-ad... | [
"This is independent of Eclipse/PyDev. You'll get the same error running the code in any other way. Your module imports gensim. The first entry on the PYTHONPATH is the current directory, and your module is called gensim.py, so your module attempts to import iteself. Because imports are cached, you don't get into i... | [
6
] | [] | [] | [
"eclipse",
"gensim",
"import",
"pydev",
"python"
] | stackoverflow_0006615569_eclipse_gensim_import_pydev_python.txt |
Q:
How could I add geolocation to OSQA?
I want to modify it so questions made in a given location can only be answered by people in or near that location.
How do I do that? is there a location plugin for django I could use?
A:
http://geodjango.org/
There is no simple plugin per say, geodjango is an add on mini fram... | How could I add geolocation to OSQA? | I want to modify it so questions made in a given location can only be answered by people in or near that location.
How do I do that? is there a location plugin for django I could use?
| [
"http://geodjango.org/\nThere is no simple plugin per say, geodjango is an add on mini framework. If you want to scale using a geo aware database is critical. \nAs a start you can represent locations as raw longitudes and latitudes without geodjango and do bounds comparison, but it will not be very efficient. If ... | [
0,
0
] | [] | [] | [
"django",
"geolocation",
"ip_geolocation",
"osqa",
"python"
] | stackoverflow_0006615051_django_geolocation_ip_geolocation_osqa_python.txt |
Q:
Just downloaded TextMate, can't import modules
I am trying to use python in order to simulate social networks, this requires matplotlib.pyplot, networkx and xlrd. Everything works fine from terminal, IDLE or X11 but when I try to use TextMate import matplotlib.pyplot as plt and import xlrd throws up ImportError: N... | Just downloaded TextMate, can't import modules | I am trying to use python in order to simulate social networks, this requires matplotlib.pyplot, networkx and xlrd. Everything works fine from terminal, IDLE or X11 but when I try to use TextMate import matplotlib.pyplot as plt and import xlrd throws up ImportError: No module named... however import networkx works fine... | [
"You need to tell TextMate which Python to use. One way to do that is to define the shell variable TM_PYTHON with an absolute path to the Python interpreter you want to use. In the TextMate menu, select Preferences, then the Advanced tab, then the Shell Variables tab, and click + to add the new variable. If you ... | [
5
] | [] | [] | [
"matplotlib",
"module",
"python",
"textmate"
] | stackoverflow_0006616005_matplotlib_module_python_textmate.txt |
Q:
Extracting Info from Plain Text and Writing to XML Using DOM
Currently, I'm designing some format conversion tools in the area of glycobiology. The format conversion involves going from a text file to an XML file that is standard in the field. Most of the time, the data we get contains the information of interest ... | Extracting Info from Plain Text and Writing to XML Using DOM | Currently, I'm designing some format conversion tools in the area of glycobiology. The format conversion involves going from a text file to an XML file that is standard in the field. Most of the time, the data we get contains the information of interest in a plain text file like below. The actual file has all of this i... | [
"Okay! Cool problem, it hurts my brain in a good way.\nFirst... for my sanity I tabbed your raw data into a way that makes sense:\n[][b-D-GlcpNAc] {\n [(4+1)][b-D-GlcpNAc] {\n [(4+1)][b-D-Manp] {\n [(3+1)][a-D-Manp] {\n [(2+1)][a-D-Manp] { }\n }\n [(6+1)][a-... | [
1
] | [] | [] | [
"bioinformatics",
"dom",
"python",
"xml"
] | stackoverflow_0006616086_bioinformatics_dom_python_xml.txt |
Q:
Numpy array from file- preallocating?
I've got a set of large ascii data files that I need to get into a numpy array. By large, I mean 390 lines, where each line is 60,000 values (double values output with high precision from a C++ program) separated by a space.
Currently I am using the following (naive) code:
im... | Numpy array from file- preallocating? | I've got a set of large ascii data files that I need to get into a numpy array. By large, I mean 390 lines, where each line is 60,000 values (double values output with high precision from a C++ program) separated by a space.
Currently I am using the following (naive) code:
import numpy as np
data_array = np.genfromtxt... | [
"Have you tried np.loadtxt? \n(genfromtxt is a more advanced file loader, which handles things like missing values and format converters.)\n"
] | [
3
] | [] | [] | [
"arrays",
"memory_management",
"numpy",
"performance",
"python"
] | stackoverflow_0006616391_arrays_memory_management_numpy_performance_python.txt |
Q:
About importing modules in python
I have three modules in the same folder.
The first module, run.py, is the main program.
The second module, called shapes.py, contains a class called "Shape"
The third module, called circles.py, that contains a class called "Circle" which inherits from Shape.
The code is written as... | About importing modules in python | I have three modules in the same folder.
The first module, run.py, is the main program.
The second module, called shapes.py, contains a class called "Shape"
The third module, called circles.py, that contains a class called "Circle" which inherits from Shape.
The code is written as follows
run.py
from shapes import Sha... | [
"Import shapes from within circles.py:\nfrom shapes import Shape\n\nclass Circle(Shape):\n ...\n\nIn Python, each module must import whatever it needs. It can't rely on any other module to do the importing for it.\n",
"You need to import all classes you are using in a python module. In your first module (run.py... | [
3,
3,
0
] | [] | [] | [
"python",
"python_import"
] | stackoverflow_0006616417_python_python_import.txt |
Q:
X-axis in Matplotlib
I've written a simple program in Python using Matplotlib to draw lines in a coordinate system. I want X-Axis description to be "2006, 2007, 2008" but instead is shows as
"0, 0.5, 1, 1.5, 2.0 +2.006e3"
code is here:
import matplotlib.pyplot
import numpy as np
fig = matplotlib.pyplot.figu... | X-axis in Matplotlib | I've written a simple program in Python using Matplotlib to draw lines in a coordinate system. I want X-Axis description to be "2006, 2007, 2008" but instead is shows as
"0, 0.5, 1, 1.5, 2.0 +2.006e3"
code is here:
import matplotlib.pyplot
import numpy as np
fig = matplotlib.pyplot.figure()
a=[2006,2007,2008]
... | [
"Instead of \nplt.axis([2006, 2008, -1, 5])\n\nuse plt.xticks:\nplt.xticks(a, map(str,a))\n\n\nPS: Its convenient to import matplotlib.pyplot with\nimport matplotlib.pyplot as plt\n\nas this cuts down on the typing.\n"
] | [
1
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0006616481_matplotlib_python.txt |
Q:
Help: Python while loop inside Class
I'm just learning Python as my first programming language, and going through the this online book. My problem relates to the exercise found on that page. I'm stuck understanding how the play method works inside the class. How is it accessing all the other methods? How is ge... | Help: Python while loop inside Class | I'm just learning Python as my first programming language, and going through the this online book. My problem relates to the exercise found on that page. I'm stuck understanding how the play method works inside the class. How is it accessing all the other methods? How is getattr functioning inside this loop? Appre... | [
"I'll try to explain how it works.\nFirst, this is run:\na_game = Game(\"central_corridor\")\n\nThis calls Game.__init__(\"central_corridor\").\nIn the __init__ method, self.start takes the value \"central_corridor\".\nThen we go back to the main body. By now, we have a variable called a_game. This variable is in f... | [
2,
1,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0006605704_python.txt |
Q:
How to convert not HTML 4 entities to be shown?
I have some entities that are not standard ones like ş or č
Is there a way to convert these entities to the UTF-8 characters (č and ş in my example) or to something else that can be shown in a html page?
I would like to do it in javascript, but if it ... | How to convert not HTML 4 entities to be shown? | I have some entities that are not standard ones like ş or č
Is there a way to convert these entities to the UTF-8 characters (č and ş in my example) or to something else that can be shown in a html page?
I would like to do it in javascript, but if it is not possible I can pre-process the content server-... | [
"One solution would be to do a regex search and replace of these entities over the body of the document. Example:\n<html>\n<head>\n<script language=\"javascript\">\n\nwindow.onload = function(){\n var entities = [{entity:\"scedil\", char:\"č\"},\n {entity:\"ccaron\", char:\"ş\"}]; // array of ... | [
1
] | [] | [] | [
"entities",
"html",
"javascript",
"python"
] | stackoverflow_0006616330_entities_html_javascript_python.txt |
Q:
Finding python function parameters from C++
I am calling python functions from C++. I was wondering if it is possible to determine the number of parameters and the names of these parameters. I have read the link How to find the number of parameters to a Python function from C? however I do not really understand.
I... | Finding python function parameters from C++ | I am calling python functions from C++. I was wondering if it is possible to determine the number of parameters and the names of these parameters. I have read the link How to find the number of parameters to a Python function from C? however I do not really understand.
I have this C++ function that calls the function '... | [
"This answer to the question you linked to seems to be what you want. inspect.getargspec does exactly what you want on the Python side, and as the answer states, you can use PyObject_CallMethod or one of the related functions described at that link target to call inspect.getargspec from your C++ code, get the retur... | [
5
] | [] | [] | [
"c++",
"parameters",
"python"
] | stackoverflow_0006616398_c++_parameters_python.txt |
Q:
Python 2.7 - Error at line 298 - What is wrong with my code?
Here is the code from the last if: to the next if:
if msgtype == "\x00":
utflength=struct.unpack("!h", data[:2])[0]
name=str(data[2:int(utflength)+2])
data=data[utflength+2:]
utflength=struct.unpack("!h", data[:2])[0]
message=data[2:u... | Python 2.7 - Error at line 298 - What is wrong with my code? | Here is the code from the last if: to the next if:
if msgtype == "\x00":
utflength=struct.unpack("!h", data[:2])[0]
name=str(data[2:int(utflength)+2])
data=data[utflength+2:]
utflength=struct.unpack("!h", data[:2])[0]
message=data[2:utflength+2]
self.sendOutput("To " + name + ": " + message)
els... | [
"There can only be one else per if statement.\nYou can, however, distinguish different cases with elif:\nif condition1:\n ...\nelif condition2:\n assert not condition1\n ...\nelse:\n assert not condition1 and not condition2\n ...\n\nFor details on if, else, elif, and other flow control statements, refer... | [
12
] | [] | [] | [
"python"
] | stackoverflow_0006616715_python.txt |
Q:
How to install mysql connector
I have downloaded mysqlDb, and while installing it I am getting errors like:
C:\Documents and Settings\naresh\Desktop\MySQL-python-1.2.3c1>setup.py build
Traceback (most recent call last):
File "C:\Documents and Settings\naresh\Desktop\MySQL-python-1.2.3c1
\setup.py",line15, i... | How to install mysql connector | I have downloaded mysqlDb, and while installing it I am getting errors like:
C:\Documents and Settings\naresh\Desktop\MySQL-python-1.2.3c1>setup.py build
Traceback (most recent call last):
File "C:\Documents and Settings\naresh\Desktop\MySQL-python-1.2.3c1
\setup.py",line15, in
metadata, options = get_config()... | [
"The registry key need to patch in that file, kindly refer to this thread\nIntegrating MySQL with Python in Windows\nor download prebuilt binary\nhttp://www.codegood.com/archives/4\n",
"You need to fire up regedit and make \nHKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Python\\PythonCore\\2.7\\InstallPath\nand HKEY... | [
6,
0
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0001803233_mysql_python.txt |
Q:
How to find an index of an item in a list, searching the item with a regular expression in Python?
I have a list like that:
lst = ['something', 'foo1', 'bar1', 'blabla', 'foo2']
Is it possible to get the index of the first item starting with "foo" (foo1) using regular expressions and lst.index() like:
ind = lst.i... | How to find an index of an item in a list, searching the item with a regular expression in Python? | I have a list like that:
lst = ['something', 'foo1', 'bar1', 'blabla', 'foo2']
Is it possible to get the index of the first item starting with "foo" (foo1) using regular expressions and lst.index() like:
ind = lst.index("some_regex_for_the_item_starting_with_foo") ?
I know I can create a counter and a for loop and us... | [
"I think that it's ok and you can use startswith method if it do what you really want(i am not sure that you really need regEx here - however code below can be easily modified to use regEx):\ndata = ['text', 'foo2', 'foo1', 'sample']\nindeces = (i for i,val in enumerate(data) if val.startswith('foo'))\n\nOr with re... | [
3,
1,
1,
0,
0
] | [] | [] | [
"indexing",
"list",
"python",
"regex"
] | stackoverflow_0006616537_indexing_list_python_regex.txt |
Q:
Oneline population of dictionary from array in Python
I need to populate dictionary from array. I've done in three lines and i'm trying to do it shortest as it can be. Is there way how to populate it in single line?
a = [['test',154],['test2',256]]
d = dict()
for b in a:
d[b[0]] = b[1]
A:
Just dict :)
>>> a ... | Oneline population of dictionary from array in Python | I need to populate dictionary from array. I've done in three lines and i'm trying to do it shortest as it can be. Is there way how to populate it in single line?
a = [['test',154],['test2',256]]
d = dict()
for b in a:
d[b[0]] = b[1]
| [
"Just dict :)\n>>> a = [['test',154],['test2',256]]\n>>> dict(a)\n{'test': 154, 'test2': 256}\n\n",
"You just do dict(a) or dict([['test',154],['test2',256]]).\n"
] | [
14,
4
] | [
"L = [['test',154],['test2',256]]\nIn Python 3.x:\nd = {k:v for k,v in L}\n\nIn Python 2.x:\nd = dict([(k,v) for k,v in L])\n\n"
] | [
-1
] | [
"python"
] | stackoverflow_0006616907_python.txt |
Q:
Clustering conceptually similar documents together?
This is more of a conceptual question than an actual implementation and am hoping someone could clarify. My goal is the following: Given a set of documents, I want to cluster them such that documents belonging to the same cluster have the same "concept".
From wh... | Clustering conceptually similar documents together? | This is more of a conceptual question than an actual implementation and am hoping someone could clarify. My goal is the following: Given a set of documents, I want to cluster them such that documents belonging to the same cluster have the same "concept".
From what I understand, Latent Semantic Analysis lets me find a ... | [
"For your first part of your question: No, you do not need to perform any 'clustering' anymore. Such clustering is already available from your singular value decomposition. If this is still unclear, please study more on detailed manner your link Latent Semantic Analysis.\nFor your second part: please just figure ou... | [
4
] | [] | [] | [
"data_mining",
"machine_learning",
"nlp",
"numpy",
"python"
] | stackoverflow_0006615833_data_mining_machine_learning_nlp_numpy_python.txt |
Q:
Django model with 3 many to many fields
I have these models
class User(models.Model):
user_name = models.CharField()
ph_number = models.CharField()
class ExamPaper(models.Model):
paper_name = models.CharField()
paper_subject = models.CharField()
class Questions(models.Model):
paper = models.M... | Django model with 3 many to many fields | I have these models
class User(models.Model):
user_name = models.CharField()
ph_number = models.CharField()
class ExamPaper(models.Model):
paper_name = models.CharField()
paper_subject = models.CharField()
class Questions(models.Model):
paper = models.ManyToManyField(ExamPaper, related_name='quest... | [
"You should use one-to-many (ForeignKey) relationships instead of many-to-many:\nclass Result(models.Model):\n user = models.ForeignKey(User)\n paper = models.ForeignKey(ExamPaper)\n question = models.ForeignKey(Question)\n marks = models.IntegerField()\n result = models.CharField()\n\n clas... | [
6,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0006617333_django_django_models_python.txt |
Q:
python datetime.datetime not returning correct timezone info with daylight savings time
I'm having an issue creating dates in python, as the dates I create are not respecting daylight savings time in some scenarios.
For example, if I go to my shell and run
>>> adjust_datetime_to_timezone(value=datetime.datetime.no... | python datetime.datetime not returning correct timezone info with daylight savings time | I'm having an issue creating dates in python, as the dates I create are not respecting daylight savings time in some scenarios.
For example, if I go to my shell and run
>>> adjust_datetime_to_timezone(value=datetime.datetime.now(), from_tz=timezone('UTC'), to_tz=timezone('US/Pacific'))
datetime.datetime(2011, 7, 7, 12,... | [
"Since I see <DstTzInfo 'US/Pacific' PST-1 day, 16:00:00 STD>, it appears you are using pytz. In that case, you can use the localize method to create timezone-aware datetimes that are adjusted for Daylight Savings Time. (Avoid using datetime.datetime's tzinfo argument since it does not adjust for Daylight Savings T... | [
2
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0006616349_datetime_python.txt |
Q:
argparse module - How to change help format in runtime?
Lets say, I've got a parser:
self.__parser = argparse.ArgumentParser(
prog = '<...>',
fromfile_prefix_chars='@')
After it is initialized I want in runtime to change the prog variable in argparser to som... | argparse module - How to change help format in runtime? | Lets say, I've got a parser:
self.__parser = argparse.ArgumentParser(
prog = '<...>',
fromfile_prefix_chars='@')
After it is initialized I want in runtime to change the prog variable in argparser to something else, lets say: 'aaa'.
Code:
self.__parser.prog = 'aaa... | [
"It is my suspicion that the problem is somewhere else in your code, as the code below is allowed to change the prog attribute, demonstrated by the calls to print_help:\nimport argparse\nimport sys\n\nclass MyParser():\n def __init__(self, nm=sys.argv[0]):\n self.__parser = argparse.ArgumentParser(prog=nm... | [
3
] | [] | [] | [
"argparse",
"python",
"runtime"
] | stackoverflow_0006616575_argparse_python_runtime.txt |
Q:
PYTHONPATH issues with versioned package names outside of site-packages
In attempting to solve a package management issue here, I learned I may have issues with the way I'm using PYTHONPATH to access packages outside of the site-packages directory.
I receive an import error when attempting to import modules from a... | PYTHONPATH issues with versioned package names outside of site-packages | In attempting to solve a package management issue here, I learned I may have issues with the way I'm using PYTHONPATH to access packages outside of the site-packages directory.
I receive an import error when attempting to import modules from a package (say wxPython) from its versioned directory folder name (i.e. wx-2.8... | [
"As I understand what you're saying, this is expected behaviour. C:\\foo is in your Pythonpath, but it does not contain an importable wx module. For import wx to succeed, it has to find one of wx.(py/pyc/pyd/dll/so) or a directory wx containing the file __init__.py, directly in one of the directories on your Python... | [
0
] | [] | [] | [
"python",
"pythonpath"
] | stackoverflow_0006616767_python_pythonpath.txt |
Q:
HTTP telnet POST/GAE server question (SIMPLE STUFF)
I am playing with HTTP transfers, just trying to make something work. I have a GAE server and I'm pretty sure it's working properly because it renders when I go to it with my browser, but here is the python code anyway:
import sys
print 'Content-Type: text/html'
... | HTTP telnet POST/GAE server question (SIMPLE STUFF) | I am playing with HTTP transfers, just trying to make something work. I have a GAE server and I'm pretty sure it's working properly because it renders when I go to it with my browser, but here is the python code anyway:
import sys
print 'Content-Type: text/html'
print ''
print '<pre>'
number = -1
data = sys.stdin.read(... | [
"when using GET, no data will be present in the request body, so sys.stdin.read() is bound to fail. instead, you might want to look at the environment, specifically os.environ['QUERY_STRING']\nAnother thing you're doing a little strangely is you are not using the correct request format. The second part of the req... | [
2
] | [] | [] | [
"google_app_engine",
"http",
"python",
"telnet"
] | stackoverflow_0006617405_google_app_engine_http_python_telnet.txt |
Q:
Python prefers unassigned local function over built-in function
The following Python script works well with Python 2.3 and Python 2.4 (which don't have a built-in definition of all():
#! /usr/bin/env python
# vim: set fileencoding=utf-8
# (c) Uwe Kleine-König
# GPLv2
import locale
import sys
f = file(sys.argv[1]... | Python prefers unassigned local function over built-in function | The following Python script works well with Python 2.3 and Python 2.4 (which don't have a built-in definition of all():
#! /usr/bin/env python
# vim: set fileencoding=utf-8
# (c) Uwe Kleine-König
# GPLv2
import locale
import sys
f = file(sys.argv[1])
data = f.read()
def len_utf8_char(data):
if not 'all' in dir(_... | [
"When Python parses a function body, it looks for variable names that are used in assignments. All such variables are assumed to be local, unless the global variable declaration is used. \nThe def all assigns a value to the variable name all. Despite the assignment being inside an if-block, all is regarded as a loc... | [
5,
3,
2,
0
] | [] | [] | [
"compatibility",
"python"
] | stackoverflow_0006617354_compatibility_python.txt |
Q:
Python/PySerial bit operator on string
I'm using PySerial (Python 2.7) to read information from a device like this:
buffer += ser.read(3)
Now I have three bytes in buffer (i.e. 0xAE0259) which is of type str. Since I'm new to Python, I'm looking for the "pythonian" way to cut off the left most (0xAE) of the three ... | Python/PySerial bit operator on string | I'm using PySerial (Python 2.7) to read information from a device like this:
buffer += ser.read(3)
Now I have three bytes in buffer (i.e. 0xAE0259) which is of type str. Since I'm new to Python, I'm looking for the "pythonian" way to cut off the left most (0xAE) of the three bytes and then interpret the remaining two a... | [
"You need to know whether multi-byte types are big or little endian and whether it's signed or unsigned. Assuming the two bytes are an unsigned, big-endian short, I would do the following:\n>>> buf = '\\xAE\\x02\\x59'\n>>> from struct import unpack\n>>> unpack('>BH', buf)\n(174, 601)\n\n'>' means big endian. 'B' is... | [
2,
1,
1,
0,
0
] | [] | [] | [
"pyserial",
"python"
] | stackoverflow_0006597133_pyserial_python.txt |
Q:
Right Click Menu (context menu) using PyGTK
So I'm still fairly new to Python, and have been learning for a couple months, but one thing I'm trying to figure out is say you have a basic window...
#!/usr/bin/env python
import sys, os
import pygtk, gtk, gobject
class app:
def __init__(self):
window = gtk.W... | Right Click Menu (context menu) using PyGTK | So I'm still fairly new to Python, and have been learning for a couple months, but one thing I'm trying to figure out is say you have a basic window...
#!/usr/bin/env python
import sys, os
import pygtk, gtk, gobject
class app:
def __init__(self):
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.set_title("... | [
"There is a example for doing this very thing found at http://www.pygtk.org/pygtk2tutorial/sec-ManualMenuExample.html\nIt shows you how to create a menu attach it to a menu bar and also listen for a mouse button click event and popup the very same menu that was created.\nI think this is what you are after.\nEDIT: (... | [
13
] | [] | [] | [
"gtk",
"menu",
"pygobject",
"pygtk",
"python"
] | stackoverflow_0006616270_gtk_menu_pygobject_pygtk_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.