Mxode/SmolLM-Chinese-180M
Text Generation • 0.2B • Updated • 1 • 5
content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers sequence | answers_scores sequence | non_answers sequence | non_answers_scores sequence | tags sequence | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
How do I make a menu that does not require the user to press [enter] to make a selection?
I've got a menu in Python. That part was easy. I'm using raw_input() to get the selection from the user.
The problem is that raw_input (and input) require the user to press Enter after they make a selection. Is there any way... | How do I make a menu that does not require the user to press [enter] to make a selection? | I've got a menu in Python. That part was easy. I'm using raw_input() to get the selection from the user.
The problem is that raw_input (and input) require the user to press Enter after they make a selection. Is there any way to make the program act immediately upon a keystroke? Here's what I've got so far:
import sys
... | [
"On Windows:\nimport msvcrt\nanswer=msvcrt.getch()\n\n",
"On Linux:\n\nset raw mode\nselect and read the keystroke\nrestore normal settings\n\n\nimport sys\nimport select\nimport termios\nimport tty\n\ndef getkey():\n old_settings = termios.tcgetattr(sys.stdin)\n tty.setraw(sys.stdin.fileno())\n select.s... | [
10,
9,
4,
0
] | [] | [] | [
"python"
] | stackoverflow_0000001829_python.txt |
Q:
File size differences after copying a file to a server vía FTP
I have created a PHP-script to update a web server that is live inside a local directory.
I'm migrating the script into Python. It works fine for the most part, but after a PUT command, the size of the file appears to change. Thus, the size of the file... | File size differences after copying a file to a server vía FTP | I have created a PHP-script to update a web server that is live inside a local directory.
I'm migrating the script into Python. It works fine for the most part, but after a PUT command, the size of the file appears to change. Thus, the size of the file is different from that of the file on the server.
Once I download ... | [
"Do you need to open the locfile in binary using rb?\nf = open (locfile, \"rb\")\n\n",
"Well if you go under the properties of your file in Windows or a *nix environment, you will notice two sizes. One is the sector size, and one is the actual size. The sector size is the number of sectors in bytes that are use... | [
17,
3,
0
] | [] | [] | [
"ftp",
"ftplib",
"php",
"python",
"webserver"
] | stackoverflow_0000002311_ftp_ftplib_php_python_webserver.txt |
Q:
Programmatically talking to a Serial Port in OS X or Linux
I have a Prolite LED sign that I like to set up to show scrolling search queries from a apache logs and other fun statistics. The problem is, my G5 does not have a serial port, so I have to use a usb to serial dongle. It shows up as /dev/cu.usbserial and /... | Programmatically talking to a Serial Port in OS X or Linux | I have a Prolite LED sign that I like to set up to show scrolling search queries from a apache logs and other fun statistics. The problem is, my G5 does not have a serial port, so I have to use a usb to serial dongle. It shows up as /dev/cu.usbserial and /dev/tty.usbserial .
When i do this everything seems to be hunky... | [
"/dev/cu.xxxxx is the \"callout\" device, it's what you use when you establish a connection to the serial device and start talking to it. /dev/tty.xxxxx is the \"dialin\" device, used for monitoring a port for incoming calls for e.g. a fax listener.\n",
"have you tried watching the traffic between the GUI and the... | [
5,
0
] | [] | [] | [
"linux",
"macos",
"python",
"serial_port"
] | stackoverflow_0000003976_linux_macos_python_serial_port.txt |
Q:
Get a preview JPEG of a PDF on Windows?
I have a cross-platform (Python) application which needs to generate a JPEG preview of the first page of a PDF.
On the Mac I am spawning sips. Is there something similarly simple I can do on Windows?
A:
ImageMagick delegates the PDF->bitmap conversion to GhostScript anywa... | Get a preview JPEG of a PDF on Windows? | I have a cross-platform (Python) application which needs to generate a JPEG preview of the first page of a PDF.
On the Mac I am spawning sips. Is there something similarly simple I can do on Windows?
| [
"ImageMagick delegates the PDF->bitmap conversion to GhostScript anyway, so here's a command you can use (it's based on the actual command listed by the ps:alpha delegate in ImageMagick, just adjusted to use JPEG as output):\ngs -q -dQUIET -dPARANOIDSAFER -dBATCH -dNOPAUSE -dNOPROMPT \\\n-dMaxBitmap=500000000 -dLas... | [
44,
16,
5
] | [] | [] | [
"image",
"pdf",
"python",
"windows"
] | stackoverflow_0000000502_image_pdf_python_windows.txt |
Q:
Best way to abstract season/show/episode data
Basically, I've written an API to www.thetvdb.com in Python. The current code can be found here.
It grabs data from the API as requested, and has to store the data somehow, and make it available by doing:
print tvdbinstance[1][23]['episodename'] # get the name of episo... | Best way to abstract season/show/episode data | Basically, I've written an API to www.thetvdb.com in Python. The current code can be found here.
It grabs data from the API as requested, and has to store the data somehow, and make it available by doing:
print tvdbinstance[1][23]['episodename'] # get the name of episode 23 of season 1
What is the "best" way to abstra... | [
"OK, what you need is classobj from new module. That would allow you to construct exception classes dynamically (classobj takes a string as an argument for the class name). \nimport new\nmyexc=new.classobj(\"ExcName\",(Exception,),{})\ni=myexc(\"This is the exc msg!\")\nraise i\n\nthis gives you:\nTraceback (most r... | [
7,
4,
0,
0,
0
] | [] | [] | [
"data_structures",
"python"
] | stackoverflow_0000005966_data_structures_python.txt |
Q:
Python Regular Expressions to implement string unescaping
I am trying to implement string unescaping with Python regex and backreferences, and it doesn't seem to want to work very well. I'm sure it's something I'm doing wrong but I can't figure out what...
>>> import re
>>> mystring = r"This is \n a test \r"
>>> p... | Python Regular Expressions to implement string unescaping | I am trying to implement string unescaping with Python regex and backreferences, and it doesn't seem to want to work very well. I'm sure it's something I'm doing wrong but I can't figure out what...
>>> import re
>>> mystring = r"This is \n a test \r"
>>> p = re.compile( "\\\\(\\S)" )
>>> p.sub( "\\1", mystring )
'This... | [
"Isn't that what Anders' second example does?\nIn 2.5 there's also a string-escape encoding you can apply:\n>>> mystring = r\"This is \\n a test \\r\"\n>>> mystring.decode('string-escape')\n'This is \\n a test \\r'\n>>> print mystring.decode('string-escape')\nThis is \n a test \n>>> \n\n",
"Well, I think you migh... | [
10,
3,
1,
0,
0
] | [] | [] | [
"backreference",
"python",
"regex"
] | stackoverflow_0000013791_backreference_python_regex.txt |
Q:
What's the best way to distribute python command-line tools?
My current setup.py script works okay, but it installs tvnamer.py (the tool) as tvnamer.py into site-packages or somewhere similar..
Can I make setup.py install tvnamer.py as tvnamer, and/or is there a better way of installing command-line applications?
... | What's the best way to distribute python command-line tools? | My current setup.py script works okay, but it installs tvnamer.py (the tool) as tvnamer.py into site-packages or somewhere similar..
Can I make setup.py install tvnamer.py as tvnamer, and/or is there a better way of installing command-line applications?
| [
"Try the entry_points.console_scripts parameter in the setup() call. As described in the setuptools docs, this should do what I think you want.\nTo reproduce here:\nfrom setuptools import setup\n\nsetup(\n # other arguments here...\n entry_points = {\n 'console_scripts': [\n 'foo = package.m... | [
38
] | [] | [] | [
"command_line",
"packaging",
"python"
] | stackoverflow_0000017893_command_line_packaging_python.txt |
Q:
Introducing Python
The company I used to work with has two developers working fulltime, and a handful of freelancers. They're in the process of hiring a new lead developer to try to bring order and management to the development.
But, currently, one of the developers has seen the light of Django (the company has on... | Introducing Python | The company I used to work with has two developers working fulltime, and a handful of freelancers. They're in the process of hiring a new lead developer to try to bring order and management to the development.
But, currently, one of the developers has seen the light of Django (the company has only developed in PHP to d... | [
"I recently introduced Python to my company, which does consulting work for the Post Office. I did this by waiting until there was a project for which I would be the only programmer, then getting permission to do this new project in Python. I then did another small project in Python with similarly impressive resu... | [
15,
4,
2,
1,
1,
0,
0,
0
] | [] | [] | [
"php",
"python"
] | stackoverflow_0000019654_php_python.txt |
Q:
How to check set of files conform to a naming scheme
I have a bunch of files (TV episodes, although that is fairly arbitrary) that I want to check match a specific naming/organisation scheme..
Currently: I have three arrays of regex, one for valid filenames, one for files missing an episode name, and one for valid... | How to check set of files conform to a naming scheme | I have a bunch of files (TV episodes, although that is fairly arbitrary) that I want to check match a specific naming/organisation scheme..
Currently: I have three arrays of regex, one for valid filenames, one for files missing an episode name, and one for valid paths.
Then, I loop though each valid-filename regex, if ... | [
"\nI want to add a rule that checks for\n the presence of a folder.jpg file in\n each directory, but to add this would\n make the code substantially more messy\n in it's current state..\n\nThis doesn't look bad. In fact your current code does it very nicely, and Sven mentioned a good way to do it as well:\n\nG... | [
2,
0
] | [] | [] | [
"naming",
"python",
"validation"
] | stackoverflow_0000019030_naming_python_validation.txt |
Q:
Date/time conversion using time.mktime seems wrong
>>> import time
>>> time.strptime("01-31-2009", "%m-%d-%Y")
(2009, 1, 31, 0, 0, 0, 5, 31, -1)
>>> time.mktime((2009, 1, 31, 0, 0, 0, 5, 31, -1))
1233378000.0
>>> 60*60*24 # seconds in a day
86400
>>> 1233378000.0 / 86400
14275.208333333334
time.mktime should retu... | Date/time conversion using time.mktime seems wrong | >>> import time
>>> time.strptime("01-31-2009", "%m-%d-%Y")
(2009, 1, 31, 0, 0, 0, 5, 31, -1)
>>> time.mktime((2009, 1, 31, 0, 0, 0, 5, 31, -1))
1233378000.0
>>> 60*60*24 # seconds in a day
86400
>>> 1233378000.0 / 86400
14275.208333333334
time.mktime should return the number of seconds since the epoch. Since I'm givi... | [
"Short answer: Because of timezones.\nThe Epoch is in UTC.\nFor example, I'm on IST (Irish Standard Time) or UTC+1. time.mktime() is relative to my timezone, so on my system this refers to\n>>> time.mktime((2009, 1, 31, 0, 0, 0, 5, 31, -1))\n1233360000.0\n\nBecause you got the result 1233378000, that would suggest ... | [
7,
3,
2,
0
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0000021961_datetime_python.txt |
Q:
Does PHP have an equivalent to this type of Python string substitution?
Python has this wonderful way of handling string substitutions using dictionaries:
>>> 'The %(site)s site %(adj)s because it %(adj)s' % {'site':'Stackoverflow', 'adj':'rocks'}
'The Stackoverflow site rocks because it rocks'
I love this becaus... | Does PHP have an equivalent to this type of Python string substitution? | Python has this wonderful way of handling string substitutions using dictionaries:
>>> 'The %(site)s site %(adj)s because it %(adj)s' % {'site':'Stackoverflow', 'adj':'rocks'}
'The Stackoverflow site rocks because it rocks'
I love this because you can specify a value once in the dictionary and then replace it all over... | [
"function subst($str, $dict){\n return preg_replace(array_map(create_function('$a', 'return \"/%\\\\($a\\\\)s/\";'), array_keys($dict)), array_values($dict), $str);\n }\n\nYou call it like so:\necho subst('The %(site)s site %(adj)s because it %(adj)s', array('site'=>'Stackoverflow', 'adj'=>'rocks'));\n\n",
"@M... | [
5,
4,
1
] | [] | [] | [
"php",
"python",
"string"
] | stackoverflow_0000028165_php_python_string.txt |
Q:
How do I create an xml document in python
Here is my sample code:
from xml.dom.minidom import *
def make_xml():
doc = Document()
node = doc.createElement('foo')
node.innerText = 'bar'
doc.appendChild(node)
return doc
if __name__ == '__main__':
make_xml().writexml(sys.stdout)
when I run the... | How do I create an xml document in python | Here is my sample code:
from xml.dom.minidom import *
def make_xml():
doc = Document()
node = doc.createElement('foo')
node.innerText = 'bar'
doc.appendChild(node)
return doc
if __name__ == '__main__':
make_xml().writexml(sys.stdout)
when I run the above code I get this:
<?xml version="1.0" ?>
... | [
"@Daniel\nThanks for the reply, I also figured out how to do it with the minidom (I'm not sure of the difference between the ElementTree vs the minidom)\n\n\nfrom xml.dom.minidom import *\ndef make_xml():\n doc = Document();\n node = doc.createElement('foo')\n node.appendChild(doc.createTextNode('bar'))\n ... | [
13,
9
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0000029243_python_xml.txt |
Q:
Proprietary plug-ins for GPL programs: what about interpreted languages?
I am developing a GPL-licensed application in Python and need to know if the GPL allows my program to use proprietary plug-ins. This is what the FSF has to say on the issue:
If a program released under the GPL uses plug-ins, what are the req... | Proprietary plug-ins for GPL programs: what about interpreted languages? | I am developing a GPL-licensed application in Python and need to know if the GPL allows my program to use proprietary plug-ins. This is what the FSF has to say on the issue:
If a program released under the GPL uses plug-ins, what are the requirements for the licenses of a plug-in?
It depends on how the program invokes... | [
"\nhe distinction between fork/exec and dynamic linking, besides being kind of artificial,\n\nI don't think its artificial at all. Basically they are just making the division based upon the level of integration. If the program has \"plugins\" which are essentially fire and forget with no API level integration, th... | [
7,
1,
0
] | [] | [] | [
"interpreted_language",
"licensing",
"open_source",
"plugins",
"python"
] | stackoverflow_0000031412_interpreted_language_licensing_open_source_plugins_python.txt |
Q:
Install Python to match directory layout in OS X 10.5
The default Python install on OS X 10.5 is 2.5.1 with a FAT 32 bit (Intel and PPC) client. I want to setup apache and mysql to run django. In the past, I have run Apache and MySQL to match this install in 32 bit mode (even stripping out the 64 bit stuff from Ap... | Install Python to match directory layout in OS X 10.5 | The default Python install on OS X 10.5 is 2.5.1 with a FAT 32 bit (Intel and PPC) client. I want to setup apache and mysql to run django. In the past, I have run Apache and MySQL to match this install in 32 bit mode (even stripping out the 64 bit stuff from Apache to make it work).
I want to upgrade Python to 64 bit. ... | [
"Not sure I entirely understand your question, but can't you simply build and install a 64 bit version and then create symbolic links so that /Library/Python/2.5 and below point to your freshly built version of python?\n",
"Personally, I wouldn't worry about it until you see a problem. Messing with the default p... | [
1,
1,
1,
0,
0
] | [] | [] | [
"64_bit",
"macos",
"python"
] | stackoverflow_0000029856_64_bit_macos_python.txt |
Q:
ssh hangs when command invoked directly, but exits cleanly when run interactive
I need to launch a server on the remote machine and retrieve the port number that the server process is lsitening on. When invoked, the server will listen on a random port and output the port number on stderr.
I want to automate the p... | ssh hangs when command invoked directly, but exits cleanly when run interactive | I need to launch a server on the remote machine and retrieve the port number that the server process is lsitening on. When invoked, the server will listen on a random port and output the port number on stderr.
I want to automate the process of logging on to the remote machine, launching the process, and retrieving the... | [
"\ns = p.stderr.readline()\n\n\nI suspect it's the above line. When you invoke a command directly through ssh, you don't get your full pty (assuming Linux), and thus no stderr to read from.\nWhen you log in interactively, stdin, stdout, and stderr are set up for you, and so your script works.\n",
"what if you do... | [
3,
0
] | [] | [] | [
"python",
"ssh"
] | stackoverflow_0000033475_python_ssh.txt |
Q:
Why does Python's iter() on a mapping return iterkeys() instead of iteritems()?
It seems like if you want to get the keys of a mapping, you ask for them; otherwise, give me the whole mapping (constituted by a set of key-value pairs). Is there a historical reason for this?
A:
Check out this thread for a discussio... | Why does Python's iter() on a mapping return iterkeys() instead of iteritems()? | It seems like if you want to get the keys of a mapping, you ask for them; otherwise, give me the whole mapping (constituted by a set of key-value pairs). Is there a historical reason for this?
| [
"Check out this thread for a discussion on the reasons behind this behavior (including that Guido likes it, and it's not likely to change).\n"
] | [
11
] | [] | [] | [
"iteration",
"mapping",
"python"
] | stackoverflow_0000035569_iteration_mapping_python.txt |
Q:
Django ImageField core=False in newforms admin
In the transition to newforms admin I'm having difficulty figuring out how specify core=False for ImageFields.
I get the following error:
TypeError: __init__() got an unexpected keyword argument 'core'
[Edit] However, by just removing the core argument I get a "This ... | Django ImageField core=False in newforms admin | In the transition to newforms admin I'm having difficulty figuring out how specify core=False for ImageFields.
I get the following error:
TypeError: __init__() got an unexpected keyword argument 'core'
[Edit] However, by just removing the core argument I get a "This field is required." error in the admin interface on ... | [
"To get rid of \"This field is required,\" you need to make it not required, by using blank=True (and possibly null=True as well, if it's not a CharField).\n",
"The core attribute isn't used anymore.\nFrom Brian Rosner's Blog:\n\nYou can safely just remove any and all core arguments. They are no longer used. newf... | [
5,
4,
2
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0000034209_django_django_models_python.txt |
Q:
Programmatically editing Python source
This is something that I think would be very useful. Basically, I'd like there to be a way to edit Python source programmatically without requiring human intervention. There are a couple of things I would like to do with this:
Edit the configuration of Python apps that use... | Programmatically editing Python source | This is something that I think would be very useful. Basically, I'd like there to be a way to edit Python source programmatically without requiring human intervention. There are a couple of things I would like to do with this:
Edit the configuration of Python apps that use source modules for configuration.
Set up a ... | [
"Python's standard library provides pretty good facilities for working with Python source; note the tokenize and parser modules.\n",
"I had the same issue and I simply opened the file and did some replace: then reload the file in the Python interpreter. This works fine and is easy to do. \nOtherwise AFAIK you hav... | [
6,
0,
0
] | [] | [] | [
"file_io",
"python"
] | stackoverflow_0000032385_file_io_python.txt |
Q:
"The system cannot find the file specified" when invoking subprocess.Popen in python
I'm trying to use svnmerge.py to merge some files. Under the hood it uses python, and when I use it I get an error - "The system cannot find the file specified". Colleagues at work are running the same version of svnmerge.py, and ... | "The system cannot find the file specified" when invoking subprocess.Popen in python | I'm trying to use svnmerge.py to merge some files. Under the hood it uses python, and when I use it I get an error - "The system cannot find the file specified". Colleagues at work are running the same version of svnmerge.py, and of python (2.5.2, specifically r252:60911) without an issue.
I found this link, which desc... | [
"It's a bug, see the documentation of subprocess.Popen. There either needs to be a \"shell=True\" option, or the first argument needs to be a sequence ['svn', '--version']. As it is now, Popen is looking for an executable named, literally, \"svn --version\" which it doesn't find.\nI don't know why it would work for... | [
21
] | [] | [] | [
"python",
"svn_merge"
] | stackoverflow_0000036324_python_svn_merge.txt |
Q:
How do I add data to an existing model in Django?
Currently, I am writing up a bit of a product-based CMS as my first project.
Here is my question. How can I add additional data (products) to my Product model?
I have added '/admin/products/add' to my urls.py, but I don't really know where to go from there. How wou... | How do I add data to an existing model in Django? | Currently, I am writing up a bit of a product-based CMS as my first project.
Here is my question. How can I add additional data (products) to my Product model?
I have added '/admin/products/add' to my urls.py, but I don't really know where to go from there. How would i build both my view and my template? Please keep in... | [
"You will want to wire your URL to the Django create_object generic view, and pass it either \"model\" (the model you want to create) or \"form_class\" (a customized ModelForm class). There are a number of other arguments you can also pass to override default behaviors.\nSample URLconf for the simplest case:\nfrom... | [
7
] | [
"This topic is covered in Django tutorials.\n",
"Follow the Django tutorial for setting up the \"admin\" part of an application. This will allow you to modify your database.\nDjango Admin Setup\nAlternatively, you can just connect directly to the database using the standard tools for whatever database type you ar... | [
-1,
-2
] | [
"django",
"python"
] | stackoverflow_0000036812_django_python.txt |
Q:
How can I simply inherit methods from an existing instance?
Below I have a very simple example of what I'm trying to do. I want to be able to use HTMLDecorator with any other class. Ignore the fact it's called decorator, it's just a name.
import cgi
class ClassX(object):
pass # ... with own __repr__
class Cl... | How can I simply inherit methods from an existing instance? | Below I have a very simple example of what I'm trying to do. I want to be able to use HTMLDecorator with any other class. Ignore the fact it's called decorator, it's just a name.
import cgi
class ClassX(object):
pass # ... with own __repr__
class ClassY(object):
pass # ... with own __repr__
inst_x=ClassX()
in... | [
"\nVery close, but then I lose everything from ClassX. Below is something a collegue gave me that does do the trick, but it's hideous. There has to be a better way.\n\nLooks like you're trying to set up some sort of proxy object scheme. That's doable, and there are better solutions than your colleague's, but first ... | [
2,
2,
0,
0,
0,
0
] | [] | [] | [
"inheritance",
"object",
"oop",
"python"
] | stackoverflow_0000037479_inheritance_object_oop_python.txt |
Q:
Why is the subprocess.Popen class not named Subprocess?
The primary class in the subprocess module is name Popen, and represents a subprocess. Popen sounds like someone was trying to force the name to follow some function naming format, rather than chosing a name that actually represents what the object is. Does ... | Why is the subprocess.Popen class not named Subprocess? | The primary class in the subprocess module is name Popen, and represents a subprocess. Popen sounds like someone was trying to force the name to follow some function naming format, rather than chosing a name that actually represents what the object is. Does anyone know why it was chosen over something simple like, say... | [
"Now, I'm not saying that this is the greatest name in the world, but here was the idea as I understand it.\nOriginally, the popen family was in the os module and was an implementation of the venerable posix popen. The movement to the subprocess module would have been an opportune time to rename them, but I guess ... | [
8,
5
] | [
"I suppose the name was chosen because the functionality subprocess is replacing was formerly in the os module as the os.popen function. There could be even ways to automate migration between the two.\n"
] | [
-1
] | [
"python",
"subprocess"
] | stackoverflow_0000038197_python_subprocess.txt |
Q:
Retrieving an Oracle timestamp using Python's Win32 ODBC module
Given an Oracle table created using the following:
CREATE TABLE Log(WhenAdded TIMESTAMP(6) WITH TIME ZONE);
Using the Python ODBC module from its Win32 extensions (from the win32all package), I tried the following:
import dbi, odbc
connection = odbc... | Retrieving an Oracle timestamp using Python's Win32 ODBC module | Given an Oracle table created using the following:
CREATE TABLE Log(WhenAdded TIMESTAMP(6) WITH TIME ZONE);
Using the Python ODBC module from its Win32 extensions (from the win32all package), I tried the following:
import dbi, odbc
connection = odbc.odbc("Driver=Oracle in OraHome92;Dbq=SERVER;Uid=USER;Pwd=PASSWD")
c... | [
"I believe this is a bug in the Oracle ODBC driver. Basically, the Oracle ODBC driver does not support the TIMESTAMP WITH (LOCAL) TIME ZONE data types, only the TIMESTAMP data type. As you have discovered, one workaround is in fact to use the TO_CHAR method.\nIn your example you are not actually reading the time zo... | [
2,
1
] | [] | [] | [
"ora_00932",
"oracle",
"python"
] | stackoverflow_0000038435_ora_00932_oracle_python.txt |
Q:
Ruby "is" equivalent
Is there a Ruby equivalent for Python's "is"? It tests whether two objects are identical (i.e. have the same memory location).
A:
Use a.equal? b
http://www.ruby-doc.org/core/classes/Object.html
Unlike ==, the equal? method should never be overridden by subclasses: it is used to determine ob... | Ruby "is" equivalent | Is there a Ruby equivalent for Python's "is"? It tests whether two objects are identical (i.e. have the same memory location).
| [
"Use a.equal? b\nhttp://www.ruby-doc.org/core/classes/Object.html\n\nUnlike ==, the equal? method should never be overridden by subclasses: it is used to determine object identity (that is, a.equal?(b) iff a is the same object as b). \n\n",
"You could also use __id__. This gives you the objects internal ID number... | [
13,
2
] | [] | [] | [
"python",
"ruby"
] | stackoverflow_0000035634_python_ruby.txt |
Q:
Why is my instance variable not in __dict__?
If I create a class A as follows:
class A:
def __init__(self):
self.name = 'A'
Inspecting the __dict__ member looks like {'name': 'A'}
If however I create a class B:
class B:
name = 'B'
__dict__ is empty.
What is the difference between the two, and why... | Why is my instance variable not in __dict__? | If I create a class A as follows:
class A:
def __init__(self):
self.name = 'A'
Inspecting the __dict__ member looks like {'name': 'A'}
If however I create a class B:
class B:
name = 'B'
__dict__ is empty.
What is the difference between the two, and why doesn't name show up in B's __dict__?
| [
"B.name is a class attribute, not an instance attribute. It shows up in B.__dict__, but not in b = B(); b.__dict__.\nThe distinction is obscured somewhat because when you access an attribute on an instance, the class dict is a fallback. So in the above example, b.name will give you the value of B.name.\n",
"cla... | [
46,
12
] | [] | [] | [
"python"
] | stackoverflow_0000035805_python.txt |
Q:
Javascript equivalent of Python's locals()?
In Python one can get a dictionary of all local and global variables in the current scope with the built-in functions locals() and globals(). Is there some equivalent way of doing this in Javascript? For instance, I would like to do something like the following:
var fo... | Javascript equivalent of Python's locals()? | In Python one can get a dictionary of all local and global variables in the current scope with the built-in functions locals() and globals(). Is there some equivalent way of doing this in Javascript? For instance, I would like to do something like the following:
var foo = function(){ alert('foo'); };
var bar = functi... | [
"\nlocals() - No. \nglobals() - Yes.\n\nwindow is a reference to the global scope, like globals() in python.\nglobals()[\"foo\"]\n\nis the same as:\nwindow[\"foo\"]\n\n",
"Well, I don't think that there is something like that in js. You can always use eval instead of locals(). Like this: \neval(s+\"()\");\n\nYou ... | [
18,
4,
3,
0,
0
] | [
"AFAIK, no. If you just want to check the existence of a given variable, you can do it by testing for it, something like this:\nif (foo) foo();\n\n"
] | [
-1
] | [
"javascript",
"python"
] | stackoverflow_0000039960_javascript_python.txt |
Q:
Using C in a shared multi-platform POSIX environment
I write tools that are used in a shared workspace. Since there are multiple OS's working in this space, we generally use Python and standardize the version that is installed across machines. However, if I wanted to write some things in C, I was wondering if mayb... | Using C in a shared multi-platform POSIX environment | I write tools that are used in a shared workspace. Since there are multiple OS's working in this space, we generally use Python and standardize the version that is installed across machines. However, if I wanted to write some things in C, I was wondering if maybe I could have the application wrapped in a Python script,... | [
"Launching a Python interpreter instance just to select the right binary to run would be much heavier than you need. I'd distribute a shell .rc file which provides aliases.\nIn /shared/bin, you put the various binaries: /shared/bin/toolname-mac, /shared/bin/toolname-debian-x86, /shared/bin/toolname-netbsd-dreamcas... | [
2,
1,
0,
0
] | [] | [] | [
"c",
"cross_platform",
"posix",
"python",
"scripting"
] | stackoverflow_0000039847_c_cross_platform_posix_python_scripting.txt |
Q:
cx_Oracle: how do I get the ORA-xxxxx error number?
In a try/except block, how do I extract the Oracle error number?
A:
try:
cursor.execute("select 1 / 0 from dual")
except cx_Oracle.DatabaseError, e:
error, = e
print "Code:", error.code
print "Message:", error.message
This results in the following ... | cx_Oracle: how do I get the ORA-xxxxx error number? | In a try/except block, how do I extract the Oracle error number?
| [
"try:\n cursor.execute(\"select 1 / 0 from dual\")\nexcept cx_Oracle.DatabaseError, e:\n error, = e\n print \"Code:\", error.code\n print \"Message:\", error.message\n\nThis results in the following output:\nCode: 1476\nMessage: ORA-01476: divisor is equal to zero\n\n"
] | [
13
] | [] | [] | [
"cx_oracle",
"oracle",
"python"
] | stackoverflow_0000040586_cx_oracle_oracle_python.txt |
Q:
Is there a python module for regex matching in zip files
I have over a million text files compressed into 40 zip files. I also have a list of about 500 model names of phones. I want to find out the number of times a particular model was mentioned in the text files.
Is there any python module which can do a regex ... | Is there a python module for regex matching in zip files | I have over a million text files compressed into 40 zip files. I also have a list of about 500 model names of phones. I want to find out the number of times a particular model was mentioned in the text files.
Is there any python module which can do a regex match on the files without unzipping it. Is there a simple way... | [
"There's nothing that will automatically do what you want.\nHowever, there is a python zipfile module that will make this easy to do. Here's how to iterate over the lines in the file.\n#!/usr/bin/python\n\nimport zipfile\nf = zipfile.ZipFile('myfile.zip')\n\nfor subfile in f.namelist():\n print subfile\n dat... | [
10,
0,
0,
0
] | [] | [] | [
"python",
"regex",
"text_processing",
"zip"
] | stackoverflow_0000014281_python_regex_text_processing_zip.txt |
Q:
How do I do monkeypatching in python?
I've had to do some introspection in python and it wasn't pretty:
name = sys._getframe(1).f_code
name = "%s:%d %s()" %(os.path.split(name.co_filename)[1],name.co_firstlineno,name.co_name)
To get something like
foo.py:22 bar() blah blah
In our debugging output.
I'd ideally li... | How do I do monkeypatching in python? | I've had to do some introspection in python and it wasn't pretty:
name = sys._getframe(1).f_code
name = "%s:%d %s()" %(os.path.split(name.co_filename)[1],name.co_firstlineno,name.co_name)
To get something like
foo.py:22 bar() blah blah
In our debugging output.
I'd ideally like to prepend anything to stderr with this ... | [
"A print statement does its IO through \"sys.stdout.write\" so you can override sys.stdout if you want to manipulate the print stream.\n",
"The python inspect module makes this a lot easier and cleaner. \n"
] | [
3,
1
] | [] | [] | [
"monkeypatching",
"python"
] | stackoverflow_0000041562_monkeypatching_python.txt |
Q:
Standard way to open a folder window in linux?
I want to open a folder window, in the appropriate file manager, from within a cross-platform (windows/mac/linux) Python application.
On OSX, I can open a window in the finder with
os.system('open "%s"' % foldername)
and on Windows with
os.startfile(foldername)
What... | Standard way to open a folder window in linux? | I want to open a folder window, in the appropriate file manager, from within a cross-platform (windows/mac/linux) Python application.
On OSX, I can open a window in the finder with
os.system('open "%s"' % foldername)
and on Windows with
os.startfile(foldername)
What about unix/linux? Is there a standard way to do thi... | [
"os.system('xdg-open \"%s\"' % foldername)\n\nxdg-open can be used for files/urls also\n",
"this would probably have to be done manually, or have as a config item since there are many file managers that users may want to use. Providing a way for command options as well.\nThere might be an function that launches t... | [
15,
0,
0
] | [] | [] | [
"cross_platform",
"desktop",
"linux",
"python"
] | stackoverflow_0000041969_cross_platform_desktop_linux_python.txt |
Q:
Pure Python library to generate Identicons?
Does anyone know of a FOSS Python lib for generating Identicons? I've looked, but so far I haven't had much luck.
A:
I've found two implementations:
http://coderepos.org/share/browser/lang/python/misc/identicon.py
http://code.google.com/p/visicon/
| Pure Python library to generate Identicons? | Does anyone know of a FOSS Python lib for generating Identicons? I've looked, but so far I haven't had much luck.
| [
"I've found two implementations:\nhttp://coderepos.org/share/browser/lang/python/misc/identicon.py\nhttp://code.google.com/p/visicon/\n"
] | [
12
] | [] | [] | [
"identicon",
"python"
] | stackoverflow_0000042093_identicon_python.txt |
Q:
How can I get a commit message from a bzr post-commit hook?
I'm trying to write a bzr post-commit hook for my private bugtracker, but I'm stuck at the function signature of
post_commit(local, master, old_revno, old_revid, new_revno, mew_revid)
How can I extract the commit message for the branch from this with bz... | How can I get a commit message from a bzr post-commit hook? | I'm trying to write a bzr post-commit hook for my private bugtracker, but I'm stuck at the function signature of
post_commit(local, master, old_revno, old_revid, new_revno, mew_revid)
How can I extract the commit message for the branch from this with bzrlib in Python?
| [
"And the answer is like so:\ndef check_commit_msg(local, master, old_revno, old_revid, new_revno, new_revid):\n branch = local or master\n revision = branch.repository.get_revision(new_revid)\n print revision.message\n\nlocal and master are Branch objects, so once you have a revision, it's easy to extract ... | [
5
] | [] | [] | [
"bazaar",
"dvcs",
"python"
] | stackoverflow_0000043099_bazaar_dvcs_python.txt |
Q:
Can the HTTP version or headers affect the visual appearance of a web page?
I know, I would have thought the answer was obviously "no" as well, but I am experiencing a strange situation where when I view my site from our staging server it appears slightly larger than when I view it from my local dev server. I hav... | Can the HTTP version or headers affect the visual appearance of a web page? | I know, I would have thought the answer was obviously "no" as well, but I am experiencing a strange situation where when I view my site from our staging server it appears slightly larger than when I view it from my local dev server. I have used Charles to confirm that all of the content -- the HTML, the images, the CS... | [
"Have you tried View -> Zoom -> Reset on both sites?\n"
] | [
9
] | [] | [] | [
"django",
"firefox",
"python"
] | stackoverflow_0000045013_django_firefox_python.txt |
Q:
Python packages - import by class, not file
Say I have the following file structure:
app/
app.py
controllers/
__init__.py
project.py
plugin.py
If app/controllers/project.py defines a class Project, app.py would import it like this:
from app.controllers.project import Project
I'd like to just be a... | Python packages - import by class, not file | Say I have the following file structure:
app/
app.py
controllers/
__init__.py
project.py
plugin.py
If app/controllers/project.py defines a class Project, app.py would import it like this:
from app.controllers.project import Project
I'd like to just be able to do:
from app.controllers import Project
H... | [
"You need to put\nfrom project import Project\n\nin controllers/__init__.py.\nNote that when Absolute imports become the default (Python 2.7?), you will want to add a dot before the module name (to avoid collisions with a top-level model named project), i.e.,\nfrom .project import Project\n\n"
] | [
103
] | [] | [] | [
"package",
"python"
] | stackoverflow_0000045122_package_python.txt |
Q:
Where can I find the time and space complexity of the built-in sequence types in Python
I've been unable to find a source for this information, short of looking through the Python source code myself to determine how the objects work. Does anyone know where I could find this online?
A:
Checkout the TimeComplexity... | Where can I find the time and space complexity of the built-in sequence types in Python | I've been unable to find a source for this information, short of looking through the Python source code myself to determine how the objects work. Does anyone know where I could find this online?
| [
"Checkout the TimeComplexity page on the py dot org wiki. It covers set/dicts/lists/etc at least as far as time complexity goes.\n",
"Raymond D. Hettinger does an excellent talk (slides) about Python's built-in collections called 'Core Python Containers - Under the Hood'. The version I saw focussed mainly on set ... | [
19,
15,
2
] | [] | [] | [
"big_o",
"complexity_theory",
"performance",
"python",
"sequences"
] | stackoverflow_0000045228_big_o_complexity_theory_performance_python_sequences.txt |
Q:
Pylons error - 'MySQL server has gone away'
I'm using Pylons (a python framework) to serve a simple web application, but it seems to die from time to time, with this in the error log: (2006, 'MySQL server has gone away')
I did a bit of checking, and saw that this was because the connections to MySQL were not being... | Pylons error - 'MySQL server has gone away' | I'm using Pylons (a python framework) to serve a simple web application, but it seems to die from time to time, with this in the error log: (2006, 'MySQL server has gone away')
I did a bit of checking, and saw that this was because the connections to MySQL were not being renewed. This shouldn't be a problem though, bec... | [
"I think I fixed it. It's turns out I had a simple config error. My ini file read:\nsqlalchemy.default.url = [connection string here]\nsqlalchemy.pool_recycle = 1800\n\nThe problem is that my environment.py file declared that the engine would only map keys with the prefix: sqlalchemy.default so pool_recycle was ign... | [
8,
2
] | [] | [] | [
"mysql",
"pylons",
"python"
] | stackoverflow_0000008154_mysql_pylons_python.txt |
Q:
Django: Print url of view without hardcoding the url
Can i print out a url /admin/manage/products/add of a certain view in a template?
Here is the rule i want to create a link for
(r'^manage/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}),
I would like to have /manage/products/add in... | Django: Print url of view without hardcoding the url | Can i print out a url /admin/manage/products/add of a certain view in a template?
Here is the rule i want to create a link for
(r'^manage/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}),
I would like to have /manage/products/add in a template without hardcoding it. How can i do this?
Edit... | [
"You can use get_absolute_url, but that will only work for a particular object. Since your object hasn't been created yet, it won't work in this case.\nYou want to use named URL patterns. Here's a quick intro:\nChange the line in your urls.py to:\n(r'^manage/products/add/$', create_object, {'model': Product, 'pos... | [
17,
2,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0000047207_django_python.txt |
Q:
Python: No module named core.exceptions
I'm trying to get Google AppEngine to work on my Debian box and am getting the following error when I try to access my page:
<type 'exceptions.ImportError'>: No module named core.exceptions
The same app works fine for me when I run it on my other Ubuntu box, so I know it's... | Python: No module named core.exceptions | I'm trying to get Google AppEngine to work on my Debian box and am getting the following error when I try to access my page:
<type 'exceptions.ImportError'>: No module named core.exceptions
The same app works fine for me when I run it on my other Ubuntu box, so I know it's not a problem with the app itself. However, ... | [
"core.exceptions is part of django; what version of django do you have installed? The AppEngine comes with the appropriate version for whatever release you've downloaded (in the lib/django directory). It can be installed by going to that directory and running python setup.py install\n"
] | [
6
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0000048777_google_app_engine_python.txt |
Q:
Python descriptor protocol analog in other languages?
Is there something like the Python descriptor protocol implemented in other languages? It seems like a nice way to increase modularity/encapsulation without bloating your containing class' implementation, but I've never heard of a similar thing in any other lan... | Python descriptor protocol analog in other languages? | Is there something like the Python descriptor protocol implemented in other languages? It seems like a nice way to increase modularity/encapsulation without bloating your containing class' implementation, but I've never heard of a similar thing in any other languages. Is it likely absent from other languages because of... | [
"I've not heard of a direct equivalent either. You could probably achieve the same effect with macros, especially in a language like Lisp which has extremely powerful macros.\nI wouldn't be at all surprised if other languages start to incorporate something similar because it is so powerful.\n",
"Ruby and C# both ... | [
4,
0
] | [] | [] | [
"encapsulation",
"language_features",
"python"
] | stackoverflow_0000034243_encapsulation_language_features_python.txt |
Q:
How do I implement a pre-commit hook script in SVN that calls dos2unix to validate checked-in file
I was wondering if anyone here had some experience writing this type of script and if they could give me some pointers.
I would like to modify this script to validate that the check-in file does not have a Carriage R... | How do I implement a pre-commit hook script in SVN that calls dos2unix to validate checked-in file | I was wondering if anyone here had some experience writing this type of script and if they could give me some pointers.
I would like to modify this script to validate that the check-in file does not have a Carriage Return in the EOL formatting. The EOL format is CR LF in Windows and LF in Unix. When a User checks-in co... | [
"I think you can avoid a commit hook script in this case by using the svn:eol-style property as described in the SVNBook:\n\nEnd-of-Line Character Sequences\nSubversion Properties\n\nThis way SVN can worry about your line endings for you.\nGood luck!\n",
"What exactly are you trying to do?\nOf course, there are n... | [
4,
1
] | [] | [] | [
"dos2unix",
"python",
"svn"
] | stackoverflow_0000048562_dos2unix_python_svn.txt |