content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
python class inheritance for parameters
I am trying to create a schedule class in python that takes the start time, end time, and location of a meeting. So far I have:
class Schedule(Time):
def __init__(self, start_time, end_time, location):
self.start_time = start_time
self.end_time = end_time
self.lo... | python class inheritance for parameters | I am trying to create a schedule class in python that takes the start time, end time, and location of a meeting. So far I have:
class Schedule(Time):
def __init__(self, start_time, end_time, location):
self.start_time = start_time
self.end_time = end_time
self.location = location
print (self.start_time)... | [
"Some dynamically-typed languages would want you to do this everywhere (statically-typed languages will generally enforce it themselves), but in Python the generally recommended practice is duck typing, which suggests that you just expect it to be a Time, but if it's something else, don't worry (if it implements th... | [
3,
2,
2,
1,
0,
0
] | [] | [] | [
"inheritance",
"init",
"parameters",
"python"
] | stackoverflow_0008352583_inheritance_init_parameters_python.txt |
Q:
Access global queue object in python
I am building a messaging app in python that interfaces with twitter I want to create a global fifo queue that the twitterConnection object can access to insert new messages.
this is the main section of the app:
#!/usr/bin/python
from twitterConnector import TwitterCon... | Access global queue object in python | I am building a messaging app in python that interfaces with twitter I want to create a global fifo queue that the twitterConnection object can access to insert new messages.
this is the main section of the app:
#!/usr/bin/python
from twitterConnector import TwitterConnector
from Queue import deque
#i... | [
"The problem is that \"global\" should appear on a line of its own\nglobal requestQueue\nrequestQueue.add(mention)\n\nMoreover, the requestQueue must appear in the module that is defining the class.\nIf you are importing the requestQueue symbol from another class, you don't need the global at all.\nfrom some_module... | [
4,
2
] | [] | [] | [
"global_variables",
"python"
] | stackoverflow_0008352736_global_variables_python.txt |
Q:
Django model object initialization
If I do
obj = Object()
obj.att1 = 'test'
obj.att2 = 'test'
obj.save()
obj.id --> works fine
But if I do
obj=Object(att1='test',att2='test').save()
Doing obj.id --> obj seems to be Nonetype at this stage
Is this the case?
A:
I don't know the exact framework you are using, bu... | Django model object initialization | If I do
obj = Object()
obj.att1 = 'test'
obj.att2 = 'test'
obj.save()
obj.id --> works fine
But if I do
obj=Object(att1='test',att2='test').save()
Doing obj.id --> obj seems to be Nonetype at this stage
Is this the case?
| [
"I don't know the exact framework you are using, but I am going to take a guess as to the problem:\nObject(att1='test',att2='test').save()\nThe save() function doesn't appear to return the Object instance, it returns None. So you would normally:\nobj=Object(att1='test',att2='test')\nobj.save()\n\nThen check obj.id... | [
8
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008352862_django_python.txt |
Q:
Symfony and mechanize
I am trying to access to a local website designed with the Symfony framework.
It works perfectly with the web browser and with CURL but when I use Mechanize I always got the 401 unauthorized answer for the server.
import mechanize
# Browser
br = mechanize.Browser()
br.set_debug_http(True)
b... | Symfony and mechanize | I am trying to access to a local website designed with the Symfony framework.
It works perfectly with the web browser and with CURL but when I use Mechanize I always got the 401 unauthorized answer for the server.
import mechanize
# Browser
br = mechanize.Browser()
br.set_debug_http(True)
br.set_debug_redirects(True... | [
"I finally found the answer by myself.\nThere is a bug in the sfDoctrineGuardPlugin (and sfGuardPlugin) that causes this behavior as stated here.\nI applied the patch and the problem is solved.\n",
"there are tight controls on who can access the development environment in symfony. Try using the main URL (probably... | [
6,
1,
1,
1,
1
] | [] | [] | [
"mechanize",
"python",
"symfony1"
] | stackoverflow_0008221190_mechanize_python_symfony1.txt |
Q:
Best way to send email with Python on Mac or Linux?
I want to send emails with my python script, but unfortunately it's not as straightforward and smooth as php, where I can just use mail() function.
I've used this example:
import smtplib
FROM = "sender@example.com"
TO = ["me@gmail.com"]
SUBJECT =... | Best way to send email with Python on Mac or Linux? | I want to send emails with my python script, but unfortunately it's not as straightforward and smooth as php, where I can just use mail() function.
I've used this example:
import smtplib
FROM = "sender@example.com"
TO = ["me@gmail.com"]
SUBJECT = "Hello!"
TEXT = "This message was sent with Python'... | [
"I rewrote the emailing logic :\n#!/usr/bin/python -tt\n\nfrom email.mime.text import MIMEText\nfrom datetime import date\nimport smtplib\n\nSMTP_SERVER = \"smtp.gmail.com\"\nSMTP_PORT = 587\nSMTP_USERNAME = \"email@gmail.com\"\nSMTP_PASSWORD = \"yourpassword\"\n\nEMAIL_TO = [\"recepient1@gmail.com\", \"recepient2@... | [
20,
2
] | [] | [] | [
"email",
"python"
] | stackoverflow_0008321586_email_python.txt |
Q:
How to extract particular set of value from a file in Python?
I am stuck with the logic here... i have to extract some values from a text file that looks like this
AAA
+-------------+------------------+
| ID | count |
+-------------+------------------+
| 3 | 1445 |
| ... | How to extract particular set of value from a file in Python? | I am stuck with the logic here... i have to extract some values from a text file that looks like this
AAA
+-------------+------------------+
| ID | count |
+-------------+------------------+
| 3 | 1445 |
| 4 | 105 |
| 9 | 160 |
| ... | [
"d = {}\nwith open(sys.argv[1]) as f:\n for line in f:\n if line[0].isalpha(): # is first character in the line a letter?\n curr = d.setdefault(line.strip(), [])\n elif filter(str.isdigit, line): # is there any digit in the line?\n curr.append(line.strip())\n\nfor this file, d... | [
3,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0008353044_python.txt |
Q:
how to change xml element name in django-piston?
I'm new with django-piston and whenever i get/post data to xml, the xml's element is always
and < resource >
<response>
<resource>
<resource>4</resource>
<resource>0</resource>
<resource>2011-11-30</resource>
</resource>
<resource>
<resource>4</resource>
<res... | how to change xml element name in django-piston? | I'm new with django-piston and whenever i get/post data to xml, the xml's element is always
and < resource >
<response>
<resource>
<resource>4</resource>
<resource>0</resource>
<resource>2011-11-30</resource>
</resource>
<resource>
<resource>4</resource>
<resource>4</resource>
<resource>2011-12-01</resource>
</... | [
"You have to write your own XMLEmitter. Here's one that always uses the tag product instead of resource.\nMaking it intelligent requires a bit more work, since models are serialized into dicts in Emitter.construct() method and it's impossible to extend properly. It would be nice to know the original model class in ... | [
2,
0
] | [] | [] | [
"django",
"django_piston",
"python",
"xml"
] | stackoverflow_0008352350_django_django_piston_python_xml.txt |
Q:
Save Python scripts with .py extension automatically
In Python IDE, while we save the script, it will prompt the save Dialog. If we specify the filename as "Test". Then file will be saved without extension as "Test" and not "Test.py".
Is it possible to save the script with .py extension automatically (as Test.py)?... | Save Python scripts with .py extension automatically | In Python IDE, while we save the script, it will prompt the save Dialog. If we specify the filename as "Test". Then file will be saved without extension as "Test" and not "Test.py".
Is it possible to save the script with .py extension automatically (as Test.py)?
| [
"Unfortunately, IDLE doesn't and can't add the .py extension automatically; you will just have to get into the habit of adding it yourself, or use another IDE like Eclipse or Komodo that will do it for you.\n",
"There is a bug report for IDLE about this: http://bugs.python.org/issue10364\nIf you want, you can edi... | [
2,
0
] | [] | [] | [
"python",
"python_idle",
"save"
] | stackoverflow_0008048702_python_python_idle_save.txt |
Q:
How do I open a .py file in IDLE for editing without starting a fresh interpreter session?
Python for Windows has built in support for right clicking a .py file, and selecting, "edit with IDLE", instead of the usual action, which is running the file.
How can I accomplish this same setup on Linux? I am running Mint... | How do I open a .py file in IDLE for editing without starting a fresh interpreter session? | Python for Windows has built in support for right clicking a .py file, and selecting, "edit with IDLE", instead of the usual action, which is running the file.
How can I accomplish this same setup on Linux? I am running Mint Julia, a Debian-type distribution. Selecting my default program from the shortcut menu will onl... | [
"In IDLE's menu, go to Options -> Configure IDLE... -> General. Under \"At Startup\" select \"Open Edit Window\" instead of \"Open Shell Window\", then hit Apply or Ok. IDLE will save this setting and from now on will open just an editor window when you open a file.\n",
"You'll need to change the command to start... | [
2,
0
] | [] | [] | [
"linux",
"python",
"python_idle"
] | stackoverflow_0007775254_linux_python_python_idle.txt |
Q:
Subscripting Strings in django templates
Is it possible to subscript strings in django templates ?
What i mean is doing
print "hello"[:3]
=> hel
in django templates.
Writing {{ stringVar[:10] }} throws
TemplateSyntaxError: Could not parse the remainder: '[:10]' from 'stringVar[:10]'
A:
You can, but the syntax ... | Subscripting Strings in django templates | Is it possible to subscript strings in django templates ?
What i mean is doing
print "hello"[:3]
=> hel
in django templates.
Writing {{ stringVar[:10] }} throws
TemplateSyntaxError: Could not parse the remainder: '[:10]' from 'stringVar[:10]'
| [
"You can, but the syntax is slightly different as what you're used to. Use slice:\n{{ stringVar|slice:\":2\" }}\n\nThis will give you the first 2 elements from the list (or the first two chars from a string).\n"
] | [
7
] | [] | [] | [
"django",
"django_templates",
"python",
"string",
"subscript"
] | stackoverflow_0008353370_django_django_templates_python_string_subscript.txt |
Q:
setting up the environment when changing to another user
I have a bash backup script run as root (cron) that delegates certain tasks to other specific bash scripts owned by different users. (simplified example, principle is, some things have to be done as root, different tasks are delegated to users with the appro... | setting up the environment when changing to another user | I have a bash backup script run as root (cron) that delegates certain tasks to other specific bash scripts owned by different users. (simplified example, principle is, some things have to be done as root, different tasks are delegated to users with the appropriate environment (oracle, amazon, ...)
mkdir -p /tmp/backup$... | [
"\nall environment variables of that user are set\n\nUsually because a shell runs a .profile file when it starts up.\nYou have several choices. \n\nCreate a proper subprocess with subprocess.Popen to execute the shell .profile -- same as su -.\nCarefully locate the environment variable settings and mimic them in Py... | [
1,
0
] | [] | [] | [
"environment_variables",
"python",
"setuid"
] | stackoverflow_0003529348_environment_variables_python_setuid.txt |
Q:
How can I share one webdriver instance in my test classes in the suite? I use Selenium2 and Python
My code is like this:
class class1(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
def testListRolesTitle(self):
driver=self.driver
driver.get("www.google.com")... | How can I share one webdriver instance in my test classes in the suite? I use Selenium2 and Python | My code is like this:
class class1(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
def testListRolesTitle(self):
driver=self.driver
driver.get("www.google.com")
def tearDown(self):
self.driver.quit()
self.assertEqual([], self.verificationError... | [
"You can have a setup function that applies to the whole module instead of just to the class as explained here.\nIn your case, that would be something like:\ndef setUpModule():\n DRIVER = webdriver.Firefox()\n\ndef tearDownModule():\n DRIVER.quit()\n\nNote that DRIVER is a global variable in this case so that... | [
3
] | [] | [] | [
"python",
"selenium",
"unit_testing",
"webdriver"
] | stackoverflow_0008352929_python_selenium_unit_testing_webdriver.txt |
Q:
python for loop list plus one item
I'm handling mouse clicks on objects based on the location of the object on the screen. I record the xy coord of the mouse click and see if it matches any of the objects that are allowed to be clicked on. The objects are in different lists or just single objects, but I want them ... | python for loop list plus one item | I'm handling mouse clicks on objects based on the location of the object on the screen. I record the xy coord of the mouse click and see if it matches any of the objects that are allowed to be clicked on. The objects are in different lists or just single objects, but I want them in one big list so I can just loop throu... | [
"For 2nd method you need itertools.chain\nfor item in itertools.chain(list, [singleobj]):\n ...\n\n",
"DrTyrsa's answer is what I was about to say about your precise question, but let me give you a few other tips:\ncopylist = list\ncopylist.append(singleobj)\n\nthis does not create a copy of the list, you migh... | [
11,
4
] | [] | [] | [
"list",
"python"
] | stackoverflow_0008353676_list_python.txt |
Q:
Python: How do I make a button freeze when I press it? - Tkinter
This is a memory game where the user selects two buttons (cells). If the two words behind the cells match, the words stays visible else the cells goes hidden and u can't see the words behind them. What I want to do is to make a cell freeze if it show... | Python: How do I make a button freeze when I press it? - Tkinter | This is a memory game where the user selects two buttons (cells). If the two words behind the cells match, the words stays visible else the cells goes hidden and u can't see the words behind them. What I want to do is to make a cell freeze if it shows the word behind it when it is pressed. I want to apply that function... | [
"You could disable the button when it should not be clickable anymore:\ncell.button.config(state = DISABLED)\n\n"
] | [
1
] | [] | [] | [
"button",
"python",
"tkinter"
] | stackoverflow_0008345230_button_python_tkinter.txt |
Q:
What are best/easiest Apache server/folder settings for allowing a python script to create a file?
I have a simple Python script in folder "fold" that is launched from a PHP file. It creates a file on the same directory then exits back to PHP.
f = open("t.txt","w")
f.write("test")
f.close()
You can call it from P... | What are best/easiest Apache server/folder settings for allowing a python script to create a file? | I have a simple Python script in folder "fold" that is launched from a PHP file. It creates a file on the same directory then exits back to PHP.
f = open("t.txt","w")
f.write("test")
f.close()
You can call it from PHP with:
$proc=proc_open("fold/simple.py",array(0=>array('pipe','r'),1=>array('pipe','w'),2=>array('pipe... | [
"from my experience, I suggest you create a directory which is only for creating files by your program, maybe files or something, and set the permission to 777(chmod -R 777 files), and other directory should be 755, for security reasons. \n",
"As said by everybody, in general it's not good to set a directory with... | [
0,
0
] | [] | [] | [
"apache",
"linux",
"php",
"python"
] | stackoverflow_0007914109_apache_linux_php_python.txt |
Q:
Read file continuously and update Python GTK application accordingly
I am working on a gesture recognition project. There is a C program that captures the gestures from video input and write them to the file. Now, I have an image viewer written in Python - GTK. It switches to the next or previous window according ... | Read file continuously and update Python GTK application accordingly | I am working on a gesture recognition project. There is a C program that captures the gestures from video input and write them to the file. Now, I have an image viewer written in Python - GTK. It switches to the next or previous window according to gestures. This continuous file read and application update is defined a... | [
"Not sure if I understand you correctly, but I would expect what you want to do is to schedule a call to ai() in your main GTK loop, so that your program checks if there is input on a regular base.\nIf this is what you want you have two choices: scheduling the call periodically or schedule the call for when the pro... | [
6,
2,
1
] | [] | [] | [
"events",
"gtk",
"python"
] | stackoverflow_0008353672_events_gtk_python.txt |
Q:
Ogg Vorbis wrapper in Python for Windows
I've found a small program written in Python which helps me to solve one problem. This program uses PyOgg wrapper to work with Ogg files. PyOgg was written for unix-based systems. Can you tell me if there's any Python Ogg wrapper for Windows? Or maybe anybody can help me to... | Ogg Vorbis wrapper in Python for Windows | I've found a small program written in Python which helps me to solve one problem. This program uses PyOgg wrapper to work with Ogg files. PyOgg was written for unix-based systems. Can you tell me if there's any Python Ogg wrapper for Windows? Or maybe anybody can help me to compile PyOgg under Windows?
| [
"Try audiolab.\n"
] | [
0
] | [] | [] | [
"audio",
"ogg",
"python",
"windows"
] | stackoverflow_0008353963_audio_ogg_python_windows.txt |
Q:
convert data type and then load data into Mysql by Python
Besides LOAD DATA INFILE command, is there any other way to read a .txt file which contains three columns into Mysql? I want to read the data line by line and put them into a table in Mysql.
It is impossible to convert the datatype in the followingLOAD DATA... | convert data type and then load data into Mysql by Python | Besides LOAD DATA INFILE command, is there any other way to read a .txt file which contains three columns into Mysql? I want to read the data line by line and put them into a table in Mysql.
It is impossible to convert the datatype in the followingLOAD DATA INFILE command, right?
LOAD DATA INFILE 'filename' into TABLE... | [
"I've tried the following which works:\ncreate table info (s datetime not null primary key, str varchar(100), str2 varchar(100));\n\nload data local infile '/home/maartenl/sample.txt' \ninto table info (@s, str, str2) \nset s = from_unixtime(@s);\n\nAnd that works fine with your sample set.\n"
] | [
1
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0008354078_mysql_python.txt |
Q:
Connect python to oracle
I have installed oracle client and oracle client-dev, and setup ORACLE_HOME environment variable. Yet when I attempt to install tux_oracle (python setup.py build) I get the following:
fatal error: oci.h: No such file or directory
A:
Well, the answer is to install cx_Oracle not tx_Oracle.... | Connect python to oracle | I have installed oracle client and oracle client-dev, and setup ORACLE_HOME environment variable. Yet when I attempt to install tux_oracle (python setup.py build) I get the following:
fatal error: oci.h: No such file or directory
| [
"Well, the answer is to install cx_Oracle not tx_Oracle. The way to do it in Ubuntu is the following:\n\nYou must have the oracle client installed in your PC. If not download from oracle http://www.oracle.com/technetwork/topics/linuxsoft-082809.html. \nInstall alien in your PC to be able to convert rpm to deb:\n\ns... | [
6,
1,
1
] | [] | [] | [
"cx_oracle",
"oracle",
"python"
] | stackoverflow_0008266568_cx_oracle_oracle_python.txt |
Q:
extracting individual email from a single thunderbird email data file
I have a thunderbird email data file from which I need to extract individual email. I tried to use regex and do plain vanilla extract based on from tag but this doesn't give me the required result. An email can have another email attached within... | extracting individual email from a single thunderbird email data file | I have a thunderbird email data file from which I need to extract individual email. I tried to use regex and do plain vanilla extract based on from tag but this doesn't give me the required result. An email can have another email attached within the body hence a single email can have more than one "From:" strings. How ... | [
"Try the python mailbox module.\nThe mailbox module can read mbox/maildir message stores.\n"
] | [
1
] | [] | [] | [
"email",
"parsing",
"python",
"regex",
"thunderbird"
] | stackoverflow_0008354535_email_parsing_python_regex_thunderbird.txt |
Q:
Problem using PySide / PyQt
I'm trying to install PySide to use the Qt libraries for scraping a website. I was following the instructions on this site and installed PySide using MacPorts (py26-pyside).
This command:
from PySide.QtCore import *
Works fine. But:
from PySide.QtGui import *
gives me this error:
Tr... | Problem using PySide / PyQt | I'm trying to install PySide to use the Qt libraries for scraping a website. I was following the instructions on this site and installed PySide using MacPorts (py26-pyside).
This command:
from PySide.QtCore import *
Works fine. But:
from PySide.QtGui import *
gives me this error:
Traceback (most recent call last):
... | [
"It not a good idea mix use system build-in python(version 2.6) and PySide install by manual.\nI got the same problem before and fix it after upgrade to py27-pyside.\nplease try py27-pyside via MacPorts\nsudo port install py27-pyside\n\n"
] | [
0
] | [] | [] | [
"pyqt",
"pyside",
"python",
"qt"
] | stackoverflow_0006376898_pyqt_pyside_python_qt.txt |
Q:
C++ API as an Python Extension Module
Can APIs written in C or C++ always be made into a library, given source code, and consequently be called from Python, due to the intrinsic callable nature of an API?
In other words, given a C/C++ API can you run a setup.py script using distutils on the source and effectively ... | C++ API as an Python Extension Module | Can APIs written in C or C++ always be made into a library, given source code, and consequently be called from Python, due to the intrinsic callable nature of an API?
In other words, given a C/C++ API can you run a setup.py script using distutils on the source and effectively use the C/C++ API from python programs?
| [
"It's a bit more involved than running a setup.py script, but there are tools to wrap C/C++ libraries so you can use them from Python. Some popular ones are:\n\nCython - you write Python-style code, but you can cimport C libraries and call their functions. Cython code is then translated to C and compiled. There's a... | [
1,
0,
0
] | [] | [] | [
"api",
"c++",
"python"
] | stackoverflow_0008350269_api_c++_python.txt |
Q:
gunicorn_django error "cannot find myproject.settings in your PYTHONPATH"
I can run gunicorn_django on the root dir of my project, but when i set all thing in supervisor I got this error message "Error: Can't find 'myproject.settings' in your PYTHONPATH."
my supervisor setting:
command=/usr/local/django/myproject/... | gunicorn_django error "cannot find myproject.settings in your PYTHONPATH" | I can run gunicorn_django on the root dir of my project, but when i set all thing in supervisor I got this error message "Error: Can't find 'myproject.settings' in your PYTHONPATH."
my supervisor setting:
command=/usr/local/django/myproject/gunicorn_django -c /usr/local/django/myproject/gunicorn.conf.py
directory=/u... | [
"Make sure gunicorn is in your INSTALLED_APPS and change command to this:\ncommand=/path/to/python /path/to/manage.py run_gunicorn -c /path/to/gunicorn.conf.py \n\n",
"Also, check for missing Python dependencies. I've had Django crash in a similar fashion when there were missing Python libs. \n"
] | [
1,
0
] | [] | [] | [
"gunicorn",
"python"
] | stackoverflow_0007020162_gunicorn_python.txt |
Q:
Deploy django using apache, mod-wsgi
I'm trying to deploy django using wsgi. But its not working. Will you please help me ? thank you
django.wsgi.py
#!/usr/bin/python
import os, sys
sys.path.append('/home/me/project')
os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings'
import django.core.handlers.wsgi
appli... | Deploy django using apache, mod-wsgi | I'm trying to deploy django using wsgi. But its not working. Will you please help me ? thank you
django.wsgi.py
#!/usr/bin/python
import os, sys
sys.path.append('/home/me/project')
os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHan... | [
"It should be obvious that your error message is coming from a different file than the one you have shown here - me rather than default. That file apparently has a reference to PythonHandler, which is a directive that belongs to mod_python which you don't seem to have installed (and shouldn't, as it is deprecated).... | [
3,
1,
1
] | [] | [] | [
"django",
"mod_wsgi",
"python"
] | stackoverflow_0008353886_django_mod_wsgi_python.txt |
Q:
Pycrypto aes 256 Initialization vector size
here's the case i have a php script that's using aes256 ,CBC
the both key and IV size are 32 bytes long
data= '123456789abcdef'
from Crypto.Cipher import AES
a = AES.new('oqufXQ(?bc=6_hR2I3sMZChDpb6dDlw4',2,'fOaiIOkD8*9Xeu_s4_bb87Ox_UG+D9GA')
print a.encrypt(data)
an... | Pycrypto aes 256 Initialization vector size | here's the case i have a php script that's using aes256 ,CBC
the both key and IV size are 32 bytes long
data= '123456789abcdef'
from Crypto.Cipher import AES
a = AES.new('oqufXQ(?bc=6_hR2I3sMZChDpb6dDlw4',2,'fOaiIOkD8*9Xeu_s4_bb87Ox_UG+D9GA')
print a.encrypt(data)
and the error i got
<type 'exceptions.ValueError'>:... | [
"Aha!\nThere's a difference of opinion what the \"256\" refers to.\nAES has a fixed block size of 128 bits, so \"AES 256\" means 128 bit blocks, 256 bit key, 14 rounds.\nHowever, Rijndael allows both the key size and the block size to vary. MCRYPT_RIJNDAEL_256 refers to Rijndael with block size set to 256 (and I do... | [
11
] | [] | [] | [
"aes",
"google_app_engine",
"pycrypto",
"python"
] | stackoverflow_0008345756_aes_google_app_engine_pycrypto_python.txt |
Q:
Python GUI both compatible GTK2 and GTK3
I'd like to create a graphical interface in python2 with GTK+.
For now I'm using gobject-introspection to use GTK3 but I'd like, if possible, to be compatible with GTK2 as well.
#!/usr/bin/python2
try:
from gi.repository import Gtk
except:
try:
import gtk as... | Python GUI both compatible GTK2 and GTK3 | I'd like to create a graphical interface in python2 with GTK+.
For now I'm using gobject-introspection to use GTK3 but I'd like, if possible, to be compatible with GTK2 as well.
#!/usr/bin/python2
try:
from gi.repository import Gtk
except:
try:
import gtk as Gtk
except:
print("You need GTK")... | [
"Substantially the choice boils down to:\n\nWrite for GTK2 directly (GTK3 is backward compatible)\nWrite alternate implementations of parts of your UI for those widgets that are not available in GTK2.\n\nIn the second case, if you use good separation between your interface and your logic you won't need to write \"t... | [
2
] | [] | [] | [
"gtk",
"pygobject",
"pygtk",
"python"
] | stackoverflow_0008354964_gtk_pygobject_pygtk_python.txt |
Q:
pymongo: Add field containing a dict
Right now my mongo document has normal key/value pairs in it.
I want to add a field (staff) that is a dict. I can run this code, and it doesn't complain, but the users field does not show up when I find the object. The object shows up as if it was never added.
staff = {'foo':... | pymongo: Add field containing a dict | Right now my mongo document has normal key/value pairs in it.
I want to add a field (staff) that is a dict. I can run this code, and it doesn't complain, but the users field does not show up when I find the object. The object shows up as if it was never added.
staff = {'foo':{'name':'Jack S.', 'title':'Pirate'}, 'bar... | [
"try\nships.update(\n {'_id': 1}, \n {\"$set\": {'staff': staff}},\n false,true\n) \n\n** you were missing closing bracket. also your staff variable doesnt seems to a correct dictionary.it looks like list of dict. please check .\n"
] | [
1
] | [] | [] | [
"pymongo",
"python"
] | stackoverflow_0008354610_pymongo_python.txt |
Q:
python-setuptools pkg_resources.py SyntaxError: invalid token
Got this error on installing Python as usual on my workstation @ work (Windows environment):
Traceback (most recent call last):
File "C:\Python27\Scripts\django-admin.py", line 4, in <module>
import pkg_resources
File "C:\Python27\Lib\site-packa... | python-setuptools pkg_resources.py SyntaxError: invalid token | Got this error on installing Python as usual on my workstation @ work (Windows environment):
Traceback (most recent call last):
File "C:\Python27\Scripts\django-admin.py", line 4, in <module>
import pkg_resources
File "C:\Python27\Lib\site-packages\pkg_resources.py", line 29
def _bypass_ensure_directory(nam... | [
"You are somehow running django-admin.py under Python 3. The octal literal syntax was changed in Python 3. The error you get is Python 3 complaining about Python 2.x octal literal syntax.\nHow do you invoke django-admin.py? You are somehow invoking django-admin.py in such a way that Python 3 is used.\nPerhaps you d... | [
2
] | [] | [] | [
"python",
"setuptools"
] | stackoverflow_0008355665_python_setuptools.txt |
Q:
how to insert into DB from XMl using python multithreading?
Could someone please advice me what are the possible ways with python multithreading?
I have one xml file (163 MB). My task is required to
read that xml file
insert the data into a DB ( many tables)
record the count of inserted rows in a log file
I alr... | how to insert into DB from XMl using python multithreading? | Could someone please advice me what are the possible ways with python multithreading?
I have one xml file (163 MB). My task is required to
read that xml file
insert the data into a DB ( many tables)
record the count of inserted rows in a log file
I already have python code that reads an xml file that does the above ... | [
"I've had a look through your code. I don't think that multithreading is the answer to your problems.\n\nNot all xml libraries are equal, lxml is a python interface to libxml2, which is written in C and the fastest I've used.\nConsider, if you haven't already, which operations are comparitively expensive time-wise.... | [
1,
0
] | [] | [] | [
"multithreading",
"python",
"xml"
] | stackoverflow_0008324502_multithreading_python_xml.txt |
Q:
how to read two digit from a file, XOR it with (0x91) and print to screen?
i try to read file of bytes written in hex for example: (909090) which is nop nop nop in assembly, i want to xor each two digit as a byte with the 0x91.
how do i print the value in hex? now it prints just numbers with no meaning.
in general... | how to read two digit from a file, XOR it with (0x91) and print to screen? | i try to read file of bytes written in hex for example: (909090) which is nop nop nop in assembly, i want to xor each two digit as a byte with the 0x91.
how do i print the value in hex? now it prints just numbers with no meaning.
in general i want to build a packer to my assembly code.
def add_prefix(a):
a = str(a)... | [
"The algorithm needed is quite simple:\n\nread two characters at a time\nconvert these to an integer\nXor the integer with your mask (0x91)\nConvert the integer back to a hex string (with leading zero)\n\n\nwith open(file_path, 'r') as fp:\n result = []\n while True:\n # 1.\n s = fp.read(2)\n ... | [
3,
2,
1
] | [] | [] | [
"hex",
"python",
"xor"
] | stackoverflow_0008354575_hex_python_xor.txt |
Q:
Is it a bad idea to learn Ruby and Python simutaneusly?
I'm learning these Ruby and Python interactively and simultaneously. My goal is to learn them at the same time so that I can decide which one I like the most. Is it a bad idea to learn them simutaneusly?
A:
Not really, but both (Python & Ruby) languages are... | Is it a bad idea to learn Ruby and Python simutaneusly? | I'm learning these Ruby and Python interactively and simultaneously. My goal is to learn them at the same time so that I can decide which one I like the most. Is it a bad idea to learn them simutaneusly?
| [
"Not really, but both (Python & Ruby) languages are somehow similar (scripting languages, dynamically typed, with powerful object & class systems). Learning a very different functional language like Haskell or Ocaml (in addition of Ruby or Python) will open more your mind.\n"
] | [
4
] | [] | [] | [
"python",
"ruby"
] | stackoverflow_0008356225_python_ruby.txt |
Q:
Comparing massive lists of dictionaries in python
I never actually thought I'd run into speed-issues with python, but I have. I'm trying to compare really big lists of dictionaries to each other based on the dictionary values. I compare two lists, with the first like so
biglist1=[{'transaction':'somevalue', 'id':'... | Comparing massive lists of dictionaries in python | I never actually thought I'd run into speed-issues with python, but I have. I'm trying to compare really big lists of dictionaries to each other based on the dictionary values. I compare two lists, with the first like so
biglist1=[{'transaction':'somevalue', 'id':'somevalue', 'date':'somevalue' ...}, {'transactio':'som... | [
"Index on the fields you want to use for lookup. O(n+m)\nmatches = []\nbiglist1_indexed = {}\n\nfor item in biglist1:\n biglist1_indexed[(item[\"transaction\"], item[\"date\"])] = item\n\nfor item in biglist2:\n if (item[\"transaction\"], item[\"date\"]) in biglist1_indexed:\n matches.append(item)\n\n... | [
19,
4,
1,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0000382466_python.txt |
Q:
wx.Display_GetCount doesn't update when (de)activating second monitor
I have an application which needs to be able to use multiple monitors. The monitors' parameters are displayed in a wx.Choice and they are updated on mouse-click on the widget.
Problem is that while the app is running if I unplug the second monit... | wx.Display_GetCount doesn't update when (de)activating second monitor | I have an application which needs to be able to use multiple monitors. The monitors' parameters are displayed in a wx.Choice and they are updated on mouse-click on the widget.
Problem is that while the app is running if I unplug the second monitor(the os switches to single monitor mode) the wx.Display_GetCount() value ... | [
"I am not sure this is going to help or not, but maybe you could try and bind the wx.EVT_DISPLAY_CHANGED event in your app and then call again wx.Display.GetCount(). The information out there about this event is pretty much non-existent, while as far as I can see wx.Display.GetCount() should rebuild the list of ava... | [
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0008356021_python_wxpython.txt |
Q:
Django Forms replacement for Google App Engine (Python)
I am looking for a Django Forms replacement.
I need auto-build form based on GAE Model as in Django.
Django Forms work with some bugs on GAE. And I need to replace it.
I have found WTForms. What is your choice?
A:
WTForms is a good choice on GAE. It is simi... | Django Forms replacement for Google App Engine (Python) | I am looking for a Django Forms replacement.
I need auto-build form based on GAE Model as in Django.
Django Forms work with some bugs on GAE. And I need to replace it.
I have found WTForms. What is your choice?
| [
"WTForms is a good choice on GAE. It is similar to django forms.\nAlso note, other than the ModelForms and the related types, django-forms should work quite well on the GAE, out of the box. In fact, that is one of the reason why django is even supported on GAE, in the first place.\n",
"I have looked for an answer... | [
2,
0
] | [] | [] | [
"django",
"django_forms",
"google_app_engine",
"python"
] | stackoverflow_0006408221_django_django_forms_google_app_engine_python.txt |
Q:
How to make this kind of equality array fast (in numpy)?
I have two numpy array (2 dimensional) e.g.
a1 = array([["a","b"],["a","c"],["b","b"],["a","b"]])
a2 = array([["a","b"],["b","b"],["c","a"],["a","c"]])
What is the most elegant way of getting a matrix like this:
array([[1,0,0,0],
[0,0,0,1],
[0... | How to make this kind of equality array fast (in numpy)? | I have two numpy array (2 dimensional) e.g.
a1 = array([["a","b"],["a","c"],["b","b"],["a","b"]])
a2 = array([["a","b"],["b","b"],["c","a"],["a","c"]])
What is the most elegant way of getting a matrix like this:
array([[1,0,0,0],
[0,0,0,1],
[0,1,0,0],
[1,0,0,0]])
Where element (i,j) is 1 if all(a... | [
">>> (a1[:,numpy.newaxis] == a2).all(axis=2)\narray([[ True, False, False, False],\n [False, False, False, True],\n [False, True, False, False],\n [ True, False, False, False]], dtype=bool)\n\nIf you really need integers, convert to int as last step:\n>>> (a1[:,numpy.newaxis] == a2).all(axis=2).... | [
10
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0008356745_numpy_python.txt |
Q:
hmm, lists, tuples, arrays, sets or dicts for this data structure?
Beginner programmer here. after a bunch of reading about 'variables' which dont exist in python, (still dont get that) Ive come to the opinion that I think I should be using lists in my data structure, but im not entirely sure.
im analysing a strin... | hmm, lists, tuples, arrays, sets or dicts for this data structure? | Beginner programmer here. after a bunch of reading about 'variables' which dont exist in python, (still dont get that) Ive come to the opinion that I think I should be using lists in my data structure, but im not entirely sure.
im analysing a string which contains commands and normal words to be printed out, if the wor... | [
"The problem here is you've misunderstood the concept of multidimensional lists (arrays). To annotate the expected output you appended to your question:\narglist[1] = 'my'\narglist[1][1] # equivalent to 'my'[1], so you get 'y'.\n # and you cannot assign anything to arglist[1][1] \n # becau... | [
2,
1,
1
] | [] | [] | [
"list",
"python",
"variables"
] | stackoverflow_0008356907_list_python_variables.txt |
Q:
How to fix NameError: Java error in HecDSS Python Script
I'm working on reading and writing information in HecDSS. I had this script working fine last night except when I opened it this morning I began getting this error:
ScriptEngine.execute:Error in script Traceback (innermost last):
File "<string>", l... | How to fix NameError: Java error in HecDSS Python Script | I'm working on reading and writing information in HecDSS. I had this script working fine last night except when I opened it this morning I began getting this error:
ScriptEngine.execute:Error in script Traceback (innermost last):
File "<string>", line 13, in ?
NameError: java
The basic code I'm using now... | [
"The * import imports all names from the module into the local namespace. So you you do:\nfrom java import *\n\nAnd the java modules has a submodule called lang, you can access it as lang, not java.lang.\nI don't know enough about Jython, but I think that you want something like this:\nimport java.lang\n\nIn which ... | [
1
] | [] | [] | [
"dss",
"java",
"python"
] | stackoverflow_0008357408_dss_java_python.txt |
Q:
how to install the 'pysparse' package using Enthought python, Windows XP SP3?
I am running on a Windows XP SP3 and currently have fresh installations of the following:
Enthought python Dist. version 7.1-2 (32-bit)
--> which set up a Python 2.7.2
pysparse-1.1.1.win32-py2.7.exe downloaded from - http://www.lfd.uc... | how to install the 'pysparse' package using Enthought python, Windows XP SP3? | I am running on a Windows XP SP3 and currently have fresh installations of the following:
Enthought python Dist. version 7.1-2 (32-bit)
--> which set up a Python 2.7.2
pysparse-1.1.1.win32-py2.7.exe downloaded from - http://www.lfd.uci.edu/~gohlke/pythonlibs/#pysparse
microsoft visual studio 2010
I need pysparse in... | [
"You can download the compiled Pysparse library for Windows system from the following website:\nhttp://www.lfd.uci.edu/~gohlke/pythonlibs/ \nThen just by running the related EXE file you can install the pysparse and import to your code. \n"
] | [
0
] | [] | [] | [
"dll",
"enthought",
"importerror",
"python"
] | stackoverflow_0007413292_dll_enthought_importerror_python.txt |
Q:
how to get the datetime.date() value from django model?
I have a problem in getting the datetime.date() value in my django...
when i trying to get it like this :
>>> s = Booking.objects.values('date_select').distinct('date_select').filter(date_select='2011-12-1')
>>> print s
[{'date_select': datetime.date(2011, 12... | how to get the datetime.date() value from django model? | I have a problem in getting the datetime.date() value in my django...
when i trying to get it like this :
>>> s = Booking.objects.values('date_select').distinct('date_select').filter(date_select='2011-12-1')
>>> print s
[{'date_select': datetime.date(2011, 12, 1)}]
it has the column of date_select, i just only want th... | [
"you are getting back a list with one element so you need to do this:\ns = Booking.objects.values('date_select').distinct('date_select').filter(date_select='2011-12-1')[0]['date_select']\n\n",
"Dimitry's answer works but it will raise an exception if your query does not return any results at all (because the inde... | [
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008351637_django_python.txt |
Q:
Regular Expression: Common string validation
I am doing some basic validation. The flow of the program goes like:
User inputs a string
Clicks SUBMIT
Now I want to make sure the following rules are fulfilled:
No spaces
Must be alphanumeric... no special charatcers! (ie !@#$%^&*)
Must start with a letter
Must be ... | Regular Expression: Common string validation | I am doing some basic validation. The flow of the program goes like:
User inputs a string
Clicks SUBMIT
Now I want to make sure the following rules are fulfilled:
No spaces
Must be alphanumeric... no special charatcers! (ie !@#$%^&*)
Must start with a letter
Must be at least 3 characters
How can I do this using pyt... | [
"You can do this in Python without regular expressions:\nif a.isalnum() and a[0].isalpha() and len(filter(str.isdigit, a)) >= 3:\n ...\n\nIf according to @Toomai \"3 digits\" are \"at least 3 characters long\", then this is what you need:\nif a.isalnum() and a[0].isalpha() and len(a) >= 3:\n ...\n\n",
"Try ... | [
6,
3
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0008357813_python_regex.txt |
Q:
Inherit a sub method in Python
I would like inherit a 'submethod' of a method in python. Could somebody help me to figure out how to do this please ?
Example of what I want to do :
class A(object):
def method(self, val):
def submethod():
return "Submethod action"
if not val:
... | Inherit a sub method in Python | I would like inherit a 'submethod' of a method in python. Could somebody help me to figure out how to do this please ?
Example of what I want to do :
class A(object):
def method(self, val):
def submethod():
return "Submethod action"
if not val:
return submethod()
... | [
"You can't \"inherit\" submethod since it's local to method and doesn't even exist until method is run.\nWhy not simply make it a top-level method of A and B?\n",
"This is called a closure (a function within a function) and does not quite behave like what you're asking. Because functions are not like classes, the... | [
4,
2
] | [] | [] | [
"inheritance",
"methods",
"python"
] | stackoverflow_0008357828_inheritance_methods_python.txt |
Q:
Why does HTMLParser miss some tags?
I used HTMLParser to count how many h2 tag in http://www.worldgolf.com/courses/usa/massachusetts/
here is the code:
class City2Parser(HTMLParser):
def handle_starttag(self,tag,attrs):
if tag == 'h2':
print 'h2'
req = urllib2.Request('http://www.world... | Why does HTMLParser miss some tags? | I used HTMLParser to count how many h2 tag in http://www.worldgolf.com/courses/usa/massachusetts/
here is the code:
class City2Parser(HTMLParser):
def handle_starttag(self,tag,attrs):
if tag == 'h2':
print 'h2'
req = urllib2.Request('http://www.worldgolf.com/courses/usa/massachusetts/')
ht... | [
"Look at what happens.\n>>> from HTMLParser import HTMLParser\n>>> import urllib2\n>>> class City2Parser(HTMLParser): \n... def handle_starttag(self,tag,attrs): \n... if tag == 'h2': \n... print 'h2'\n... \n>>> req = urllib2.Request('http://www.worldgolf.com/courses/usa/massachusetts/') \n>>... | [
1,
1
] | [] | [] | [
"html_parsing",
"python"
] | stackoverflow_0008356909_html_parsing_python.txt |
Q:
httplib python error
I'm trying to send an http get request via the httplib, but I'm facing issues.
conn = httplib.HTTPConnection("10.30.111.13/View")
conn.request("GET", "/Default.aspx")
res = conn.getresponse()
if res.status == 200:
print(res.status)
else:
... | httplib python error | I'm trying to send an http get request via the httplib, but I'm facing issues.
conn = httplib.HTTPConnection("10.30.111.13/View")
conn.request("GET", "/Default.aspx")
res = conn.getresponse()
if res.status == 200:
print(res.status)
else:
print("Something... | [
"I'm not someplace where I can test this now, but here's what I think:\nYou're passing only an IP address to a host field that's expecting a DNS address, not an IP address. That's why your second error listing says 'getaddrinfo' failed.\nThat said, I'm not sure how to use an IP address with httplib. Maybe try \"htt... | [
1,
0
] | [] | [] | [
"httplib",
"python"
] | stackoverflow_0008332658_httplib_python.txt |
Q:
How does Python's "import" work internally?
When you import a module, then reimport it again, will it get reimported/overwritten, or skipped?
When you import module "a" and "b", but also have module "b" imported in module "a", what happens? Is it safe to do this? For example if that module "b" has a class instanti... | How does Python's "import" work internally? | When you import a module, then reimport it again, will it get reimported/overwritten, or skipped?
When you import module "a" and "b", but also have module "b" imported in module "a", what happens? Is it safe to do this? For example if that module "b" has a class instantiated in it, will you end up instantiating it twic... | [
"import loads the matching .py, .pyc or .pyo file, creates a module object, and stores it with its fully qualified (\"dotted\") name in the sys.modules dictionary. If a second import finds the module to import in this dictionary, it will return it without loading the file again.\nTo answer your questions:\n\nWhen ... | [
7,
3
] | [] | [] | [
"import",
"module",
"python"
] | stackoverflow_0008358258_import_module_python.txt |
Q:
Equivalent to Java Topology Suite and Jena TBD in Python
I normally use the Java Topology Suite to handle 2D geometries in Java.
Is there a similar library in Python, supporting some spatial standard such as GML?
A:
Shapely (https://github.com/sgillies/shapely) is based on GEOS, the C/C++ port of JTS. JTS implem... | Equivalent to Java Topology Suite and Jena TBD in Python | I normally use the Java Topology Suite to handle 2D geometries in Java.
Is there a similar library in Python, supporting some spatial standard such as GML?
| [
"Shapely (https://github.com/sgillies/shapely) is based on GEOS, the C/C++ port of JTS. JTS implements OGC simple features, not GML. Shapely doesn't read/write GML either.\n"
] | [
3
] | [] | [] | [
"geometry",
"java",
"python",
"topology"
] | stackoverflow_0008357070_geometry_java_python_topology.txt |
Q:
Problems with creating custom chainable query set manager
In my project I'm using code from http://djangosnippets.org/snippets/562/ and I'm encountering some problems.
When I use my own ChainableQuerySetManager and try to create an object through a related object I get a recursion error.
ChainableQuerySetManager s... | Problems with creating custom chainable query set manager | In my project I'm using code from http://djangosnippets.org/snippets/562/ and I'm encountering some problems.
When I use my own ChainableQuerySetManager and try to create an object through a related object I get a recursion error.
ChainableQuerySetManager source:
class ChainableQuerySetManager(models.Manager):
... | [
"I recently had a similar issue. Try replacing self.__class__ with ChainableQuerySetManager in your query manager. I never quite sorted out exactly why this was the issue, but it did solve things for me.\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008355606_django_python.txt |
Q:
formatting files with sed/ python/ etc
I have a file which is created by a program. It contains html code and propitiatory calls to other software. In this file there are many variations of:
<td>$GETR("wp","1")$Yes$GETR("","2")$No$NOTE()$</td>
so it could be:
<td>$GETR("dc","1")$Yes$GETR("","2")$NO$GETR("","3")$N... | formatting files with sed/ python/ etc | I have a file which is created by a program. It contains html code and propitiatory calls to other software. In this file there are many variations of:
<td>$GETR("wp","1")$Yes$GETR("","2")$No$NOTE()$</td>
so it could be:
<td>$GETR("dc","1")$Yes$GETR("","2")$NO$GETR("","3")$NA$NOTE()$</td>
or:
<td>$GETR("tc","1")$Yes$... | [
"This is what you are desiring?\n>>> x='<td>$GETR(\"wp\",\"1\")$Yes$GETR(\"\",\"2\")$No$NOTE()$</td>'\n>>> if x.count(\"$GETR\")>1:\n x=x.replace(\"$GETR\",\"\\n\\t$GETR\").replace(\"</td>\",\"\\n</td>\")\n\n\n>>> print x\n<td>\n $GETR(\"wp\",\"1\")$Yes\n $GETR(\"\",\"2\")$No$NOTE()$\n</td>\n>>> x='<td>$GE... | [
1,
1
] | [] | [] | [
"formatting",
"python",
"replace",
"sed",
"solaris"
] | stackoverflow_0008355262_formatting_python_replace_sed_solaris.txt |
Q:
When running my django webapp on my local box, why am I getting a blank screen with firefox 7.0.1
I have two web apps written in Django 1.1. In the past, I have never had problems running them on my local computer via http://127.0.0.1:8000. Recently, my firefox was upgraded to v. 7.0.1. Now, from time to time a... | When running my django webapp on my local box, why am I getting a blank screen with firefox 7.0.1 | I have two web apps written in Django 1.1. In the past, I have never had problems running them on my local computer via http://127.0.0.1:8000. Recently, my firefox was upgraded to v. 7.0.1. Now, from time to time and for various urls, firefox will display a blank screen or a partial screen - something that never hap... | [
"It could be something to do with the cache. Have you set the about:config settings so no caching takes place.\n"
] | [
1
] | [] | [] | [
"django",
"firefox",
"python"
] | stackoverflow_0007687273_django_firefox_python.txt |
Q:
Why claim a python class could be "better" implemented as a dictionary plus some functions?
I saw this instruction in an answer to the question Python progression path - From apprentice to guru.
9. Annoy your cubicle mates every time they present you with a Python class. Claim it could be "better" implemented as... | Why claim a python class could be "better" implemented as a dictionary plus some functions? | I saw this instruction in an answer to the question Python progression path - From apprentice to guru.
9. Annoy your cubicle mates every time they present you with a Python class. Claim it could be "better" implemented as a dictionary plus some functions. Embrace functional programming.
But I don't understand this. ... | [
"It means that:\nclass A:\n def __init__(this):\n this.count = 0\n def bump(this):\n this.count += 1\n\na = A()\na.bump()\n\ncan be replaced by something along the lines of:\ndef constructA():\n return {'count':0}\n\ndef bumpA(anA):\n anA['count'] += 1\n\na = constructA()\nbumpA(a)\n\nor, ... | [
3,
3
] | [] | [] | [
"functional_programming",
"python"
] | stackoverflow_0008357799_functional_programming_python.txt |
Q:
assign the result of an list operation to var
In python,
how can i do something like that
a = ["pera", "uva", "maca", "saladamista"]
b = a.reverse()
but without assign the reverse list to a?
A:
First copy the list, then reverse the copy:
a = ["pera", "uva", "maca", "saladamista"]
b = a[:]
b.reverse()
or use th... | assign the result of an list operation to var | In python,
how can i do something like that
a = ["pera", "uva", "maca", "saladamista"]
b = a.reverse()
but without assign the reverse list to a?
| [
"First copy the list, then reverse the copy:\na = [\"pera\", \"uva\", \"maca\", \"saladamista\"]\nb = a[:]\nb.reverse()\n\nor use the \"Martian smiley\":\nb = a[::-1]\n\nEdit: In case someone is interested in timings, here they are:\nIn [1]: a = range(100000)\n\nIn [2]: %timeit b = a[:]; b.reverse()\n1000 loops, be... | [
7,
6
] | [] | [] | [
"python"
] | stackoverflow_0008359557_python.txt |
Q:
How can I tell if an Expando subclass has a property defined?
I'm creating an app that I want to have an expandable set of properties (each a RatingProperty) I also want to validate that any dynamic properties are of the RatingProperty type.
In the Expando documentation it says:
Tip: If you want to validate a dy... | How can I tell if an Expando subclass has a property defined? | I'm creating an app that I want to have an expandable set of properties (each a RatingProperty) I also want to validate that any dynamic properties are of the RatingProperty type.
In the Expando documentation it says:
Tip: If you want to validate a dynamic property value using a Property class, you can instantiate th... | [
"After a bit more research (damn you lazyweb!) I've found a solution that I think is acceptable: \nA dynamic property can't be of a db subclassed property type. Thus, there are two distinct steps that must be taken. First you need to create an instance of your property class and validate your value: \ntest = db.R... | [
1,
1,
0,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0000417584_google_app_engine_python.txt |
Q:
switching letters to different letters inside a string (Caesar cipher)
I've got some homework involving Caesar cipher, and I got stuck here:
I need to write a function which gets a text (as a String) and a dictionary. The dictionary keys are the English ABC, and its values are other letters from the ABC.
My goal i... | switching letters to different letters inside a string (Caesar cipher) | I've got some homework involving Caesar cipher, and I got stuck here:
I need to write a function which gets a text (as a String) and a dictionary. The dictionary keys are the English ABC, and its values are other letters from the ABC.
My goal is to go over the text, and wherever there is a letter (only letters!)
change... | [
"You're looking for the translate method:\n>>> u\"abc\".translate({ord('a'): u'x', ord('b'): u'y', ord('c'): u'z'})\n'xyz'\n\nLook at maketrans if you're using bytestrings or if your Python is older than 2.7.\n",
"A bit of pseudocode (language agnostic). You should be able to take it from here.\ncipher = array\nc... | [
3,
2,
2
] | [] | [] | [
"encryption",
"python",
"string"
] | stackoverflow_0008359650_encryption_python_string.txt |
Q:
Efficiently Row Standardize a Matrix
I need an efficient way to row standardize a sparse matrix.
Given
W = matrix([[0, 1, 0, 1, 0, 0, 0, 0, 0],
[1, 0, 1, 0, 1, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 1, 0, 0, 0],
[1, 0, 0, 0, 1, 0, 1, 0, 0],
[0, 1, 0, 1, 0, 1, 0, 1, 0],
... | Efficiently Row Standardize a Matrix | I need an efficient way to row standardize a sparse matrix.
Given
W = matrix([[0, 1, 0, 1, 0, 0, 0, 0, 0],
[1, 0, 1, 0, 1, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 1, 0, 0, 0],
[1, 0, 0, 0, 1, 0, 1, 0, 0],
[0, 1, 0, 1, 0, 1, 0, 1, 0],
[0, 0, 1, 0, 1, 0, 0, 0, 1],
... | [
"with a bit of matrix algebra\n>>> cc\n<9x9 sparse matrix of type '<type 'numpy.int32'>'\n with 24 stored elements in Compressed Sparse Row format>\n>>> ccd = sparse.spdiags(1./cc.sum(1).T, 0, *cc.shape)\n>>> ccn = ccd * cc\n>>> np.round(ccn.todense(), 2)\narray([[ 0. , 0.5 , 0. , 0.5 , 0. , 0. , 0. ,... | [
6
] | [] | [] | [
"matrix",
"numpy",
"python",
"scipy"
] | stackoverflow_0008358962_matrix_numpy_python_scipy.txt |
Q:
How to get objects if user is in a field of another django model's many-to-many field?
I have the models:
class Project(models.Model):
title = models.CharField(max_length=75)
description = models.CharField(max_length=250)
...
class Node(models.Model):
title = models.CharField(max_length=75)
collab... | How to get objects if user is in a field of another django model's many-to-many field? | I have the models:
class Project(models.Model):
title = models.CharField(max_length=75)
description = models.CharField(max_length=250)
...
class Node(models.Model):
title = models.CharField(max_length=75)
collaborators = models.ManyToManyField(User)
project = models.ForeignKey(Project)
What I'm tr... | [
"Project.objects.filter(node__collaborators=my_user)\n\n"
] | [
2
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0008359717_django_django_models_python.txt |
Q:
request.user in Django Form
I'm having a problem accessing a Django Form POST data.
I need to pass request.user to the form, so:
class TradeForForm(forms.Form):
def __init__(self, *args, **kwargs):
user = kwargs.pop('user')
else:
request = kwargs.pop('request')
super(TradeForForm, self).__init_... | request.user in Django Form | I'm having a problem accessing a Django Form POST data.
I need to pass request.user to the form, so:
class TradeForForm(forms.Form):
def __init__(self, *args, **kwargs):
user = kwargs.pop('user')
else:
request = kwargs.pop('request')
super(TradeForForm, self).__init__(*args, **kwargs)
#Obtain i... | [
"you should probably pass the user to the form creator even with POST data so the choices can be validated properly, so\nTradeForForm(request.POST, user=request.user)\n\nif you don't want this, you need to change user = kwargs.pop('user') to something like\nuser = kwargs.pop('user', None)\n# if kwargs has no key 'u... | [
5,
2,
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008357607_django_python.txt |
Q:
Array indexing in Numpy python
How can I define _SOME CODE_ in the next code fragment in order to get the results shown below?
vector = numpy.array([a,b,c,d])
for i in xrange(4):
print vector[_SOME CODE_ using i]
It sould give me those results:
[a,b,c]
[a,c,d]
[a,b,d]
[b,c,d]
The order is not important.
A:
... | Array indexing in Numpy python | How can I define _SOME CODE_ in the next code fragment in order to get the results shown below?
vector = numpy.array([a,b,c,d])
for i in xrange(4):
print vector[_SOME CODE_ using i]
It sould give me those results:
[a,b,c]
[a,c,d]
[a,b,d]
[b,c,d]
The order is not important.
| [
"Answer for the edited question:\n>>> vector = numpy.array([0, 1, 2, 3])\n>>> for i in xrange(4):\n... print numpy.r_[vector[:i], vector[i+1:]]\n... \n[1 2 3]\n[0 2 3]\n[0 1 3]\n[0 1 2]\n\nAnswer for the original question: Here's some random code producing the desired output:\n>>> import numpy\n>>> vector = num... | [
3,
0
] | [] | [] | [
"arrays",
"indexing",
"numpy",
"python"
] | stackoverflow_0008359387_arrays_indexing_numpy_python.txt |
Q:
How to save file data from POST variable and load it back to response in Python Django?
I have a such problem - I am using Python 2.6 / Django 1.3 and I need to accept as POST variable with key 'f', which contains a binary data. After that, I need to save data in a file.
POST
T$topX$objectsX$versionY$archiverО©ҐR$... | How to save file data from POST variable and load it back to response in Python Django? | I have a such problem - I am using Python 2.6 / Django 1.3 and I need to accept as POST variable with key 'f', which contains a binary data. After that, I need to save data in a file.
POST
T$topX$objectsX$versionY$archiverО©ҐR$0О©ҐО©ҐО©Ґull_=<---------------------- content of file -------------------->О©ҐО©Ґ_NSKeyedArc... | [
"It would probably be easier, and more memory efficient if you just save the data into a file, and like @keckse said, let a browser stream it. Django is very inefficient in streaming data. It will all depend on the size of the data. If you want to stream it with django anyways, it can be done like this:\nfrom djang... | [
0
] | [] | [] | [
"django",
"httpresponse",
"python"
] | stackoverflow_0008298958_django_httpresponse_python.txt |
Q:
Counting same length items in a list
I am trying to port a cgi script using pythonic style of coding.
sequence = "aaaabbababbbbabbabb"
res = sequence.split("a") + sequence.split("b")
res = [l for l in res if l]
The result is
>>> res
['bb', 'b', 'bbbb', 'bb', 'bb', 'aaaa', 'a', 'a', 'a', 'a']
This was ~100loc in ... | Counting same length items in a list | I am trying to port a cgi script using pythonic style of coding.
sequence = "aaaabbababbbbabbabb"
res = sequence.split("a") + sequence.split("b")
res = [l for l in res if l]
The result is
>>> res
['bb', 'b', 'bbbb', 'bb', 'bb', 'aaaa', 'a', 'a', 'a', 'a']
This was ~100loc in C. Now i want to count the items with the ... | [
"The easiest way to generate a histogram of string lengths given a list of strings is to use collections.Counter:\n>>> from collections import Counter\n>>> a = [\"a\", \"b\", \"aaa\", \"bb\", \"aa\", \"bbb\", \"\", \"a\", \"b\"]\n>>> Counter(map(len, a))\nCounter({1: 4, 2: 2, 3: 2, 0: 1})\n\nEdit: There is also a b... | [
6,
1
] | [] | [] | [
"list",
"python"
] | stackoverflow_0008360538_list_python.txt |
Q:
Loading native python libraries
Python 2.7 comes with json library included. In my PYTHONPATH I include third party sources and one of them is also called json. The result ending up with loaded the wrong json library. What would be a good practice to handle and avoid situations like above? Is there a way to instru... | Loading native python libraries | Python 2.7 comes with json library included. In my PYTHONPATH I include third party sources and one of them is also called json. The result ending up with loaded the wrong json library. What would be a good practice to handle and avoid situations like above? Is there a way to instruct Python to explicitly load the nati... | [
"You could try \nfrom path import json as anotherjson\n\nThis way the namespace conflict can be removed.\nAlso you can see the discussions about relative/absolute import.\n\nhttp://docs.python.org/whatsnew/2.5.html#pep-328\n\nIt says :\n\nIn Python 2.5, you can switch import‘s behaviour to absolute imports\n using... | [
2,
2
] | [] | [] | [
"module",
"python",
"python_module"
] | stackoverflow_0008360512_module_python_python_module.txt |
Q:
Python, html and writing to a text file
I'm creating an html string and writing it to a an .html file. I'm pulling data from websites with json and xml. This pulls text and links and places them into a triple quoted string. There is more to this html string but this much will show the problem. I have a function th... | Python, html and writing to a text file | I'm creating an html string and writing it to a an .html file. I'm pulling data from websites with json and xml. This pulls text and links and places them into a triple quoted string. There is more to this html string but this much will show the problem. I have a function that takes the news string and writes the strin... | [
"I can't say for sure without seeing the input data, but it's likely because some of them are numbers (int, float) or possibly unicode (which would yield a UnicodeEncodeError).\nThe simplest thing to do would be to wrap all the variables in str(…) or unicode(…), but if it were me writing this code, I would install ... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0008360801_python.txt |
Q:
PyPy reload(...) error
I'm going throgh Segaran's Programming Collective Intelligence using Windows version of PyPy.
The author is gradually building this example. First loading the dictionary with:
from recommendations import critics
recommendations.py is then modified by adding a new function. The reader is the... | PyPy reload(...) error | I'm going throgh Segaran's Programming Collective Intelligence using Windows version of PyPy.
The author is gradually building this example. First loading the dictionary with:
from recommendations import critics
recommendations.py is then modified by adding a new function. The reader is then supposed to reload the mod... | [
"The global is not there. You need to import recommendations for it to work.\n"
] | [
2
] | [] | [] | [
"pypy",
"python"
] | stackoverflow_0008360610_pypy_python.txt |
Q:
Hangman game, Loop breaks and sys.exit
Hello I was wondering if there is any way to have a loop be broken, I have tried to use the break command but that doesn't do anything. I am very new at this.
Also, is there any way to get it to gracefully to close when people use the use the command:
wannaplay = raw_input(... | Hangman game, Loop breaks and sys.exit | Hello I was wondering if there is any way to have a loop be broken, I have tried to use the break command but that doesn't do anything. I am very new at this.
Also, is there any way to get it to gracefully to close when people use the use the command:
wannaplay = raw_input('Wanna play hangman?(yes or no): ')"
I trie... | [
"Use Exception to break a Loop. Consider the following Example\ntry:\n while True:\n answer = raw_input(\"Type [Y]es to Exit :\")\n if answer.lower() in [\"yes\",\"y\"]: raise StopIteration\n print \"Your answer is \", answer\nexcept StopIteration:\n print \"Good Bye\"\n\n\nType [Y]es to ... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0008360699_python.txt |
Q:
reportlab: setting colspan for td in rml
I can't find any option, that would allow to set colspan for td element in rml. Is that somehow possible?
A:
Gordon's suggestion of the blockSpan element worked for me. Here's an example of how to use it:
<?xml version="1.0"?>
<document filename="test.pdf">
<template pa... | reportlab: setting colspan for td in rml | I can't find any option, that would allow to set colspan for td element in rml. Is that somehow possible?
| [
"Gordon's suggestion of the blockSpan element worked for me. Here's an example of how to use it:\n<?xml version=\"1.0\"?>\n<document filename=\"test.pdf\">\n <template pageSize=\"(612,792)\" title=\"Test\" author=\"Don Kirkby\">\n <pageTemplate id=\"first\">\n <frame id=\"first\" x1=\"10.0\" y1=\"10.0\" wi... | [
8,
3
] | [] | [] | [
"python",
"reportlab",
"rml"
] | stackoverflow_0005002944_python_reportlab_rml.txt |
Q:
Get just a class name without module, etc
I'm probably overlooking something simple. Given an instance of a class, I'd like to get just the class name. For example:
class Foooo: pass
instance = Foooo()
print("instance.__class__ = "+str(instance.__class__))
print("Just the class name: "+str(instance.__class__).s... | Get just a class name without module, etc | I'm probably overlooking something simple. Given an instance of a class, I'd like to get just the class name. For example:
class Foooo: pass
instance = Foooo()
print("instance.__class__ = "+str(instance.__class__))
print("Just the class name: "+str(instance.__class__).split(".")[-1][:-2])
This gives the following o... | [
"Try this:\ninstance.__class__.__name__\n\n"
] | [
28
] | [] | [] | [
"python"
] | stackoverflow_0008361974_python.txt |
Q:
remove contents between brackets from string
I have a string like this:
s = 'word1 word2 (word3 word4) word5 word6 (word7 word8) word9 word10'
how can I delete everything that is in brackets, so that the output is:
'word1 word2 word5 word6 word9 word10'
I tried regular expression but that doesn't seem to work. A... | remove contents between brackets from string | I have a string like this:
s = 'word1 word2 (word3 word4) word5 word6 (word7 word8) word9 word10'
how can I delete everything that is in brackets, so that the output is:
'word1 word2 word5 word6 word9 word10'
I tried regular expression but that doesn't seem to work. Any suggestions?
Best
Jacques
| [
"import re\ns = re.sub(r'\\(.*?\\)', '', s)\n\nNote that this deletes everything between parentheses only. This means you'll be left with double space between \"word2 and word5\". Output from my terminal:\n>>> re.sub(r'\\(.*?\\)', '', s)\n'word1 word2 word5 word6 word9 word10'\n>>> # -------^ -----------^ (Note d... | [
7,
2,
0,
0,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0006857296_python_string.txt |
Q:
parse the uploaded file as an argument to python program Django
So right now I have written a python program which takes the path name as an argument from console to execute..
now I am trying to learn Django and am trying to execute same program but via the web browser.
So I figured out that let me have a form fie... | parse the uploaded file as an argument to python program Django | So right now I have written a python program which takes the path name as an argument from console to execute..
now I am trying to learn Django and am trying to execute same program but via the web browser.
So I figured out that let me have a form field to upload the file..
and then an execute button..
and when the exe... | [
"There's a bunch of ways:\n\nos.system(command)\nos.popen(command[, mode[, bufsize]])\nusing subprocess module - subprocess.call(...)\n\nand maybe others i don't know about. Be aware that exposing these features to the public invites abuse. You may be interested in sandboxing (or this writeup) or using something li... | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008361823_django_python.txt |
Q:
Python Script to Change Folder Names
I'm on OS X and I'm fed up with our labeling system where I work. The labels are mm/dd/yy and I think that they should be yy/mm/dd. Is there a way to write a script to do this? I understand a bit of Python with lists and how to change the position of characters.
Any suggestion... | Python Script to Change Folder Names | I'm on OS X and I'm fed up with our labeling system where I work. The labels are mm/dd/yy and I think that they should be yy/mm/dd. Is there a way to write a script to do this? I understand a bit of Python with lists and how to change the position of characters.
Any suggestions or tips?
What I have now:
083011-Hallowe... | [
"Assuming the script is in the same directory as the files you want to rename, and you already have the list of files that you want to rename, you can do this:\nfor file in rename_list:\n os.rename(file, file[4:6] + file[:2] + file[2:4] + file[6:])\n\n",
"There is a Q&A with information on traversing directori... | [
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0008361948_python.txt |
Q:
Suggest a project I can use to study good software architecture
I am close to completing Zed Shaw's Learn Python The Hard Way. I also know that the second best thing to programming excellence apart from actually getting hands on and working on a project is to study other peoples code. Thanks to all the repositorie... | Suggest a project I can use to study good software architecture | I am close to completing Zed Shaw's Learn Python The Hard Way. I also know that the second best thing to programming excellence apart from actually getting hands on and working on a project is to study other peoples code. Thanks to all the repositories out there, there is no shortage of projects that one can download a... | [
"Here is a very good material and book on reading up various kinds of architecture\n\nhttp://www.aosabook.org/en/index.html\n\n",
"That sounds like a dangerous question :) \nI say that because although there are many different ways to design a solution, each approach typically has it's own pros and cons. A well d... | [
3,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0008361844_python.txt |
Q:
Can't append x86 Python 2.7 path
I'd like to have a module in python27\scripts\ added to the list in the path browser - tried the syntax from here: https://stackoverflow.com/a/3402196 and here: http://www.johnny-lin.com/cdat_tips/tips_pylang/path.html
import sys
sys.path.append("E:\Program Files\Python27\Scripts")... | Can't append x86 Python 2.7 path | I'd like to have a module in python27\scripts\ added to the list in the path browser - tried the syntax from here: https://stackoverflow.com/a/3402196 and here: http://www.johnny-lin.com/cdat_tips/tips_pylang/path.html
import sys
sys.path.append("E:\Program Files\Python27\Scripts")
sys.path.append('E:\Program Files\Pyt... | [
"sys.path is the module search path. It is a list of directories that Python will use when searching for modules that you import. Adding a directory to sys.path will not create the directory for you, it should be used when you have a directory with Python modules that you want to import in your script.\nIf you wa... | [
3,
0
] | [] | [] | [
"append",
"path",
"python",
"sys"
] | stackoverflow_0008362089_append_path_python_sys.txt |
Q:
Python, 'return' outside function error
I was writing this code in C++ and it kept giving me an answer that I didn't want so I thought I should write it in python, so when I did it gave me the error "* 'return' outside function ([Place on hard drive], line 7)". I searched it and found that it was to do with indent... | Python, 'return' outside function error | I was writing this code in C++ and it kept giving me an answer that I didn't want so I thought I should write it in python, so when I did it gave me the error "* 'return' outside function ([Place on hard drive], line 7)". I searched it and found that it was to do with indentions, so I re-wrote that line of code but I s... | [
"Try changing class to def. \n",
"You are telling Python that you are defining a class, because of the \"class\" keyword.\nHowever, you instead should be defining a function, using \"def\".\nThere are a few other things you will need to fix to make this work. For example, gimmeANumber() should return a number, bu... | [
4,
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0008362660_python.txt |
Q:
reformatting strings with included variables
I have a library full of variables(that I do not wish to hand edit), it looks like this:
def get_variables(gateway):
variables={
'gateway':gateway,
'license_test_data':gateway['license_data'],
'license_for_application':gateway['license_for_a... | reformatting strings with included variables | I have a library full of variables(that I do not wish to hand edit), it looks like this:
def get_variables(gateway):
variables={
'gateway':gateway,
'license_test_data':gateway['license_data'],
'license_for_application':gateway['license_for_application'],
'Valid_Login_Test_Vairables'... | [
"I found your question somewhat difficult to understand, but if I manged to do so correctly, the following produces what you said you wanted from what you have.\n# used as a stand-in for your 'import dummy.gateway'\ndummy_gateway = {}\ndummy_gateway['license_test_data'] = \"gateway['license_test_data']\"\ndummy_gat... | [
1
] | [] | [] | [
"python",
"robotframework",
"variables"
] | stackoverflow_0008361256_python_robotframework_variables.txt |
Q:
Detrending a time-series of a multi-dimensional array without the for loops
I have a 3D array which has a time-series of air-sea carbon flux for each grid point on the earth's surface (model output). I want to remove the trend (linear) in the time series. I came across this code:
from matplotlib import mlab
for x... | Detrending a time-series of a multi-dimensional array without the for loops | I have a 3D array which has a time-series of air-sea carbon flux for each grid point on the earth's surface (model output). I want to remove the trend (linear) in the time series. I came across this code:
from matplotlib import mlab
for x in xrange(40):
for y in xrange(182):
cflux_detrended[:, x, y] = mlab... | [
"Scipy has a lot of signal processing tools. \nUsing scipy.signal.detrend() will remove the linear trend along an axis of the data. From the documentation it looks like the linear trend of the complete data set will be subtracted from the time-series at each grid point.\nimport scipy.signal\ncflux_detrended = scipy... | [
4,
2,
1
] | [] | [] | [
"numpy",
"python",
"scipy",
"signal_processing"
] | stackoverflow_0008355197_numpy_python_scipy_signal_processing.txt |
Q:
Shortest distance algorithm Python
I wanted to create a simple breadth first search algorithm, which returns the shortest path.
An actor information dictionary maps and actor to the list of movies the actor appears in:
actor_info = { "act1" : ["movieC", "movieA"], "act2" : ["movieA", "movieB"],
"act3" :["mov... | Shortest distance algorithm Python | I wanted to create a simple breadth first search algorithm, which returns the shortest path.
An actor information dictionary maps and actor to the list of movies the actor appears in:
actor_info = { "act1" : ["movieC", "movieA"], "act2" : ["movieA", "movieB"],
"act3" :["movieA", "movieB"], "act4" : ["movieC", "mo... | [
"Firstly create one graph out of this to connect all the nodes and then run the shortest_path code(There could be an efficient graph library to do this instead of the function mentioned below, nevertheless this one is elegant) and then find out all the number of movie names from the shortest path.\nfor i in movie_i... | [
2,
1
] | [] | [] | [
"breadth_first_search",
"python"
] | stackoverflow_0008362522_breadth_first_search_python.txt |
Q:
Continuous mutual information in Python
[Frontmatter] (skip this if you just want the question):
I'm currently looking at using Shannon-Weaver Mutual Information and normalized redundancy to measure the degree of information masking between bags of discrete and continuous feature values, organized by feature. Usi... | Continuous mutual information in Python | [Frontmatter] (skip this if you just want the question):
I'm currently looking at using Shannon-Weaver Mutual Information and normalized redundancy to measure the degree of information masking between bags of discrete and continuous feature values, organized by feature. Using this method, it is my goal to construct an... | [
"Before trying more radical solutions like reframing the problem or using different integration tools, see if this helps. Replace INF=float('INF') with INF=1E12 or some other large number -- that may eliminate NaN results created by simple arithmetic operations on the input variables.\nNo promises on this one, but... | [
4
] | [] | [] | [
"floating_point",
"information_theory",
"math",
"python",
"scipy"
] | stackoverflow_0008363085_floating_point_information_theory_math_python_scipy.txt |
Q:
django-south: chicken+egg with initial data
I have a model:
class Foo(models.Model):
pass
I want to add a type attribute to it. There are a fixed number of types. The existing ones should all have the default type. So I add the type:
class Type(models.Model):
name = models.CharField(max_length=100)
And t... | django-south: chicken+egg with initial data | I have a model:
class Foo(models.Model):
pass
I want to add a type attribute to it. There are a fixed number of types. The existing ones should all have the default type. So I add the type:
class Type(models.Model):
name = models.CharField(max_length=100)
And the types to an initial data fixture:
- model: app... | [
"You need to write an extra datamigration specifically for your initial data in the fixture. Check out South's docs on the subject http://south.aeracode.org/docs/fixtures.html#initial-data Hope that helps you out.\n"
] | [
3
] | [] | [] | [
"django",
"django_south",
"python"
] | stackoverflow_0008362283_django_django_south_python.txt |
Q:
Rsyslog + Virtualenv
I'm using a shell execute action in rsyslog to a python script on a CentOS machine. How can I ensure that it runs in a specified virtualenv?
A:
Have you ever asked a question while researching something, then learned what you needed to do and then wished you hadn't asked the question?
All y... | Rsyslog + Virtualenv | I'm using a shell execute action in rsyslog to a python script on a CentOS machine. How can I ensure that it runs in a specified virtualenv?
| [
"Have you ever asked a question while researching something, then learned what you needed to do and then wished you hadn't asked the question?\nAll you need to do is modify your python path and add the path to the site-packages directory of the virtualenv you want to use.\n"
] | [
2
] | [] | [] | [
"centos",
"python",
"rsyslog",
"virtualenv"
] | stackoverflow_0007687332_centos_python_rsyslog_virtualenv.txt |
Q:
Clear selected list item (so there's no selected list item) in Python/PySide
I have an application written in Python using PySide, the UI was created with QT Designer.
I have a list in the window, which has a set of items. When the application loads, it seems to grab the last item in the list (even though there i... | Clear selected list item (so there's no selected list item) in Python/PySide | I have an application written in Python using PySide, the UI was created with QT Designer.
I have a list in the window, which has a set of items. When the application loads, it seems to grab the last item in the list (even though there is no 'highlighted' row showing in the list). If I break and check if there is a s... | [
"The current item and the selection are not necessarily the same thing. The current item refers to the item with the keyboard focus; the selection refers to the currently highlighted items. So a tree widget with no selection will still have a current item (unless it has no items at all).\nSo one solution might be t... | [
1
] | [] | [] | [
"pyside",
"python",
"qt_designer"
] | stackoverflow_0008363064_pyside_python_qt_designer.txt |
Q:
Key-value consistency in python dictionaries
This is probably a noob question. For any dictionary 'd' in python is this always True:
dict( zip( d.keys(), d.values() ) ) == d
Are the keys and values returned in the same corresponding order ?
A:
Yes it's always true. Guaranteed by Python iff there are no interv... | Key-value consistency in python dictionaries | This is probably a noob question. For any dictionary 'd' in python is this always True:
dict( zip( d.keys(), d.values() ) ) == d
Are the keys and values returned in the same corresponding order ?
| [
"Yes it's always true. Guaranteed by Python iff there are no intervening modifications to the ditionary. \nRelevant spec: http://docs.python.org/library/stdtypes.html#dict.items\nThis is better generally, both because it protects against the dict going out of sync and uses negligible extra memory:\ndict((k,v) for k... | [
7,
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0008363938_python.txt |
Q:
Counting equal strings in Python
I have a list of strings and some of them are equal. I need some script which would count equal strings. Ex:
I have a list with some words :
"House"
"Dream"
"Tree"
"Tree"
"House"
"Sky"
"House"
And the output should look like this:
"House" - 3
"Tree" - 2
"Dream" - 1
and so on
A:
... | Counting equal strings in Python | I have a list of strings and some of them are equal. I need some script which would count equal strings. Ex:
I have a list with some words :
"House"
"Dream"
"Tree"
"Tree"
"House"
"Sky"
"House"
And the output should look like this:
"House" - 3
"Tree" - 2
"Dream" - 1
and so on
| [
"Use collections.Counter(). It is designed for exactly this use case:\n>>> import collections\n>>> seq = [\"House\", \"Dream\", \"Tree\", \"Tree\", \"House\", \"Sky\", \"House\"]\n>>> for word, cnt in collections.Counter(seq).most_common():\n print repr(word), '-', cnt\n\n'House' - 3\n'Tree' - 2\n'Sky' - 1\... | [
8,
4,
3,
2,
1
] | [] | [] | [
"comparison",
"python",
"string"
] | stackoverflow_0008364045_comparison_python_string.txt |
Q:
Pywin32 Excel write limits?
I'm using pywin32 and the common way to write range to excel, by getting some range objects and then writing to it with
range.Value=my_data
(it's all the same syntax as VBA)
Now, if I have a set of fairly large cells (>6000 chars) and I write them out all at once by setting the Value ... | Pywin32 Excel write limits? | I'm using pywin32 and the common way to write range to excel, by getting some range objects and then writing to it with
range.Value=my_data
(it's all the same syntax as VBA)
Now, if I have a set of fairly large cells (>6000 chars) and I write them out all at once by setting the Value of a range object, then it someti... | [
"There isn't a fixed size limit for transferring an array to a range. It depends more on the memory required for the array, RAM, etc. If there is any chance the amount of data is large, it's best to break up the array into chunks and write them one at a time.\n"
] | [
0
] | [] | [] | [
"excel",
"python",
"pywin32",
"vba"
] | stackoverflow_0006171490_excel_python_pywin32_vba.txt |
Q:
Unicode being re-unicoded
I'm scraping info from Facebook which compiles weirdly. The source for a page returns the name "Trentemøller" as a regular string with a unicode character:
Trentem\u00f8ller
When I try to print that or commit it to a list print u'%s' % name or print unicode(name) it escape-sequences the b... | Unicode being re-unicoded | I'm scraping info from Facebook which compiles weirdly. The source for a page returns the name "Trentemøller" as a regular string with a unicode character:
Trentem\u00f8ller
When I try to print that or commit it to a list print u'%s' % name or print unicode(name) it escape-sequences the backslash.
u'Trentem\\u00f8ller'... | [
"If you're in control of forming the unicode string, then use just one backslash:\n>>> print u'Trentem\\u00f8ller'\nTrentemøller\n\nIf the regular string has already been formed by the screen scaper, you will need to re-evaluate the string to transform the backslash escape sequences into a real unicode characters. ... | [
4
] | [] | [] | [
"python",
"unicode"
] | stackoverflow_0008364703_python_unicode.txt |
Q:
Can't decode output from BeautifulSoup in Python
I've been attempting to write a little scraper in Python using BeautifulSoup.
Everything goes smoothly until I attempt to print (or write to a file) the strings contained inside the various HTML elements. The site i'm scraping is: http://www.yellowpages.ca/search/s... | Can't decode output from BeautifulSoup in Python | I've been attempting to write a little scraper in Python using BeautifulSoup.
Everything goes smoothly until I attempt to print (or write to a file) the strings contained inside the various HTML elements. The site i'm scraping is: http://www.yellowpages.ca/search/si/1/Boots/Montreal+QC which contains various french ch... | [
"This should be something like what you want:\nfrom BeautifulSoup import BeautifulSoup as bs\nimport urllib as ul\n\nbase_url = 'http://www.yellowpages.ca'\ndata_file = open('yellow_file.txt', 'a')\n\nbt = bs(ul.urlopen(base_url + '/locations/Quebec/Montreal/90014002.html'))\n\nfor div in bt.findAll('div', 'ypgCate... | [
3,
0
] | [] | [] | [
"beautifulsoup",
"decoding",
"python",
"unicode"
] | stackoverflow_0008364672_beautifulsoup_decoding_python_unicode.txt |
Q:
How to make Tkinter message expand when I resize the window?
I'm trying to get a tkinter message widget to make the words move when I resize the window. Right now, the window is a small block, and the line of text is an ugly block. How can I make it expand. This is the code I have.
root = Tk()
Message(text="This i... | How to make Tkinter message expand when I resize the window? | I'm trying to get a tkinter message widget to make the words move when I resize the window. Right now, the window is a small block, and the line of text is an ugly block. How can I make it expand. This is the code I have.
root = Tk()
Message(text="This is a Tkinter message widget. Pretty exiting, huh? I enjoy Tkinter. ... | [
"You need to set the width of the Message text when you resize the window. As far as I know, there is no way to tell the Message widget do that automatically, so you're stuck with using a callback:\nfrom tkinter import Tk, Message\n\nroot = Tk()\nm = Message(text=\"This is a Tkinter message widget. Pretty exiting,... | [
5
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0008363390_python_tkinter.txt |
Q:
Additional field in django form
I am creating a form in Django. When I POST the data, the data is naturally sent. My problem is, I want to pass an additional property to the POST data, that is not any of the form fields, but an additional one.
So that I can later do something like (pseudocode):
def form_view(reque... | Additional field in django form | I am creating a form in Django. When I POST the data, the data is naturally sent. My problem is, I want to pass an additional property to the POST data, that is not any of the form fields, but an additional one.
So that I can later do something like (pseudocode):
def form_view(request):
if request.method == 'POST':... | [
"If you want to pass anything to django as a POST request from the HTML, you would use a hidden input\n<input type=\"hidden\" name=\"foo\" value=\"bar\" />\n\nprint request.POST['foo'] # out: bar\n\nIf you want to modify the POST dictionary in python from your view, copy() it to make it mutable.\nmutable_post = req... | [
4,
1,
1
] | [] | [] | [
"django",
"django_forms",
"forms",
"python"
] | stackoverflow_0008364948_django_django_forms_forms_python.txt |
Q:
String reverse in Python
Write a simple program that reads a line from the keyboard and outputs the same line where
every word is reversed. A word is defined as a continuous sequence of alphanumeric characters
or hyphen (‘-’). For instance, if the input is
“Can you help me!”
the output should be
“naC uoy pleh em!”... | String reverse in Python | Write a simple program that reads a line from the keyboard and outputs the same line where
every word is reversed. A word is defined as a continuous sequence of alphanumeric characters
or hyphen (‘-’). For instance, if the input is
“Can you help me!”
the output should be
“naC uoy pleh em!”
I just tryed with the followi... | [
"The easiest is probably to use the re module to split the string:\nimport re\npattern = re.compile('(\\W)')\nstring = raw_input('Enter the string: ')\nprint ''.join(x[::-1] for x in pattern.split(string))\n\nWhen run, you get:\nEnter the string: Can you help me!\nnaC uoy pleh em!\n\n",
"You could use re.sub() to... | [
6,
3,
0,
0
] | [
"you can do this.\nprint\"Enter the string:\"\n\nstr1=raw_input()\n\nprint( ' '.join(str1[::-1].split(' ')[::-1]) )\n\nor then, this\nprint(' '.join([w[::-1] for w in a.split(' ') ]))\n\n"
] | [
-1
] | [
"python"
] | stackoverflow_0008358520_python.txt |
Q:
Screen Scraping a Javascript based webpage in Python
I am working on a screen scraping tool in Python. But, as I look through the source of the webpage, I noticed that most of the data is coming through Javascript.
Any idea, how to scrape javascript based webpage ? Any tool in Python ?
Thanks
A:
Scraping javas... | Screen Scraping a Javascript based webpage in Python | I am working on a screen scraping tool in Python. But, as I look through the source of the webpage, I noticed that most of the data is coming through Javascript.
Any idea, how to scrape javascript based webpage ? Any tool in Python ?
Thanks
| [
"Scraping javascript-based webpages is possible with selenium. In particular, try the Selenium WebDriver.\n",
"I use webkit, which is the browser renderer behind Chrome and Safari. There are Python bindings to webkit through Qt. \nAnd here is a full Python example to execute JavaScript and extract the final HTML.... | [
5,
4,
3
] | [] | [] | [
"beautifulsoup",
"python",
"screen_scraping",
"web_scraping"
] | stackoverflow_0008183682_beautifulsoup_python_screen_scraping_web_scraping.txt |
Q:
how to specify empty queryset to not empty queryset : [ ] to []
i have a problem in determining an object if it is empty or not...
here is my code :
this value has no data
>>> x = Booking.objects.filter(date_select='2011-12-3')
>>> print x
[]
>>> if x == None:
... print 'none'
...
>>>
this has a data :
>>> x ... | how to specify empty queryset to not empty queryset : [ ] to [] | i have a problem in determining an object if it is empty or not...
here is my code :
this value has no data
>>> x = Booking.objects.filter(date_select='2011-12-3')
>>> print x
[]
>>> if x == None:
... print 'none'
...
>>>
this has a data :
>>> x = Booking.objects.filter(date_select='2011-12-2')
>>> print x
[<Booki... | [
"Use exists()\n\nReturns True if the QuerySet contains any results, and False if not.\n This tries to perform the query in the simplest and fastest way\n possible, but it does execute nearly the same query. This means that\n calling QuerySet.exists() is faster than bool(some_query_set), but not\n by a large deg... | [
8,
2,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008365255_django_python.txt |
Q:
I can only import the Stripe Python library under a certain version of Python
I use Webfaction, and this is the command line for the shared host.
[zallarak@web198 ~]$ python2.6
Python 2.6.5 (r265:79063, Nov 23 2010, 02:02:03)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2
Type "help", "copyright", "credits" or... | I can only import the Stripe Python library under a certain version of Python | I use Webfaction, and this is the command line for the shared host.
[zallarak@web198 ~]$ python2.6
Python 2.6.5 (r265:79063, Nov 23 2010, 02:02:03)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import stripe
>>>
[zallarak@web198 ~]$ python... | [
"Your problem is that the stripe module is not installed in each python environment.\n\nI know there must be a simple way to make it work in all version of Python.\n\nYou must install stripe in each environment. According to your webhost, you should be able to install them with easy_install. Try this:\npython2.7 ... | [
4,
3
] | [] | [] | [
"linux",
"module",
"python",
"stripe_payments",
"webfaction"
] | stackoverflow_0008364972_linux_module_python_stripe_payments_webfaction.txt |
Q:
How to view .py in Eclipse
I just installed eclipse on my machine and want to modify a .py file. I tried opening the file and I get the error application not found. What do I need to install and how do I install it. I have searched the web and not found any clear instruction. I am using Java Eclipse SDK.
I am tryi... | How to view .py in Eclipse | I just installed eclipse on my machine and want to modify a .py file. I tried opening the file and I get the error application not found. What do I need to install and how do I install it. I have searched the web and not found any clear instruction. I am using Java Eclipse SDK.
I am trying to open the file .py with Ecl... | [
"Install the PyDev plug-in for Eclipse:\nhttp://www.rose-hulman.edu/class/csse/resources/Eclipse/eclipse-python-configuration.htm\n"
] | [
7
] | [] | [] | [
"eclipse",
"python"
] | stackoverflow_0008365426_eclipse_python.txt |
Q:
Empty bounding box result with geomodel in GAE
I'm attempting to do a bounding box fetch in the GAE using geomodel in python. It is my understanding that you define a box and then the geomodel fetch will return all results with co-ordinates that lie within this box. I am currently inputting a GPS latitude and long... | Empty bounding box result with geomodel in GAE | I'm attempting to do a bounding box fetch in the GAE using geomodel in python. It is my understanding that you define a box and then the geomodel fetch will return all results with co-ordinates that lie within this box. I am currently inputting a GPS latitude and longitude (55.497527,-3.114624), and then establishing a... | [
"Code to add to the database -\nfrom google.appengine.ext import db\nfrom models.place import Place\n\nplace = Place(location=db.GeoPt(LAT, LON)) # location is a required field \n # LAT, LON are floats\nplace.state = \"New York\"\nplace.zip_code = 10003\n#... set other fiel... | [
0
] | [] | [] | [
"geohashing",
"google_app_engine",
"python"
] | stackoverflow_0006754009_geohashing_google_app_engine_python.txt |
Q:
About python's socket backup
I've programmed a python script to backup my files, something like Dropbox.
But there are some bugs. I have a class called SyncServer, and there are two functions called __init__ and TF1 seperately. TF1 stands for "Thread Function 1".
When I write thread.start_new_thread(TF1, (conn, 0)... | About python's socket backup | I've programmed a python script to backup my files, something like Dropbox.
But there are some bugs. I have a class called SyncServer, and there are two functions called __init__ and TF1 seperately. TF1 stands for "Thread Function 1".
When I write thread.start_new_thread(TF1, (conn, 0)), the first parameter, I sent a s... | [
"thread.start_new_thread(TF1, (conn, 0))\nAssumes that TF1 is a global.\n\"NameError: global name 'TF1' is not defined\"\nStates that TF1 is not a global.\nIt must be that the assumption is wrong.\nTF1 is a method function in a class. Therefore, it needs to be qualified either by the class name or by an object inst... | [
4
] | [] | [] | [
"python",
"sockets"
] | stackoverflow_0008365436_python_sockets.txt |
Q:
How to make a python gtk app "dock" on top of other apps?
I'd like for this python gtk app to be "docked" at the top of the screen. Is there a way to disable the close, maximize, and minimize buttons and keep it on top of the other applications?
#!/usr/bin/env python
import sys
import gtk
import webkit
DEFAULT_URL... | How to make a python gtk app "dock" on top of other apps? | I'd like for this python gtk app to be "docked" at the top of the screen. Is there a way to disable the close, maximize, and minimize buttons and keep it on top of the other applications?
#!/usr/bin/env python
import sys
import gtk
import webkit
DEFAULT_URL = 'http://webpage.com'
class SimpleBrowser:
def __init__(self)... | [
"Close, Maximize & Minimize in the toolbar are part of window manager decorations. If you want to get rid of them then disable decorations using gtk.Window.set_decorated and setting the decorations settings to false. Regarding always on top you can try gtk.Window.set_keep_above. This again is a \"hint\" to the wind... | [
2
] | [] | [] | [
"gtk",
"python"
] | stackoverflow_0008362281_gtk_python.txt |
Q:
Can we execute mutiple commands in the same command prompt launched by python script?
I have used os.system(command) in a for loop.
By using this, CMD opens, executes the command and close. For Second command, CMD opens again, executes tha command and close. Due to this, CMD pop-ups again and again.
Meanwhile, I a... | Can we execute mutiple commands in the same command prompt launched by python script? | I have used os.system(command) in a for loop.
By using this, CMD opens, executes the command and close. For Second command, CMD opens again, executes tha command and close. Due to this, CMD pop-ups again and again.
Meanwhile, I am not able to do another task on system. I want to do this in a CMD so that i can minimize ... | [
"You can just concatenate your commands, delimited by a semicolon (;) and only call os.system once.\n",
"Another approach is to write all of the command strings to a .bat or .cmd file, and then execute the resulting file with os.system.\nThis is more useful if the number of commands per iteration is \"large-ish\"... | [
2,
1,
0
] | [] | [] | [
"python",
"windows"
] | stackoverflow_0008356137_python_windows.txt |
Q:
how to print only date and not include the time in datetime.datetime.strptime()
I have this code :
>>> import datetime
>>> l = '2011-12-02'
>>> t = datetime.datetime.strptime(l, '%Y-%m-%d')
>>> print t
2011-12-02 00:00:00
my question is, it is possible that only the 2011-12-02 will be printed?
A:
>>> t.strftime... | how to print only date and not include the time in datetime.datetime.strptime() | I have this code :
>>> import datetime
>>> l = '2011-12-02'
>>> t = datetime.datetime.strptime(l, '%Y-%m-%d')
>>> print t
2011-12-02 00:00:00
my question is, it is possible that only the 2011-12-02 will be printed?
| [
">>> t.strftime('%Y-%m-%d')\n'2011-12-02'\n\n",
"With strftime():\nprint t.strftime('%Y-%m-%d')\n\n",
"You have to specify the output format for the date, e.g. by using \nprint t.strftime(\"%Y-%m-%d\")\n\nAll the letter after a \"%\" represent a format: %d is the day number, %m is the month number, %y is the y... | [
31,
6,
2,
1
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0008365819_datetime_python.txt |
Q:
using the filechooser dialog with glade
I would like to ask if anyone knows how to use the filechooser dialog in glade and pygtk. (It should be very similar in any of the language bindings, and that is why I didn't specify the language.) Basically, the filechooser now looks like this: there are two columns, one fo... | using the filechooser dialog with glade | I would like to ask if anyone knows how to use the filechooser dialog in glade and pygtk. (It should be very similar in any of the language bindings, and that is why I didn't specify the language.) Basically, the filechooser now looks like this: there are two columns, one for the folders (left), and one for the files (... | [
"Dialog with buttons returns the response id which is associated with the button pressed. In your case, when you create your \"Cancel\" & \"Ok\" buttons in glade & drop them into empty slot available in the file chooser dialog, in the edit box (right bottom of the screen which will have heading like \"Button Proper... | [
7
] | [] | [] | [
"dialog",
"filechooser",
"gtk",
"pygtk",
"python"
] | stackoverflow_0008362344_dialog_filechooser_gtk_pygtk_python.txt |
Q:
Fastest way to Sort an algo in Python
I am preparing for Codility. And I need to find out what is the fastest way to find an array with big values and many entries?
Is inbuilt python sort is the fastest or do i need to implement some other sort method?
A:
If your data is already in Python, the Python's sort is l... | Fastest way to Sort an algo in Python | I am preparing for Codility. And I need to find out what is the fastest way to find an array with big values and many entries?
Is inbuilt python sort is the fastest or do i need to implement some other sort method?
| [
"If your data is already in Python, the Python's sort is likely the fastest way to go. It uses the Timsort algorithm which performs well on random data and very well on partially ordered data.\nIf you only need the largest items, use heapq.nlargest.\n",
"The impression I get from the codility.com job interview s... | [
10,
2,
0
] | [] | [] | [
"algorithm",
"python",
"sorting"
] | stackoverflow_0008365923_algorithm_python_sorting.txt |
Q:
Reading Website That Has Japanese
UnicodeDecodeCharacter 'ascii' cocec can't decode byte 0xe3 at position 348: ordinal not in range(128)
I have urllib.urlopen-ing a website, and I have a .readlines() going through it paragraph by paragraph, searching for certain text.
I reading from a website that has a few Japane... | Reading Website That Has Japanese | UnicodeDecodeCharacter 'ascii' cocec can't decode byte 0xe3 at position 348: ordinal not in range(128)
I have urllib.urlopen-ing a website, and I have a .readlines() going through it paragraph by paragraph, searching for certain text.
I reading from a website that has a few Japanese characters on it (I WANT TO SKIP THI... | [
"You can read in the raw bytes, convert them to ascii (while ignoring non-ascii) and then split the lines:\nimport urllib\n\nurl = 'http://www.asahi.com/'\nu = urllib.urlopen(url)\nrawdata = u.read()\nu.close()\nasciidata = rawdata.decode('ascii', 'ignore')\nasciilines = asciidata.splitlines(False)\n\nfor line in a... | [
2
] | [] | [] | [
"ascii",
"encoding",
"python",
"unicode",
"urllib"
] | stackoverflow_0008366017_ascii_encoding_python_unicode_urllib.txt |
Q:
How can I speed up simplejson in Python?
simplejson is slow. I wish it to be fast. How might I achieve this?
A:
simplejson has built in speedups module writen in C.
Make sure it's compiled.
( For example, check if there is /usr/local/lib/python2.6/dist-packages/simplejson-2.2.1-py2.6-linux-i686.egg/simplejson/_... | How can I speed up simplejson in Python? | simplejson is slow. I wish it to be fast. How might I achieve this?
| [
"simplejson has built in speedups module writen in C.\nMake sure it's compiled. \n( For example, check if there is /usr/local/lib/python2.6/dist-packages/simplejson-2.2.1-py2.6-linux-i686.egg/simplejson/_speedups.so file )\n"
] | [
1
] | [
"Have a look at cjson.\n",
"If you can update to at least python 2.6, you can use the standard lib json module, which will be faster since it has some speedups.\nhttp://docs.python.org/library/json.html\n"
] | [
-1,
-1
] | [
"python",
"simplejson"
] | stackoverflow_0005159323_python_simplejson.txt |
Q:
search for hexadecimal number on python using re
I am processing an html text file, and serching for hexadecimal numbers as follows:
example \xb7\xc7\xa0....
I tried with this code
t=re.findall (r'\\x[0-9a-fA-F]+', line)
but I can only gained empty list.
please tell the right way of writing the code.
A:
You... | search for hexadecimal number on python using re | I am processing an html text file, and serching for hexadecimal numbers as follows:
example \xb7\xc7\xa0....
I tried with this code
t=re.findall (r'\\x[0-9a-fA-F]+', line)
but I can only gained empty list.
please tell the right way of writing the code.
| [
"Your code works fine if the backslash is escaped inside the regular expression:\nt = re.findall (r'\\\\x[0-9a-fA-F]+', line)\n\nResult:\n\n['\\\\xb7', '\\\\xc7', '\\\\xa0']\n\nideone: http://ideone.com/MPO5j\n\nIf it doesn't work it might be because you string contains literal binary characters. Then try something... | [
2,
2,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0008366682_python_regex.txt |
Q:
Elixir for Python 3?
I have a problem installing Elixir with Python 3 although I have installed SqlAlchemy 0.7.3 successfully? I've tried google-ing but I am loosing hope. Is there really a version of Elixir for Python 3? Thanks in advance.
A:
Looking at the source code, I see that the latest change happened 10... | Elixir for Python 3? | I have a problem installing Elixir with Python 3 although I have installed SqlAlchemy 0.7.3 successfully? I've tried google-ing but I am loosing hope. Is there really a version of Elixir for Python 3? Thanks in advance.
| [
"Looking at the source code, I see that the latest change happened 10 months ago. Also, searching for print I see that all the strings found in all branches use print as a statement, not as a function and there isn't any log string that makes a reference to python 3.\nHence, since I don't see any trace of work towa... | [
2,
1
] | [] | [] | [
"cpython",
"python",
"python_3.x",
"python_elixir",
"sqlalchemy"
] | stackoverflow_0008365735_cpython_python_python_3.x_python_elixir_sqlalchemy.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.