content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
What's the most pythonic way of normalizing lineends in a string?
Given a text-string of unknown source, how does one best rewrite it to have a known lineend-convention?
I usually do:
lines = text.splitlines()
text = '\n'.join(lines)
... but this doesn't handle "mixed" text-files of utterly confused conventions (... | What's the most pythonic way of normalizing lineends in a string? | Given a text-string of unknown source, how does one best rewrite it to have a known lineend-convention?
I usually do:
lines = text.splitlines()
text = '\n'.join(lines)
... but this doesn't handle "mixed" text-files of utterly confused conventions (Yes, they still exist!).
Edit
The oneliner of what I'm doing is of cour... | [
"mixed.replace('\\r\\n', '\\n').replace('\\r', '\\n')\n\nshould handle all possible variants.\n",
"\n... but this doesn't handle \"mixed\" text-files of utterly confused conventions (Yes, they still exist!)\n\nActually it should work fine:\n>>> s = 'hello world\\nline 1\\r\\nline 2'\n\n>>> s.splitlines()\n['hello... | [
17,
7,
0
] | [] | [] | [
"line_breaks",
"newline",
"python"
] | stackoverflow_0001749466_line_breaks_newline_python.txt |
Q:
replace or remove one null (python)
I would like to remove one null byte in a string, and sometime replace it with another char.
Like that :
string = "41 00 36 00 36 00 00 00 57 00 46 00 42 00 41 00 61 00 62 00 73 00 20 00 36 00"
i was thinking about using random and replace, but replace always start by the first ... | replace or remove one null (python) | I would like to remove one null byte in a string, and sometime replace it with another char.
Like that :
string = "41 00 36 00 36 00 00 00 57 00 46 00 42 00 41 00 61 00 62 00 73 00 20 00 36 00"
i was thinking about using random and replace, but replace always start by the first one:
replace("00","B",1)
So it's not ran... | [
"Not only that, but 00 isn't \"a null\" by any stretch of the imagination -- it's a 2-characters string. You appear to silently assume that your string is made up of substrings each of two hex digits, and any string operation you perform will have no idea about this little private convention of yours -- if you do ... | [
7,
1,
0,
0
] | [] | [] | [
"python",
"random",
"replace"
] | stackoverflow_0001749827_python_random_replace.txt |
Q:
use random functions (python)
I wonder if we can do that in python, let's suppose we have 3 differents functions to processing datas
like this:
def main():
def process(data):
.....
def process1(data):
.....
def process2(data):
.....
def run():
test = choice([process,process1,process2])... | use random functions (python) | I wonder if we can do that in python, let's suppose we have 3 differents functions to processing datas
like this:
def main():
def process(data):
.....
def process1(data):
.....
def process2(data):
.....
def run():
test = choice([process,process1,process2])
test(data)
run()
main()
C... | [
"Excellent approach (net of some oversimplification in your skeleton code). Since you ask for an example:\nimport random\n\ndef main():\n def process(data):\n return data + [0]\n def process1(data):\n return data + [9]\n def process2(data):\n return data + [7]\n def run(data):\n test = random.c... | [
4,
3,
1,
0
] | [] | [] | [
"function",
"python",
"random"
] | stackoverflow_0001750480_function_python_random.txt |
Q:
Jython 2.1 __getattr__
I am trying to implement a wrapper/proxy class for a java object (baseClient) in jython v2.1. Everything seems to be working ok except when the following statement is encountered:
if __client != None # __client is an instance of the ClientProxy class
raise AttributeError(attr) is called in ... | Jython 2.1 __getattr__ | I am trying to implement a wrapper/proxy class for a java object (baseClient) in jython v2.1. Everything seems to be working ok except when the following statement is encountered:
if __client != None # __client is an instance of the ClientProxy class
raise AttributeError(attr) is called in __getattr__(), because self.... | [
"if __client != None:\n\nFor testing against specific instances such as None, it's idiomatic to use the identity operator:\nif __client is not None:\n\nThis will avoid the problem of calling comparators.\nHowever, the fact that __getattr__ raises AttributeError should not be a problem. The comparator should call ge... | [
0
] | [] | [] | [
"getattr",
"jython",
"python",
"setattr",
"word_wrap"
] | stackoverflow_0001750392_getattr_jython_python_setattr_word_wrap.txt |
Q:
PyQt: No such slot
I am starting to learn Qt4 and Python, following along some tutorial i found on the interwebs. I have the following two files:
lcdrange.py:
from PyQt4 import QtGui, QtCore
class LCDRange(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(... | PyQt: No such slot | I am starting to learn Qt4 and Python, following along some tutorial i found on the interwebs. I have the following two files:
lcdrange.py:
from PyQt4 import QtGui, QtCore
class LCDRange(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
l... | [
"Try this:\nself.connect(lcdRange, QtCore.SIGNAL('valueChanged'), previousRange.setValue)\n\nWhat's the difference?\nThe PyQt documentation has a section about SIGNALS/SLOTS in PyQt, they work a little differently.\nSIGNAL\nSIGNAL('valueChanged') is something called a short-circuit signal. They work only for Python... | [
7,
1,
0
] | [] | [] | [
"pyqt",
"python",
"qt4",
"ruby"
] | stackoverflow_0000577824_pyqt_python_qt4_ruby.txt |
Q:
Making Python Use Code in My Directory (not that in /usr/...)
I am trying to work on a Python library that is already installed on my (Ubuntu) system. I checked out that library, edited some files, and wrote a small script to test my changes. Even though I put my script in the same folder as that of the library, i... | Making Python Use Code in My Directory (not that in /usr/...) | I am trying to work on a Python library that is already installed on my (Ubuntu) system. I checked out that library, edited some files, and wrote a small script to test my changes. Even though I put my script in the same folder as that of the library, it seems Python is using the installed version instead (the one in /... | [
"You can dictate where python searches for modules using the PYTHONPATH environment variable:\n\nWhen a module named spam is imported,\n the interpreter searches for a file\n named spam.py in the current\n directory, and then in the list of\n directories specified by the\n environment variable PYTHONPATH. This... | [
3,
3,
3,
1,
0
] | [] | [] | [
"path",
"python"
] | stackoverflow_0001749452_path_python.txt |
Q:
How do I get something like repeat customers in Django
My models look something like this:
class Customer(models.Model):
name = models.CharField(max_length=100)
class Order(models.Model):
customer = models.ForeignKey(Customer)
date = models.DateField()
total = models.DecimalField(max_digits=5, decimal... | How do I get something like repeat customers in Django | My models look something like this:
class Customer(models.Model):
name = models.CharField(max_length=100)
class Order(models.Model):
customer = models.ForeignKey(Customer)
date = models.DateField()
total = models.DecimalField(max_digits=5, decimal_places=2)
I then have a queryset of orders:
from datetime ... | [
"Always base your query around the object in which you are primarily interested in:\nrepeat_customers = Customer.objects.annotate(order_count=Count('order'))\\\n .filter(order_count__gt=1)\n\nThen if you want to annotate with their totals (you could alternatively do this in the ann... | [
2,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001750806_django_python.txt |
Q:
mongodb, pymongo querying
I've been browsing through the documentation, but I can't seem to figure out a way to perform a find on my mongodb collection using only a key.
For example, let's suppose this is what's inside my collection
{ 'res1': 10 }
{ 'res2: 20 }
How can I query the collection using only the key 'r... | mongodb, pymongo querying | I've been browsing through the documentation, but I can't seem to figure out a way to perform a find on my mongodb collection using only a key.
For example, let's suppose this is what's inside my collection
{ 'res1': 10 }
{ 'res2: 20 }
How can I query the collection using only the key 'res1', in order to get 10 ?
| [
"Not sure exaclty what you want, so... This is if you want all documents that have key res1 set:\ndb.collection.find({'res1': { $exists : true }})\nAnd this is if you want all the documents that have key res1 set to 10:\ndb.collection.find({'res1': 10})\n",
"Ah, I guess I'm structuring my data all wrong, I should... | [
2,
2,
1
] | [] | [] | [
"mongodb",
"python"
] | stackoverflow_0001741379_mongodb_python.txt |
Q:
Python SOAP server / client
I have a problem with Python and SOAP. I need to create a web service based on SOAP in Python. I read that I can use libraries like soaplib, suds and ZSI. I created a Hello World web service with soaplib, like in documentation (http://trac.optio.webfactional.com/wiki/HelloWorld). The pr... | Python SOAP server / client | I have a problem with Python and SOAP. I need to create a web service based on SOAP in Python. I read that I can use libraries like soaplib, suds and ZSI. I created a Hello World web service with soaplib, like in documentation (http://trac.optio.webfactional.com/wiki/HelloWorld). The problem is that I cannot make a cli... | [
"How are you serving the service? soaplib produces a WSGI object, which needs to be served by a webserver. If you are following the helloworld example you link to then you are using CherryPy (a pure python web server) to host the service on your own machine. In the example the port is 7789 (but you can use anything... | [
2,
1
] | [] | [] | [
"python",
"soap",
"web_services"
] | stackoverflow_0001751027_python_soap_web_services.txt |
Q:
How to run multiple Tornado processes/threads/frontends?
In the tornado documentation they show how they can have a very large through-put from 4 frontends. I'd like to run an app in the same way, and would like to have the frontends running as daemon processes managed with an init.d script*.
I'm fairly new to Py... | How to run multiple Tornado processes/threads/frontends? | In the tornado documentation they show how they can have a very large through-put from 4 frontends. I'd like to run an app in the same way, and would like to have the frontends running as daemon processes managed with an init.d script*.
I'm fairly new to Python so don't really know where to start. Currently I'm starti... | [
"Try Supervisor. It's great for managing multiple daemon processes. You configure your applications in the supervisord.conf file and supervisord itself is launched from an init.d script.\n",
"I can vouch for Supervisor too. We have been using tornado in production with 4 instances using supervisor and it is wor... | [
6,
1
] | [] | [] | [
"deployment",
"python",
"tornado"
] | stackoverflow_0001506463_deployment_python_tornado.txt |
Q:
Basic Comet in Python using just std lib
I'm developing a web interface for an already existing desktop application. I've been looking for a way to allow the server to push content to the browser and ended up reaching Comet.
Navigating through the internet, and most of the questions here, I got answers like twiste... | Basic Comet in Python using just std lib | I'm developing a web interface for an already existing desktop application. I've been looking for a way to allow the server to push content to the browser and ended up reaching Comet.
Navigating through the internet, and most of the questions here, I got answers like twisted, orbited, tornado and most of them even poin... | [
"As gs said, just keep the connection open.\nHere's an example WSGI app that sends the current time to the client every second:\nimport time\n\ndef application(environ, start_response):\n start_response('200 OK', [('content-type', 'text/plain')])\n while True:\n time.sleep(1.0)\n yield time.ctim... | [
4,
0,
0
] | [] | [] | [
"comet",
"python"
] | stackoverflow_0001520953_comet_python.txt |
Q:
Stuck on a loop!
I am creating an app which will be used to upload images to a specified server. I have created my GUI in Qt Designer, everything works fine I just am stuck on something that I know is simple. Cant seem to wrap my head around it.
The idea is for the script to go through and see how many text field... | Stuck on a loop! | I am creating an app which will be used to upload images to a specified server. I have created my GUI in Qt Designer, everything works fine I just am stuck on something that I know is simple. Cant seem to wrap my head around it.
The idea is for the script to go through and see how many text fields are filed in with pa... | [
"The issue you have is that you are assigning to the variable fullname three times overwriting it each time. So by the time you get to the for loop only have the last file name available if the last field has been set otherwise you get nothing at all. Your statement that you need a list of full names rather than o... | [
2,
0,
0
] | [] | [] | [
"ftp",
"image",
"python",
"qt_designer",
"range"
] | stackoverflow_0001751359_ftp_image_python_qt_designer_range.txt |
Q:
What's the best python soap stack for consuming Amazon Web Services WSDL?
Python has a number of soap stacks; as near as I can tell, all have substantial defects.
Has anyone had luck consuming and using WSDL for S3, EC2, and SQS in python?
My experience is that suds fails when constructing a Client object; after s... | What's the best python soap stack for consuming Amazon Web Services WSDL? | Python has a number of soap stacks; as near as I can tell, all have substantial defects.
Has anyone had luck consuming and using WSDL for S3, EC2, and SQS in python?
My experience is that suds fails when constructing a Client object; after some wrangling, ZSI generates client code that doesn't work; etc.
Finally, I'm a... | [
"The REST or \"Query\" APIs are definitely easier to use than SOAP, but unfortunately at least once service (EC2) doesn't provide any alternatives to SOAP. As you've already discovered, Python's existing SOAP implementations are woefully inadequate for most purposes; one workaround approach is to just generate the ... | [
3,
1,
0,
0
] | [] | [] | [
"amazon",
"amazon_web_services",
"python",
"soap",
"wsdl"
] | stackoverflow_0000231924_amazon_amazon_web_services_python_soap_wsdl.txt |
Q:
Is there any way to read the header codes without downloading the file at all?
import httplib
conn = httplib.HTTPConnection(head)
conn.request("HEAD",tail)
res = conn.getresponse()
print res.status
I am currently using this to get the HTTP header code of a file.
However, it seems like this code DOWNLOADS the... | Is there any way to read the header codes without downloading the file at all? | import httplib
conn = httplib.HTTPConnection(head)
conn.request("HEAD",tail)
res = conn.getresponse()
print res.status
I am currently using this to get the HTTP header code of a file.
However, it seems like this code DOWNLOADS the file, and then gets the code.
However, some files are actually video files...and i... | [
"Unfortunately the HEAD HTTP Method like all other HTTP method is just a directive to the server. The HTTP spec says that the server must not return the body in case, but if the server is not implemented or configured correctly then it may return the entire contents of the URL.\nThere are other factors that may be ... | [
2,
1,
0,
0
] | [] | [] | [
"header",
"http",
"python"
] | stackoverflow_0001751253_header_http_python.txt |
Q:
How to loop until EOF in Python?
I need to loop until I hit the end of a file-like object, but I'm not finding an "obvious way to do it", which makes me suspect I'm overlooking something, well, obvious. :-)
I have a stream (in this case, it's a StringIO object, but I'm curious about the general case as well) whic... | How to loop until EOF in Python? | I need to loop until I hit the end of a file-like object, but I'm not finding an "obvious way to do it", which makes me suspect I'm overlooking something, well, obvious. :-)
I have a stream (in this case, it's a StringIO object, but I'm curious about the general case as well) which stores an unknown number of records ... | [
"You can combine iteration through iter() with a sentinel:\nfor block in iter(lambda: file_obj.read(4), \"\"):\n use(block)\n\n",
"Have you seen how to iterate over lines in a text file?\nfor line in file_obj:\n use(line)\n\nYou can do the same thing with your own generator:\ndef read_blocks(file_obj, size):\n ... | [
27,
10,
5,
3,
1,
0
] | [] | [] | [
"eof",
"python",
"stringio"
] | stackoverflow_0001752107_eof_python_stringio.txt |
Q:
In Python, what does getresponse() return?
import httplib
conn = httplib.HTTPConnection(head)
conn.request("HEAD",tail)
res = conn.getresponse()
I can get the res.status , which is the http status code.
What other elements can I get?
Why is it that when I do print res, it won't print the dictionary? ... | In Python, what does getresponse() return? | import httplib
conn = httplib.HTTPConnection(head)
conn.request("HEAD",tail)
res = conn.getresponse()
I can get the res.status , which is the http status code.
What other elements can I get?
Why is it that when I do print res, it won't print the dictionary? I just want to see the keys that are in that di... | [
"You can always inspect an object using dir; that will show you which attributes it has.\n>>> import httplib\n>>> conn = httplib.HTTPConnection(\"www.google.nl\")\n>>> conn.request(\"HEAD\", \"/index.html\")\n>>> res = conn.getresponse()\n>>> dir(res)\n['__doc__', '__init__', '__module__', '_check_close', '_method'... | [
26
] | [] | [] | [
"http",
"linux",
"python",
"unix"
] | stackoverflow_0001752283_http_linux_python_unix.txt |
Q:
How to get the true URL of a file on the web. (Python)
I notice that sometimes audio files on the internet have a "fake" URL.
http://garagaeband.com/3252243
And this will 302 to the real URL:
http://garageband.com/michael_jackson4.mp3
My question is...when supplied with the fake URL, how can you get the REAL U... | How to get the true URL of a file on the web. (Python) | I notice that sometimes audio files on the internet have a "fake" URL.
http://garagaeband.com/3252243
And this will 302 to the real URL:
http://garageband.com/michael_jackson4.mp3
My question is...when supplied with the fake URL, how can you get the REAL URL from headers?
Currently, this is my code for reading the ... | [
"Use urllib.getUrl()\nedit:\nSorry, I haven't done this in a while: \nimport urllib\nurllib.urlopen(url).geturl()\n\nFor example:\n>>> f = urllib2.urlopen(\"http://tinyurl.com/oex2e\")\n>>> f.geturl()\n'http://www.amazon.com/All-Creatures-Great-Small-Collection/dp/B00006G8FI'\n>>> \n\n",
"Mark Pilgrim advises to... | [
9,
2,
0,
0
] | [] | [] | [
"http",
"http_headers",
"linux",
"python",
"unix"
] | stackoverflow_0001752317_http_http_headers_linux_python_unix.txt |
Q:
A dictionary with values that are dictionaries: trying to sum across those keys in python
Data structure is a dictionary, each value is another dictionary, like:
>>> from lib import schedule
>>> schedule = schedule.Schedule()
>>> game = schedule.games[0]
>>> game.home
<lib.schedule.Team instance at 0x9d97c6c>
>>> ... | A dictionary with values that are dictionaries: trying to sum across those keys in python | Data structure is a dictionary, each value is another dictionary, like:
>>> from lib import schedule
>>> schedule = schedule.Schedule()
>>> game = schedule.games[0]
>>> game.home
<lib.schedule.Team instance at 0x9d97c6c>
>>> game.home.lineup
{'guerv001': {'HR': 392, '1B': 1297}, 'kendh001': {'HR': 12, '1B': 201}, 'ande... | [
"You can use a generator expression:\ndef total(category):\n return sum(value.get(category, 0) for value in game.home.lineup.values())\n\n>>> total('HR')\n1104\n\nI used dict.get to make the default 0 if the category is missing from any dictionary.\nThe self version:\ndef total(self, category):\n return sum(v... | [
4,
1,
0
] | [] | [] | [
"dictionary",
"hash",
"python"
] | stackoverflow_0001752730_dictionary_hash_python.txt |
Q:
python paste using global egg instead of local one
I'm using Paste to run a Pylons application. Is there a way to specify in my paste config file to use the egg from the current directory (the same dir as the config file) instead of looking in global site-packages?
For example, right now the config file has:
[app... | python paste using global egg instead of local one | I'm using Paste to run a Pylons application. Is there a way to specify in my paste config file to use the egg from the current directory (the same dir as the config file) instead of looking in global site-packages?
For example, right now the config file has:
[app:main]
use = egg:example
This definitely looks to site-... | [
"Read this similar question, at least one of the answers should help you: Making Python Use Code in My Directory (not that in /usr/...)\nUPDATE: You could rename the local module to something slightly different, like example_local.\n",
"One way to use several versions of python package on the same system is virt... | [
1,
1
] | [] | [] | [
"paste",
"paster",
"pylons",
"python"
] | stackoverflow_0001751959_paste_paster_pylons_python.txt |
Q:
BeautifulSoup - easy way to to obtain HTML-free contents
I'm using this code to find all interesting links in a page:
soup.findAll('a', href=re.compile('^notizia.php\?idn=\d+'))
And it does its job pretty well. Unfortunately inside that a tag there are a lot of nested tags, like font, b and different things... I... | BeautifulSoup - easy way to to obtain HTML-free contents | I'm using this code to find all interesting links in a page:
soup.findAll('a', href=re.compile('^notizia.php\?idn=\d+'))
And it does its job pretty well. Unfortunately inside that a tag there are a lot of nested tags, like font, b and different things... I'd like to get just the text content, without any other html t... | [
"I've used this:\ndef textOf(soup):\n return u''.join(soup.findAll(text=True))\n\nSo...\ntexts = [textOf(n) for n in soup.findAll('a', href=re.compile('^notizia.php\\?idn=\\d+'))]\n\n",
"Interested in a pyparsing take on the problem?\nfrom pyparsing import makeHTMLTags, SkipTo, anyOpenTag, anyCloseTag, ParseEx... | [
13,
2
] | [] | [] | [
"beautifulsoup",
"html_content_extraction",
"html_parsing",
"python"
] | stackoverflow_0001752662_beautifulsoup_html_content_extraction_html_parsing_python.txt |
Q:
Is there a better way to get a named series of constants (enumeration) in Python?
Just looking at ways of getting named constants in python.
class constant_list:
(A_CONSTANT, B_CONSTANT, C_CONSTANT) = range(3)
Then of course you can refer to it like so:
constant_list.A_CONSTANT
I suppose you could use a di... | Is there a better way to get a named series of constants (enumeration) in Python? | Just looking at ways of getting named constants in python.
class constant_list:
(A_CONSTANT, B_CONSTANT, C_CONSTANT) = range(3)
Then of course you can refer to it like so:
constant_list.A_CONSTANT
I suppose you could use a dictionary, using strings:
constant_dic = {
"A_CONSTANT" : 1,
"B_CONSTANT" : 2,... | [
"For 2.3 or after:\nclass Enumerate(object):\n def __init__(self, names):\n for number, name in enumerate(names.split()):\n setattr(self, name, number)\n\nTo use:\n codes = Enumerate('FOO BAR BAZ')\n\ncodes.BAZ will be 2 and so on. \nIf you only have 2.2, precede this with:\n from __future__ import generat... | [
19,
2,
2,
2,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0000196876_python.txt |
Q:
How do I make a simple DNS server listening two ports simultaneously in python
I'm trying to build a DNS server in python. It must listen two ports (8007 - client, 8008 - admin). The client only send an URL and receives the respective IP. The admin has permissions to change the DNS table (add, remove,.. doesn't ma... | How do I make a simple DNS server listening two ports simultaneously in python | I'm trying to build a DNS server in python. It must listen two ports (8007 - client, 8008 - admin). The client only send an URL and receives the respective IP. The admin has permissions to change the DNS table (add, remove,.. doesn't matter to this right now).
So my question is: how do I implement the server listening ... | [
"No need to use threads.\nUse twisted.\nTwistedNames has support out of the box for a dns server. You can customize it as needed or read its source as base when you build yours.\n",
"You can use non-blocking sockets, and use the select call to read from the socket. This Sockets Programming HOWTO for Python articl... | [
5,
0
] | [] | [] | [
"dns",
"listen",
"ports",
"python"
] | stackoverflow_0001752902_dns_listen_ports_python.txt |
Q:
Import C++ classes in python?
so.. let's say i have this C function:
PyObject* Foo(PyObject* pSelf, PyObject* pArgs)
{
MessageBox(NULL, "Foo was called!", "Info", MB_OK);
return PyInt_FromLong(0);
}
and then, I have to do this:
static PyMethodDef Methods[] =
{
{"Foo", Foo, METH_NOARGS, "Dummy functio... | Import C++ classes in python? | so.. let's say i have this C function:
PyObject* Foo(PyObject* pSelf, PyObject* pArgs)
{
MessageBox(NULL, "Foo was called!", "Info", MB_OK);
return PyInt_FromLong(0);
}
and then, I have to do this:
static PyMethodDef Methods[] =
{
{"Foo", Foo, METH_NOARGS, "Dummy function"},
{NULL, NULL, 0, NULL}
};
P... | [
"boost.python enables you to do that very effectively.\n",
"SWIG would work pretty well, too.\n",
"Take a look at boost python page. Search for 'free function'.\n",
"Cython has the best C++ wrapping I have found, even though it is a bit more verbose than SWIG and it is a bit of a mindset to get into. It's ea... | [
5,
2,
1,
0
] | [] | [] | [
"c++",
"python"
] | stackoverflow_0001750517_c++_python.txt |
Q:
Python optparse Values Instance
How can I take the opt result of
opt, args = parser.parse_args()
and place it in a dict? Python calls opt a "Values Instance" and I can't find any way to turn a Values Instance into a list or dict. One can't copy items from opt in this way,
for i in opt:
myDict[i] = opt[i]
ins... | Python optparse Values Instance | How can I take the opt result of
opt, args = parser.parse_args()
and place it in a dict? Python calls opt a "Values Instance" and I can't find any way to turn a Values Instance into a list or dict. One can't copy items from opt in this way,
for i in opt:
myDict[i] = opt[i]
instead, its a clumsy,
myDict[parm1] = o... | [
"options, args = parser.parse_args()\noption_dict = vars(options)\n\n(Source is this python-ideas post.)\n"
] | [
93
] | [] | [] | [
"dictionary",
"optparse",
"python"
] | stackoverflow_0001753460_dictionary_optparse_python.txt |
Q:
Python functions can be given new attributes from outside the scope?
I didn't know you could do this:
def tom():
print "tom's locals: ", locals()
def dick(z):
print "z.__name__ = ", z.__name__
z.guest = "Harry"
print "z.guest = ", z.guest
print "dick's locals: ", locals()
tom() #... | Python functions can be given new attributes from outside the scope? | I didn't know you could do this:
def tom():
print "tom's locals: ", locals()
def dick(z):
print "z.__name__ = ", z.__name__
z.guest = "Harry"
print "z.guest = ", z.guest
print "dick's locals: ", locals()
tom() #>>> tom's locals: {}
#print tom.guest #AttributeError: 'function' obje... | [
"I think you might be conflating the concepts of local variables and function attributes. For more information on Python function attributes, see the SO question Python function attributes - uses and abuses.\n",
"@behindthefall, the motivation to give function objects generic assignable attributes (they didn't us... | [
4,
4,
3,
1,
1,
0,
0
] | [] | [] | [
"attributes",
"namespaces",
"python",
"scope"
] | stackoverflow_0001753232_attributes_namespaces_python_scope.txt |
Q:
Can this breadth-first search be made faster?
I have a data set which is a large unweighted cyclic graph The cycles occur in loops of about 5-6 paths. It consists of about 8000 nodes and each node has from 1-6 (usually about 4-5) connections. I'm doing single pair shortest path calculations and have implemented th... | Can this breadth-first search be made faster? | I have a data set which is a large unweighted cyclic graph The cycles occur in loops of about 5-6 paths. It consists of about 8000 nodes and each node has from 1-6 (usually about 4-5) connections. I'm doing single pair shortest path calculations and have implemented the following code to do a breadth-first search.
from... | [
"Well, given the upvotes on the comment, I'll make it an answer now.\nThe SQL in the tight loop is definitely slowing you down. I don't care how fast the call is. Think about it -- you're asking for a query to be parsed, a lookup to be run -- as fast as that is, it's still in a tight loop. What does your data set l... | [
11,
1,
0,
0
] | [] | [] | [
"algorithm",
"breadth_first_search",
"computer_science",
"python"
] | stackoverflow_0001753257_algorithm_breadth_first_search_computer_science_python.txt |
Q:
How can I append data to a text file with a line break using Python?
I've just been asked to come up with a script to find files with a certain filename length. I've decided to try out Python for the first time for this task as I've always wanted to learn it.
I've got the script to find the files and append them t... | How can I append data to a text file with a line break using Python? | I've just been asked to come up with a script to find files with a certain filename length. I've decided to try out Python for the first time for this task as I've always wanted to learn it.
I've got the script to find the files and append them to a text file but it does not write a line break for each new entry. Is th... | [
"You just need to explicitly append a '\\n' each time you want a line break -- if you're appending to the output file in text mode, this will expand to the proper line separation where needed (e.g. Windows). (You could use os.linesep instead, if you had to output in binary mode for some reason, but that's a pretty... | [
10,
0
] | [] | [] | [
"python"
] | stackoverflow_0001752019_python.txt |
Q:
What conditions cause Tokyo Cabinet to block
I'm using Tokyo Cabinet with the tc module in python. I store my data in the TDB format. I expected the table to block only for the duration of a write. Unfortunately, I see that when the file is open with in the "writer mode", other processes cannot read from it. Is th... | What conditions cause Tokyo Cabinet to block | I'm using Tokyo Cabinet with the tc module in python. I store my data in the TDB format. I expected the table to block only for the duration of a write. Unfortunately, I see that when the file is open with in the "writer mode", other processes cannot read from it. Is that a standard behaviour, wrappers problem, or am I... | [
"According to specification:\n\nTokyo Cabinet provides two modes to\n connect to a database: \"reader\" and\n \"writer\". A reader can perform\n retrieving but neither storing nor\n deleting. A writer can perform all\n access methods. Exclusion control\n between processes is performed when\n connecting to a ... | [
5
] | [] | [] | [
"blocking",
"python",
"tokyo_cabinet"
] | stackoverflow_0001752454_blocking_python_tokyo_cabinet.txt |
Q:
DOM related question and problem
these day im making python script related with DOM.
problem is these day many website structure is very complicate .
what is best method to check DOM structure and path..
i mean...following is some example.
what is best method to check can extract such like following info quickly?... | DOM related question and problem | these day im making python script related with DOM.
problem is these day many website structure is very complicate .
what is best method to check DOM structure and path..
i mean...following is some example.
what is best method to check can extract such like following info quickly?
before i was spent much time to extra... | [
"I would hope that you've read Python's implementation of the DOM and here's a good tutorial. Alternatively, if you know javascript jQuery makes it incredibly easy to DOM parse and manipulate the DOM, as seen here. Now if you're just trying to get someone to parse it for you, good luck. \n"
] | [
2
] | [] | [] | [
"dom",
"python"
] | stackoverflow_0001754675_dom_python.txt |
Q:
Get Intervals Between Two Times
A User will specify a time interval of n secs/mins/hours and then two times (start / stop).
I need to be able to take this interval, and then step through the start and stop times, in order to get a list of these times. Then after this, I will perform a database look up via a table.... | Get Intervals Between Two Times | A User will specify a time interval of n secs/mins/hours and then two times (start / stop).
I need to be able to take this interval, and then step through the start and stop times, in order to get a list of these times. Then after this, I will perform a database look up via a table.objects.filter, in order to retrieve ... | [
"Are you looking for something like this? (pseudo code)\nt = start \nwhile t != stop: \n t += interval \n table.objects.filter(t) \n\n",
"it fits nicely as a generator, too:\ndef timeseq(start,stop,interval):\n while start <= stop:\n yield start\n start += interval\n\nused as:\nfor t in tim... | [
4,
4,
1
] | [] | [] | [
"datetime",
"django",
"python"
] | stackoverflow_0001754781_datetime_django_python.txt |
Q:
How to kill headless X server started via Python?
I want to get screenshots of a webpage in Python. For this I am using http://github.com/AdamN/python-webkit2png/ .
newArgs = ["xvfb-run", "--server-args=-screen 0, 640x480x24", sys.argv[0]]
for i in range(1, len(sys.argv)):
if sys.argv[i] not in ["-... | How to kill headless X server started via Python? | I want to get screenshots of a webpage in Python. For this I am using http://github.com/AdamN/python-webkit2png/ .
newArgs = ["xvfb-run", "--server-args=-screen 0, 640x480x24", sys.argv[0]]
for i in range(1, len(sys.argv)):
if sys.argv[i] not in ["-x", "--xvfb"]:
newArgs.append(sys.argv[i])
... | [
"The documentation for os.execvp states:\n\nThese functions all execute a new\n program, replacing the current\n process; they do not return. [..]\n\nSo after calling os.execvp no other statement in the program will be executed. You may want to use subprocess.Popen instead:\n\nThe subprocess module allows you to... | [
5
] | [] | [] | [
"python",
"screenshot",
"xserver"
] | stackoverflow_0001747022_python_screenshot_xserver.txt |
Q:
How do I get stdout from tcl into a python string variable when using tkinter?
I have the following python code...
import Tkinter
root = Tkinter.Tk()
root.tk.eval('puts {printed by tcl}')
It prints "printed by tcl" to the screen. How can I capture what the tcl interpreter prints to the screen into a python stri... | How do I get stdout from tcl into a python string variable when using tkinter? | I have the following python code...
import Tkinter
root = Tkinter.Tk()
root.tk.eval('puts {printed by tcl}')
It prints "printed by tcl" to the screen. How can I capture what the tcl interpreter prints to the screen into a python string.
This is a simplified example of what I am doing. I have an automation system wri... | [
"If the code you are running prints to screen and you're calling it with root.tk.eval() you can't capture that. However, You can redefine what \"puts\" does in the tcl code and have it do whatever you want. This is part of the beauty of Tcl -- there are no reserved words. \nSimply create a proc named \"puts\" in th... | [
5
] | [] | [] | [
"python",
"tcl",
"tkinter"
] | stackoverflow_0001755415_python_tcl_tkinter.txt |
Q:
Converting RE code from PHP to Python
I have done a simple program in PHP, now need to convert this into Python:
$string="Google 1600 Amphitheatre Parkway Mountain View, CA 94043 phone";
preg_match_all('/[0-9]+.{10,25}[^0-9]*[0-9]{5,6}+\s/',$string,$matches);
print_r($matches);
A:
import re
for x in re.findall('... | Converting RE code from PHP to Python | I have done a simple program in PHP, now need to convert this into Python:
$string="Google 1600 Amphitheatre Parkway Mountain View, CA 94043 phone";
preg_match_all('/[0-9]+.{10,25}[^0-9]*[0-9]{5,6}+\s/',$string,$matches);
print_r($matches);
| [
"import re\nfor x in re.findall('[0-9]+.{10,25}[^0-9]*[0-9]{5,6}\\s',STRING):print x\n\nwill be ok for you?\n",
"In python, you must use the \"re\" module to do that. Unlike in PHP, you don't need to place delimitors, so strip the \"/\" you have at the begining and the end of the pattern.\nThe Python idiom would ... | [
1,
0
] | [
"import re\nstring = \"Input values\"\nmatch = re.match('/[0-9]+.{10,25}[^0-9]*[0-9]{5,6}\\s/', s)\nprint match\n\nthis should be what you're looking for, if the RegEx is right.\n"
] | [
-1
] | [
"php",
"python",
"regex"
] | stackoverflow_0001755706_php_python_regex.txt |
Q:
lazy load or early load for python?
We've got the following code sample:
big_static_data = {
"key1" : {
"subkey1" : "subvalue1",
...
},
"key2" :
...
}
class StaticDataEarlyLoad:
def __init__(self):
self.static_data = big_static_data
# other init
def handle_use_id(self... | lazy load or early load for python? | We've got the following code sample:
big_static_data = {
"key1" : {
"subkey1" : "subvalue1",
...
},
"key2" :
...
}
class StaticDataEarlyLoad:
def __init__(self):
self.static_data = big_static_data
# other init
def handle_use_id(self, id):
return complex_handle(self... | [
"In your example, StaticDataLazyLoad (once the syntax for init is correct) wont make a big difference.\n\"big_static_data\" is initialized (\"loaded\") when the module is imported. It will immediately require some memory, no matter whether an instance of your classes is created or not.\nAn instance of StaticDataEar... | [
3,
3
] | [] | [] | [
"performance",
"python"
] | stackoverflow_0001756276_performance_python.txt |
Q:
Custom traversal and page templates
Using Marius Gedminas's excellent blog post, I have created a custom traverser for a folder in my site.
This allows me to show: http://foo.com/folder/random_id
Instead of: http://foo.com/folder/object.html?id=random_id
The configuration side works great, I can catch the random_i... | Custom traversal and page templates | Using Marius Gedminas's excellent blog post, I have created a custom traverser for a folder in my site.
This allows me to show: http://foo.com/folder/random_id
Instead of: http://foo.com/folder/object.html?id=random_id
The configuration side works great, I can catch the random_ids and search through my messages for the... | [
"It would be easier to answer your question if you showed what your custom traverser is doing.\nEssentially, you want something like this:\ndef publishTraverse(self, request, name):\n if name in self.context:\n return MyMessageView(self.context[name], request)\n\n # fall back to views such as index.htm... | [
1,
0,
0
] | [] | [] | [
"python",
"zope",
"zpt"
] | stackoverflow_0001752090_python_zope_zpt.txt |
Q:
Problem with db.get in Google App Engine
When I run the following code:
query = datastore.Food_Item.all()
results = query.fetch(1)
foodA = results[0]
foodB = db.get(foodA.key())
I would expect foodA and foodB to be the same type. However, I see that the foodA is of type "model.datastore.Food_Item"... | Problem with db.get in Google App Engine | When I run the following code:
query = datastore.Food_Item.all()
results = query.fetch(1)
foodA = results[0]
foodB = db.get(foodA.key())
I would expect foodA and foodB to be the same type. However, I see that the foodA is of type "model.datastore.Food_Item" and foodB is of type "datastore.Food_Item". W... | [
"It seems likely you're importing the same module (model.datastore) by different names in different places - for example, by using a relative import inside the model package. db.get returns whichever name it saw when the module was first imported, while your own code (the query) returns whatever you explicitly spec... | [
4
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0001756059_google_app_engine_python.txt |
Q:
Nonblocking webserver on .Net for Comet applications
I am trying to implement a Comet style (e.g. chat) application using IronPython. While I don't need to scale to twitter like dimensions, it is vital that the response time is lightening fast. All the possibilities in Python (Twisted, Tornado, Magnum-Py) do not... | Nonblocking webserver on .Net for Comet applications | I am trying to implement a Comet style (e.g. chat) application using IronPython. While I don't need to scale to twitter like dimensions, it is vital that the response time is lightening fast. All the possibilities in Python (Twisted, Tornado, Magnum-Py) do not work with IronPython, often because of epoll support.
Is ... | [
"There sure is. Check out WebSync, a full comet solution for .NET/IIS. To my knowledge, it's the only full implementation of comet for .NET available today. You can use the on-demand version for free (up to a limit), or pick up the server version to host it yourself. It's pretty inexpensive too, no runtime fees, et... | [
2
] | [] | [] | [
".net",
"comet",
"ironpython",
"python"
] | stackoverflow_0001730986_.net_comet_ironpython_python.txt |
Q:
Django development server CPU intensive - how to analyse?
I'm noticing that my django development server (version 1.1.1) on my local windows7 machine is using a lot of CPU (~30%, according to task manager's python.exe entry), even in idle state, i.e. no request coming in/going out. Is there an established way of a... | Django development server CPU intensive - how to analyse? | I'm noticing that my django development server (version 1.1.1) on my local windows7 machine is using a lot of CPU (~30%, according to task manager's python.exe entry), even in idle state, i.e. no request coming in/going out. Is there an established way of analysing what might be responsible for this?
Thanks!
Martin
| [
"FWIW, you should do the profiling, but when you do I'll bet you find that the answer is \"polling for changes to your files so it can auto-reload.\" You might do a quick test with \"python manage.py runserver --noreload\" and see how that affects the CPU usage.\n",
"Hit Control-C and crash the process. It will p... | [
19,
4,
3,
1
] | [] | [] | [
"cpu",
"django",
"python"
] | stackoverflow_0001750676_cpu_django_python.txt |
Q:
How to specify a baseDN when connecting to LDAP via python?
I want to connect to a ldap server with python-ldap using a specific baseDN.
import ldap
baseDN="ou=unit,o=org.c=xx" # doesn't work
#baseDN="" # works
host="ldaps://test.org.xx:636"
userDN="cn=proxyhlrb,ou=services,o=org,c=xx"
passwd="secret"
server=ld... | How to specify a baseDN when connecting to LDAP via python? | I want to connect to a ldap server with python-ldap using a specific baseDN.
import ldap
baseDN="ou=unit,o=org.c=xx" # doesn't work
#baseDN="" # works
host="ldaps://test.org.xx:636"
userDN="cn=proxyhlrb,ou=services,o=org,c=xx"
passwd="secret"
server=ldap.initialize(host+"/"+baseDN)
server.bind_s(userDN,passwd,ldap.... | [
"I think this resource would be interesting for you. It nicely explains how to combine LDAP with Python.\nhttp://www.packtpub.com/article/python-ldap-applications-ldap-opearations\nEdit: is the port you are using correct? In PHP, developers mainly use port 389 for LDAP connects, bindings and queries.\n"
] | [
0
] | [] | [] | [
"connection",
"ldap",
"python"
] | stackoverflow_0001756977_connection_ldap_python.txt |
Q:
Python LEPL LineAwareConfiguration trouble
I'm new to using python's LEPL, and it looks great. However, I'm trying to use the LineAwareConfiguration to easily handle a grammar in which whitespace matters, and I'm running into some serious issues. Namely, this code works:
from lepl import *
broken = Token(r'.')
par... | Python LEPL LineAwareConfiguration trouble | I'm new to using python's LEPL, and it looks great. However, I'm trying to use the LineAwareConfiguration to easily handle a grammar in which whitespace matters, and I'm running into some serious issues. Namely, this code works:
from lepl import *
broken = Token(r'.')
parser = broken[:].string_parser()
While this code... | [
"yeah, sorry about this. it's at least partly related to the difference between normal (byte) and unicode strings in python 2.6 (the line aware code is new this last release). i will get a fixed release out as soon as i can - hopefully by the weekend. if you keep watching the mailing list there may be a point be... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0001752645_python.txt |
Q:
Checking files retrieved by Twisted's FTPClient.retrieveFile method for completeness
I'm writing a custom ftp client to act as a gatekeeper for incoming multimedia content from subcontractors hired by one of our partners. I chose twisted because it allows me to parse the file contents before writing the files to d... | Checking files retrieved by Twisted's FTPClient.retrieveFile method for completeness | I'm writing a custom ftp client to act as a gatekeeper for incoming multimedia content from subcontractors hired by one of our partners. I chose twisted because it allows me to parse the file contents before writing the files to disk locally, and I've been looking for occasion to explore twisted anyway. I'm using 'twis... | [
"There are a couple unit tests for behavior in this area.\ntwisted.test.test_ftp.FTPClientTestCase.test_failedRETR is the most directly relevant one. It covers the case where the control and data connections are lost while a file transfer is in progress.\nIt seems to me that test coverage in this area could be sig... | [
4
] | [] | [] | [
"client",
"ftp",
"python",
"twisted"
] | stackoverflow_0001757276_client_ftp_python_twisted.txt |
Q:
Gracefully convert .rar to .zip using Python
I'm currently making system call to "unrar and zip" commands. It interrupts and requires me to enter password while encounter password propected archives.
Is it possible to let it run and return a "unsuccessful" value to main program on any error or password prompt?
Can... | Gracefully convert .rar to .zip using Python | I'm currently making system call to "unrar and zip" commands. It interrupts and requires me to enter password while encounter password propected archives.
Is it possible to let it run and return a "unsuccessful" value to main program on any error or password prompt?
Can we natively use rarfile and zipfile library to do... | [
"I think it's very difficult to do the task without using temporary files. If you are converting very large files you need to use temporary space in disk.\nYou can use the PyUnRAR2 library, it will let you examine and extract the files of a RAR archive. You can extract the files to a temporary folder created with t... | [
2,
0
] | [] | [] | [
"compression",
"python",
"rar",
"zip"
] | stackoverflow_0001756109_compression_python_rar_zip.txt |
Q:
How to append a reading to a python list?
i am using GM862 module and i want to write the cordinates as it is in a file "cordinates.txt" but i get some error, this is the code i wrote:
import MDM
cordlist = []
f = open("cordinates.txt", 'w')
def AcquiredPosition():
res = MDM.send('AT$GPSACP\r', 0)
res = MDM... | How to append a reading to a python list? | i am using GM862 module and i want to write the cordinates as it is in a file "cordinates.txt" but i get some error, this is the code i wrote:
import MDM
cordlist = []
f = open("cordinates.txt", 'w')
def AcquiredPosition():
res = MDM.send('AT$GPSACP\r', 0)
res = MDM.receive(30)
if(res.find('OK') != -1):
tm... | [
"You are appending to your list and then writing the full list to the file each time through the loop.\nYou need to clear down the list in each pass through the loop.\nPut cordlist = [] as the first line under while(1)\n",
"Why not open the file in append mode ('a' instead of 'w') and just writelines to that?\n",... | [
3,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0001758068_python.txt |
Q:
Twisted: source IP address for outbound connections
I'm in the process of implementing a service -- written in Python with the Twisted framework, running on Debian GNU/Linux -- that checks the availability of SIP servers. For this I use the OPTIONS method (a SIP protocol feature), as this seems to be a commonplac... | Twisted: source IP address for outbound connections | I'm in the process of implementing a service -- written in Python with the Twisted framework, running on Debian GNU/Linux -- that checks the availability of SIP servers. For this I use the OPTIONS method (a SIP protocol feature), as this seems to be a commonplace practice. In order to construct correct and RFC compli... | [
"For the sake of completeness I answer my own question:\nMake sure you use connect() on the transport before trying to determine the host's source IP address. The following excerpt shows the relevant part of a protocol implementation:\nclass FooBarProtocol(protocol.DatagramProtocol):\n def startProtocol(self):\... | [
8,
0,
0
] | [] | [] | [
"linux",
"network_programming",
"networking",
"python",
"twisted"
] | stackoverflow_0001622454_linux_network_programming_networking_python_twisted.txt |
Q:
Google App Engine - design considerations about cron tasks
I'm developing software using the Google App Engine.
I have some considerations about the optimal design regarding the following issue: I need to create and save snapshots of some entities at regular intervals.
In the conventional relational db world, I w... | Google App Engine - design considerations about cron tasks | I'm developing software using the Google App Engine.
I have some considerations about the optimal design regarding the following issue: I need to create and save snapshots of some entities at regular intervals.
In the conventional relational db world, I would create db jobs which would insert new summary records.
For ... | [
"I think you'll find that snapshotting every user's state every hour isn't something that will scale well no matter what your framework. A more ordinary environment will disguise this by letting you have longer running tasks, but you'll still reach the point where it's not practical to take a snapshot of every user... | [
3,
2,
0
] | [] | [] | [
"cron",
"database",
"google_app_engine",
"python"
] | stackoverflow_0000814896_cron_database_google_app_engine_python.txt |
Q:
How to read line (from a file) and then append + print in python?
for line in file:
print line
In the code above when I change it to:
for line in file:
print line + " just a string"
This only appends "just a string" to the last line
PS: Python newbie
A:
Iterating over a file includes the line endings,... | How to read line (from a file) and then append + print in python? | for line in file:
print line
In the code above when I change it to:
for line in file:
print line + " just a string"
This only appends "just a string" to the last line
PS: Python newbie
| [
"Iterating over a file includes the line endings, so just remove them:\nfor line in file:\n print line.rstrip(\"\\n\"), \"something\"\n\nNote that print will append its own newline, so even without appending \"something\" you'd want to do this (or use sys.stdout.write instead of print). You may also use line.rstr... | [
5,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0001759193_python.txt |
Q:
What is the right way to organize python unittests into suites?
I have some test case classes organized in directories
foo_tests
foo_tests1.py
foo_tests2.py
...
bar_tests
bar_tests1.py
...
The test cases look like:
foo_tests1.py:
import unittest
class FooTestsOne(unittest.TestCase):
def te... | What is the right way to organize python unittests into suites? | I have some test case classes organized in directories
foo_tests
foo_tests1.py
foo_tests2.py
...
bar_tests
bar_tests1.py
...
The test cases look like:
foo_tests1.py:
import unittest
class FooTestsOne(unittest.TestCase):
def test_1():
assert(1=1)
def test_2():
#...
How do you ... | [
"Tests are not supposed to run during import. Maybe you have unittest.main() at the bottom of foo_test1.py?\nYour script should work, except that \nresult = unittest.TextTestRunner(verbosity=2).run(suite())\n\nshould be \nresult = unittest.TextTestRunner(verbosity=2).run(suite)\n\n"
] | [
3
] | [] | [] | [
"python",
"unit_testing"
] | stackoverflow_0001759128_python_unit_testing.txt |
Q:
How to generate a graphic on the fly with cherrypy
I am developing a small web application using cherrypy and I would like to generate some graphs from the data stored in a database. The web pages with tables are easy and I plan to use matplotlib for the graphs themselves, but how do I set the content-type for th... | How to generate a graphic on the fly with cherrypy | I am developing a small web application using cherrypy and I would like to generate some graphs from the data stored in a database. The web pages with tables are easy and I plan to use matplotlib for the graphs themselves, but how do I set the content-type for the method so they return images instead of plain text? ... | [
"You need to set the content-type header of the response manually, either in the app config, using the response.headers tool, or in the handler method.\nIn the handler method, there are two options covered on the MimeDecorator page of the Cherrypy Tools wiki.\nIn the method body:\ndef hello(self):\n cherrypy.res... | [
6,
0
] | [] | [] | [
"cherrypy",
"dynamic",
"graph",
"python"
] | stackoverflow_0001759608_cherrypy_dynamic_graph_python.txt |
Q:
python prompt with a bash like interface
I am using the python prompt to practice some regular expressions. I was wondering if there was a way to use the up/down arrows (like bash) to cycle through the old commands typed. I know its possible since it works on python on cygwin/windows.
thanks
A:
Use the rlcomplet... | python prompt with a bash like interface | I am using the python prompt to practice some regular expressions. I was wondering if there was a way to use the up/down arrows (like bash) to cycle through the old commands typed. I know its possible since it works on python on cygwin/windows.
thanks
| [
"Use the rlcompleter module to get both readline and completion.\nSample PYTHONSTARTUP code:\ntry:\n import readline\nexcept ImportError:\n print \"Module readline unavailable.\"\nelse:\n import rlcompleter\n readline.parse_and_bind(\"tab: complete\")\n\nSample .bashrc code to set your python startup file:\nif ... | [
7,
7,
6,
6
] | [] | [] | [
"python"
] | stackoverflow_0001758819_python.txt |
Q:
Python: Issue reading data lines multiple times from a file
I am trying to make a Python2.6 script on a Win32 that will read all the text files stored in a directory and print only the lines containing actual data. A sample file -
Set : 1
Date: 10212009
12 34 56
25 67 90
End Set
+++++++++
Set: 2
Date: 1022200... | Python: Issue reading data lines multiple times from a file | I am trying to make a Python2.6 script on a Win32 that will read all the text files stored in a directory and print only the lines containing actual data. A sample file -
Set : 1
Date: 10212009
12 34 56
25 67 90
End Set
+++++++++
Set: 2
Date: 10222009
34 56 89
25 67 89
End Set
In the above example file, I want... | [
"in_data = False\nfor line in open( 'data.txt' ):\n if line.startswith( 'Date:' ):\n in_data = True\n elif line.startswith( 'End Set' ):\n in_data = False\n elif in_data:\n print line.rstrip()\n\nJust put something like that inside a loop over your files (i.e. os.walk) and you should b... | [
2,
2,
2,
1,
1,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0001759320_python.txt |
Q:
How can I run a Python program over telnet?
How can I run a Python program so it outputs its STDOUT and inputs its STDIN to/from a remote telnet client?
All the program does is print out text then wait for raw_input(), repeatedly. I want a remote user to use it without needing shell access. It can be single thread... | How can I run a Python program over telnet? | How can I run a Python program so it outputs its STDOUT and inputs its STDIN to/from a remote telnet client?
All the program does is print out text then wait for raw_input(), repeatedly. I want a remote user to use it without needing shell access. It can be single threaded/single user.
| [
"On a Unix system, you can use inetd for this. It will take care of opening the network connection for you, so your program will work as-is.\n",
"Make the Python script into the shell for that user. (Or if that doesn't work, wrap it up in bash script or even a executable).\n(You might have to put it in /etc/shel... | [
10,
5,
4,
0
] | [] | [] | [
"python",
"telnet"
] | stackoverflow_0001758276_python_telnet.txt |
Q:
How to merge duplicates in 2D python arrays
I have a set of data similar to this:
# Start_Time End_Time Call_Type Info
1 13:14:37.236 13:14:53.700 Ping1 RTT(Avr):160ms
2 13:14:58.955 13:15:29.984 Ping2 RTT(Avr):40ms
3 13:19:12.754 13:19:14.757 Ping3_1 RTT(Avr):620ms
3 13:19:12.754... | How to merge duplicates in 2D python arrays | I have a set of data similar to this:
# Start_Time End_Time Call_Type Info
1 13:14:37.236 13:14:53.700 Ping1 RTT(Avr):160ms
2 13:14:58.955 13:15:29.984 Ping2 RTT(Avr):40ms
3 13:19:12.754 13:19:14.757 Ping3_1 RTT(Avr):620ms
3 13:19:12.754 Ping3_2 RTT(Avr):210ms
4 13:1... | [
"Assuming your duplicates are adjacent (as they're shown on your question), itertools.groupby is the ideal way to identify them as duplicates (with a little help from operator.itemgetter to extract the \"key\" defining identity. Assuming you have a list of objects (the pings) with attributes such as .start and .en... | [
1,
0,
0
] | [] | [] | [
"arrays",
"duplicates",
"merge",
"python"
] | stackoverflow_0001759369_arrays_duplicates_merge_python.txt |
Q:
extract the number and name of python method arguments
How can I return the arguments of a function in a different module
#Module: functionss.py
def simple(a, b, c):
print "does something"
#Module: extract.py
#load the called module and function
def get_args(module_name, function_name):
modFile, modPath, ... | extract the number and name of python method arguments | How can I return the arguments of a function in a different module
#Module: functionss.py
def simple(a, b, c):
print "does something"
#Module: extract.py
#load the called module and function
def get_args(module_name, function_name):
modFile, modPath, modDesc = imp.find_module(module_name)
mod = imp.load_m... | [
"Use inspect.getargspec for the \"heavy lifting\" (introspecting a function).\nUse __import__ to import a module (given its module name -- \"functions.py\" is a terrible way to specify a module name;-).\nUse getattr(moduleobject, functionname) to get the function object given module object and function name.\n"
] | [
1
] | [] | [] | [
"arguments",
"function",
"python"
] | stackoverflow_0001760945_arguments_function_python.txt |
Q:
sum of two numbers coming from the command line
I know it's a very basic program but I am getting an error of list out of range. Here is the program to take two numbers as command-line arguments (while invoking the script) and display sum (using python):
import sys
a= sys.argv[1]
b= sys.argv[2]
sum=str( a+b)
print... | sum of two numbers coming from the command line | I know it's a very basic program but I am getting an error of list out of range. Here is the program to take two numbers as command-line arguments (while invoking the script) and display sum (using python):
import sys
a= sys.argv[1]
b= sys.argv[2]
sum=str( a+b)
print " sum is", sum
| [
"You should do this:\nimport sys\na, b = sys.argv[1:2]\nsumm = int(a) + int(b)\nprint \"sum is\", summ\n\nThere is no need for str() when printing an integer. But you should use int() if you want to add a and b as integers.\n",
"The error list index out of range means that you are trying to access a list item tha... | [
5,
3,
3,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0001356348_python.txt |
Q:
Shorten Python imports?
I'm working on a Django project. Let's call it myproject. Now my code is littered with myproject.folder.file.function. Is there anyway I can remove the need to prefix all my imports and such with myproject.? What if I want to rename my project later? It kind of annoys me that I need to pref... | Shorten Python imports? | I'm working on a Django project. Let's call it myproject. Now my code is littered with myproject.folder.file.function. Is there anyway I can remove the need to prefix all my imports and such with myproject.? What if I want to rename my project later? It kind of annoys me that I need to prefix stuff like that when the v... | [
"from myproject.folder import file (horrible name, btw, trampling over the builtin type file, but that's another rant;-), then use file.function -- if file (gotta hate that module name;-) is still too long for you, add e.g. as fi to the from statement, and use fi.function. If you want to rename myproject to myhorr... | [
5,
4,
4
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001760963_django_python.txt |
Q:
Python: Convert string into function name; getattr or equal?
I am editing PROSS.py to work with .cif files for protein structures. Inside the existing PROSS.py, there is the following functions (I believe that's the correct name if it's not associated with any class?), just existing within the .py file:
...
def un... | Python: Convert string into function name; getattr or equal? | I am editing PROSS.py to work with .cif files for protein structures. Inside the existing PROSS.py, there is the following functions (I believe that's the correct name if it's not associated with any class?), just existing within the .py file:
...
def unpack_pdb_line(line, ATOF=_atof, ATOI=_atoi, STRIP=string.strip):
.... | [
"Usually you just use a dict and store (func_name, function) pairs:\nunpack_options = { 'unpack_pdb_line' : unpack_pdb_line,\n 'some_other' : some_other_function }\n\nunpack_function = unpack_options[options.unpack_method]\n\n",
"If you want to exploit the dictionaries (&c) that Python's already... | [
9,
4,
3,
3,
1
] | [] | [] | [
"function",
"getattr",
"python"
] | stackoverflow_0001738687_function_getattr_python.txt |
Q:
Installing Trac with Subversion 1.6
I'm trying to set up Trac on my server and have successfully installed it, compiled the bytecode and run the tracd server. The only problem is that it's not reading my SVN repository.
The error I'm receiving is:
Warning: Can't synchronize with the repository (Couldn't open Subv... | Installing Trac with Subversion 1.6 | I'm trying to set up Trac on my server and have successfully installed it, compiled the bytecode and run the tracd server. The only problem is that it's not reading my SVN repository.
The error I'm receiving is:
Warning: Can't synchronize with the repository (Couldn't open Subversion repository /data1/repos: Subversio... | [
"Is your python svn library updated? Sounds like it's stale.\n",
"you should make sure the python binding match your SVN version. \nto get the binding you can use the SVN source and compile the wrapper, the install give an overview of the process how to build that binding. \nfirst you would have to download the ... | [
3,
3,
2,
0
] | [] | [] | [
"installation",
"python",
"svn",
"trac"
] | stackoverflow_0001740165_installation_python_svn_trac.txt |
Q:
mechanize can't login python
I'm making auto-login script by use mechanize python.
Before I was used mechanize with no problem, but www.gmarket.co.kr in this site I couldn't make it .
whenever i try to login always login page was returned even with correct gmarket id , pass, i can't login and I saw some suspicious... | mechanize can't login python | I'm making auto-login script by use mechanize python.
Before I was used mechanize with no problem, but www.gmarket.co.kr in this site I couldn't make it .
whenever i try to login always login page was returned even with correct gmarket id , pass, i can't login and I saw some suspicious message
"<script language=javasc... | [
"mechanize doesn't have the ability to interact with JavaScript. Probably spidermonkey module will help you (I have no experience with it, but description is quite promising). Also you could handle such reload (e.g.Browser.reload() for this particular case) manually if it's the only site you have this problem.\nUpd... | [
1
] | [] | [] | [
"mechanize",
"python"
] | stackoverflow_0001760245_mechanize_python.txt |
Q:
Python SIP library
I need to write python application connect to trixbox that run as SIP server. But I not found any library that implement in python. I found SIP SKD at http://www.vaxvoip.com/ but it not support python. Can anyone suggest me an alternative to VaxVoip?
Thank you.
A:
There are Python bindings for... | Python SIP library | I need to write python application connect to trixbox that run as SIP server. But I not found any library that implement in python. I found SIP SKD at http://www.vaxvoip.com/ but it not support python. Can anyone suggest me an alternative to VaxVoip?
Thank you.
| [
"There are Python bindings for the PJSUA API.\n",
"Twisted supports SIP. That's really cool\n",
"You might want to have a look at Sippy. It's a B2BUA with a complete SIP stack implementation underneath (you could use just that). It's written entirely in Python, so it's pretty hackable. Sippy is implemented w... | [
19,
15,
10
] | [] | [] | [
"python",
"sip",
"trixbox",
"voip"
] | stackoverflow_0001286875_python_sip_trixbox_voip.txt |
Q:
Detach a subprocess started using python multiprocessing module
I would like to create a process using the mutliprocessing module in python but ensure it continues running after the process that created the subprocess exits.
I can get the required functionality using the subprocess module and Popen, but I want to... | Detach a subprocess started using python multiprocessing module | I would like to create a process using the mutliprocessing module in python but ensure it continues running after the process that created the subprocess exits.
I can get the required functionality using the subprocess module and Popen, but I want to run my code as a function, not as a script. The reason I want to do ... | [
"I finally got what I wanted. I appreciate any suggestions to improve the code.\ndef start_server():\n pyrodaemon = Pyro.core.Daemon()\n #setup daemon and nameserver\n #Don't want to close the pyro socket\n #Need to remove SIGTERM map so Processing doesn't kill the subprocess\n #Need to explicitly de... | [
4
] | [] | [] | [
"detach",
"multiprocessing",
"pyro",
"python",
"subprocess"
] | stackoverflow_0001757388_detach_multiprocessing_pyro_python_subprocess.txt |
Q:
How to uncheck a checkbox to stop infinite drawing in pyqt?
My problem is I want to keep rotating the scene if the checkbox is checked, and stop this rotation immediately once it is unchecked. However, "keep rotating" means an infinite loop...
So after entering the loop, the program gets kind of freezed and no lon... | How to uncheck a checkbox to stop infinite drawing in pyqt? | My problem is I want to keep rotating the scene if the checkbox is checked, and stop this rotation immediately once it is unchecked. However, "keep rotating" means an infinite loop...
So after entering the loop, the program gets kind of freezed and no longer react to my "uncheck" signal. Is there a way to interrupt thi... | [
"You must not implement this as a loop. This is defined to break the interaction of the program, as it prevents the \"main loop\" of the Qt application from running.\nPut your drawing code into an event handler (like redraw event), and use a timer to generate events at regular intervals (e.g. 10/s).\n"
] | [
1
] | [] | [] | [
"pyopengl",
"pyqt",
"python"
] | stackoverflow_0001761352_pyopengl_pyqt_python.txt |
Q:
Read password from stdin
Scenario: An interactive CLI Python program, that is in need for a password. That means also, there's no GUI solution possible.
In bash I could get a password read in without re-prompting it on screen via
read -s
Is there something similar for Python? I.e.,
password = raw_input('Password:... | Read password from stdin | Scenario: An interactive CLI Python program, that is in need for a password. That means also, there's no GUI solution possible.
In bash I could get a password read in without re-prompting it on screen via
read -s
Is there something similar for Python? I.e.,
password = raw_input('Password: ', dont_print_statement_back_... | [
">>> import getpass\n>>> pw = getpass.getpass()\n\n",
"Yes, getpass: \"Prompt the user for a password without echoing.\"\nEdit: I had not played with this module myself yet, so this is what I just cooked up (wouldn't be surprised if you find similar code all over the place, though):\nimport getpass\n\ndef login()... | [
296,
55
] | [] | [] | [
"interactive",
"passwords",
"prompt",
"python"
] | stackoverflow_0001761744_interactive_passwords_prompt_python.txt |
Q:
Numpy equivalent of MATLAB's cell array
I want to create a MATLAB-like cell array in Numpy. How can I accomplish this?
A:
Matlab cell arrays are most similar to Python lists, since they can hold any object - but scipy.io.loadmat imports them as numpy object arrays - which is an array with dtype=object.
To be hon... | Numpy equivalent of MATLAB's cell array | I want to create a MATLAB-like cell array in Numpy. How can I accomplish this?
| [
"Matlab cell arrays are most similar to Python lists, since they can hold any object - but scipy.io.loadmat imports them as numpy object arrays - which is an array with dtype=object.\nTo be honest though you are just as well off using Python lists - if you are holding general objects you will loose almost all of th... | [
18
] | [] | [] | [
"matlab",
"numpy",
"python"
] | stackoverflow_0001761419_matlab_numpy_python.txt |
Q:
How to convert text into URL syntax on Python?
I want to convert Python string to URL syntax.
For example
>>> u'한글'.encode('utf-8')
'\xed\x95\x9c\xea\xb8\x80' to '%ed%95%9c%ea%b8%80'
A:
>>> import urllib2
>>> urllib2.quote('한글')
'%ED%95%9C%EA%B8%80'
| How to convert text into URL syntax on Python? | I want to convert Python string to URL syntax.
For example
>>> u'한글'.encode('utf-8')
'\xed\x95\x9c\xea\xb8\x80' to '%ed%95%9c%ea%b8%80'
| [
">>> import urllib2\n>>> urllib2.quote('한글')\n'%ED%95%9C%EA%B8%80'\n\n"
] | [
10
] | [] | [] | [
"python",
"url"
] | stackoverflow_0001762123_python_url.txt |
Q:
Fastest way to search 1GB+ a string of data for the first occurrence of a pattern in Python
There's a 1 Gigabyte string of arbitrary data which you can assume to be equivalent to something like:
1_gb_string=os.urandom(1*gigabyte)
We will be searching this string, 1_gb_string, for an infinite number of fixed width... | Fastest way to search 1GB+ a string of data for the first occurrence of a pattern in Python | There's a 1 Gigabyte string of arbitrary data which you can assume to be equivalent to something like:
1_gb_string=os.urandom(1*gigabyte)
We will be searching this string, 1_gb_string, for an infinite number of fixed width, 1 kilobyte patterns, 1_kb_pattern. Every time we search the pattern will be different. So cachi... | [
"As you clarify that long-ish preprocessing is acceptable, I'd suggest a variant of Rabin-Karp: \"an algorithm of choice for multiple pattern search\", as wikipedia puts it.\nDefine a \"rolling hash\" function, i.e., one such that, when you know the hash for haystack[x:x+N], computing the hash for haystack[x+1:x+N+... | [
12,
5,
1,
1,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"algorithm",
"large_data_volumes",
"python",
"search"
] | stackoverflow_0001750343_algorithm_large_data_volumes_python_search.txt |
Q:
How to integrate Disqus to Facebook Connect-enabled site (python Tornado app)
I succesfully use Facebook auth for my Tornado-based site using FacebookMixin. I also have Facebook Connect auth enabled for my Disqus, which placed in page using javascript widget. When user already logged in using FB to my site, they s... | How to integrate Disqus to Facebook Connect-enabled site (python Tornado app) | I succesfully use Facebook auth for my Tornado-based site using FacebookMixin. I also have Facebook Connect auth enabled for my Disqus, which placed in page using javascript widget. When user already logged in using FB to my site, they still have to log to FB again when they want to comment using Disqus.
How Discus FB ... | [
"how did you integrate disqus into your site? are you using their api in your backend?\nIf I understand disqus correctly then you would need to post to their service usign the data of the authenticated users, else (if they use the javascript widget) they would need to establish a fb connect session with disqus whic... | [
0
] | [] | [] | [
"disqus",
"python",
"tornado"
] | stackoverflow_0001762268_disqus_python_tornado.txt |
Q:
Adding Lists Elements to 'Mega List'
Let's say I have a list somewhere called majorPowers which contain these two lists:
axis=["germany","italy","japan"]
allies=["russia","uk","us"]
I'd like to insert each of the elements of these lists, into a new mega-list. I'm currently doing this:
>>> temp = []
>>> temp = [ww... | Adding Lists Elements to 'Mega List' | Let's say I have a list somewhere called majorPowers which contain these two lists:
axis=["germany","italy","japan"]
allies=["russia","uk","us"]
I'd like to insert each of the elements of these lists, into a new mega-list. I'm currently doing this:
>>> temp = []
>>> temp = [ww2.append(t) for t in majorPowers]
>>>ww2
[... | [
"It is good that you ask this question, because it is bad form to misuse list\ncomprehensions like that. The code you show uses append, not to generate the\nelements of temp, but because of its side effects. Avoid side effects in list\ncomprehensions!\nSo, there are a couple of things you can do. First, you can use... | [
5,
1,
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0001762446_list_python.txt |
Q:
UnicodeDecodeError when using socket.gethostname() result
Some of my users report that the following code may raise a UnicodeDecodeError when the hostname contains non-ascii characters (however I haven't been able to replicate this on my Windows Vista machine):
self.path = path
self.lock_file = os.path.abs... | UnicodeDecodeError when using socket.gethostname() result | Some of my users report that the following code may raise a UnicodeDecodeError when the hostname contains non-ascii characters (however I haven't been able to replicate this on my Windows Vista machine):
self.path = path
self.lock_file = os.path.abspath(path) + ".lock"
self.hostname = socket.gethostname()
... | [
"I don't think gethostname() is necessarily giving you a unicode object. It could be the directory name of lockfile. Regardless, one of them is a standard string with a non-ASCII (higher than 127) char in it and the other is a unicode string.\nThe problem is that the join function in the ntpath module (the module P... | [
1,
0,
0,
0
] | [] | [] | [
"python",
"unicode"
] | stackoverflow_0001290601_python_unicode.txt |
Q:
Why is it when I print something, there is always a unicode next to it? (Python)
[u'Iphones', u'dont', u'receieve', u'messages']
Is there a way to print it without the "u" in front of it?
A:
What you are seeing is the __repr__() representation of the unicode string which includes the u to make it clear. If you ... | Why is it when I print something, there is always a unicode next to it? (Python) | [u'Iphones', u'dont', u'receieve', u'messages']
Is there a way to print it without the "u" in front of it?
| [
"What you are seeing is the __repr__() representation of the unicode string which includes the u to make it clear. If you don't want the u you could print the object (using __str__) - this works for me:\nprint [str(x) for x in l]\n\nProbably better is to read up on python unicode and encode using the particular uni... | [
9,
4
] | [] | [] | [
"python"
] | stackoverflow_0001762690_python.txt |
Q:
Pyinstaller ld-linux-x86-64.so.2 linking problem
I'm trying to deploy my Python based application on another Linux host. Pyinstaller works flawlessly as long as I run the generated executable on my own system.
On the target box I get this error message:
/lib/ld-linux-x86-64.so.2: bad ELF
interpreter: No such f... | Pyinstaller ld-linux-x86-64.so.2 linking problem | I'm trying to deploy my Python based application on another Linux host. Pyinstaller works flawlessly as long as I run the generated executable on my own system.
On the target box I get this error message:
/lib/ld-linux-x86-64.so.2: bad ELF
interpreter: No such file or directory
As the output of ldd shows Pyinstall... | [
"This is not really a Python question, but a UNIX/Linux compile and link question.\nFirst of all, are you using the latest Pyinstaller. If not, then try that. If you still have the problem, then please report the bug to the Pyinstaller developers here.\nTry to workaround your problem by using LD_LIBRARY_PATH to poi... | [
1
] | [] | [] | [
"deployment",
"dll",
"linux",
"pyinstaller",
"python"
] | stackoverflow_0001761140_deployment_dll_linux_pyinstaller_python.txt |
Q:
How to install python-igraph on Ubuntu 8.04 LTS 64-Bit?
Apparently libigraph and python-igraph are the only packages on earth that can't be installed via apt-get or easy_install under Ubuntu 8.04 LTS 64-bit.
Installing both from source from source on seems to go smoothly...until I try to use them.
When I run pytho... | How to install python-igraph on Ubuntu 8.04 LTS 64-Bit? | Apparently libigraph and python-igraph are the only packages on earth that can't be installed via apt-get or easy_install under Ubuntu 8.04 LTS 64-bit.
Installing both from source from source on seems to go smoothly...until I try to use them.
When I run python I get:
>>> import igraph
Traceback (most recent call last):... | [
"How did you compile? Did you do a make install (if there was any).\nAs for the 'library not found' error in the easy_install version, i'd try the following:\n\n'sudo updatedb' (to update the locate database)\n'locate libigraph.so.0' (to find where this file is on your system. If you did a make install it could hav... | [
11,
2,
0,
0
] | [] | [] | [
"64_bit",
"igraph",
"python",
"ubuntu_8.04"
] | stackoverflow_0000834076_64_bit_igraph_python_ubuntu_8.04.txt |
Q:
Create broken symlink with Python
Using Python I want to create a symbolic link pointing to a path that does not exist. However os.symlink just complains about "OSError: [Errno 2] No such file or directory:".. This can easily be done with the ln program, but how to do it in Python without calling the ln program fr... | Create broken symlink with Python | Using Python I want to create a symbolic link pointing to a path that does not exist. However os.symlink just complains about "OSError: [Errno 2] No such file or directory:".. This can easily be done with the ln program, but how to do it in Python without calling the ln program from Python?
Edit: somehow I really messe... | [
"Such error is raised when you try to create a symlink in non-existent directory. For example, the following code will fail if /tmp/subdir doesn't exist:\nos.symlink('/usr/bin/python', '/tmp/subdir/python')\n\nBut this should run successfully:\nsrc = '/usr/bin/python'\ndst = '/tmp/subdir/python'\n\nif not os.path.i... | [
9,
3,
0,
0
] | [] | [] | [
"ln",
"python",
"symlink"
] | stackoverflow_0001762831_ln_python_symlink.txt |
Q:
Testing complex datatypes?
What's are some ways of testing complex data types such as video, images, music, etc. I'm using TDD and wonder are there alternatives to "gold file" testing for rendering algorithms. I understand that there's ways to test other parts of the program that don't render and using those resul... | Testing complex datatypes? | What's are some ways of testing complex data types such as video, images, music, etc. I'm using TDD and wonder are there alternatives to "gold file" testing for rendering algorithms. I understand that there's ways to test other parts of the program that don't render and using those results you can infer. However, I'm p... | [
"The idea how to test rendering is quite simple: to test a function use the inverse function and check if the input and output match (match is not equality in your case):\nf(f^-1(x)) = x\n\nTo test a rendering algorithm you would encode the raw input, render the encoded values and analyze the difference between the... | [
2,
0
] | [] | [] | [
"image",
"opencv",
"python",
"testing"
] | stackoverflow_0001761663_image_opencv_python_testing.txt |
Q:
What Is The Best Python Zip Module To Handle Large Files?
EDIT: Specifically compression and extraction speeds.
Any Suggestions?
Thanks
A:
So I made a random-ish large zipfile:
$ ls -l *zip
-rw-r--r-- 1 aleax 5000 115749854 Nov 18 19:16 large.zip
$ unzip -l large.zip | wc
23396 93633 2254735
i.e., 116 M... | What Is The Best Python Zip Module To Handle Large Files? | EDIT: Specifically compression and extraction speeds.
Any Suggestions?
Thanks
| [
"So I made a random-ish large zipfile:\n$ ls -l *zip\n-rw-r--r-- 1 aleax 5000 115749854 Nov 18 19:16 large.zip\n$ unzip -l large.zip | wc\n 23396 93633 2254735\n\ni.e., 116 MB with 23.4K files in it, and timed things:\n$ time unzip -d /tmp large.zip >/dev/null\n\nreal 0m14.702s\nuser 0m2.586s\nsys ... | [
15,
5
] | [] | [] | [
"compression",
"extraction",
"performance",
"python",
"zip"
] | stackoverflow_0001759736_compression_extraction_performance_python_zip.txt |
Q:
Python: asynchronous tcp socketserver
I'm looking http://docs.python.org/library/socketserver.html to try and handle asynchronous requests with the socketserver in python. At the very bottom there is an example, but it doesn't make sense. It says you use port 0 which assigns an arbitrary unused port. But how do yo... | Python: asynchronous tcp socketserver | I'm looking http://docs.python.org/library/socketserver.html to try and handle asynchronous requests with the socketserver in python. At the very bottom there is an example, but it doesn't make sense. It says you use port 0 which assigns an arbitrary unused port. But how do you know what port to use for the client if t... | [
"Since the client is implemented in the same script as the server, the port is known. In a real-world scenario, you should specify a port for your daemon. Besides letting your clients know on which port to connect, you may also need to know so that you can open firewalls between your clients and your server.\n",
... | [
9,
5,
2,
0
] | [] | [] | [
"asynchronous",
"networking",
"python",
"python_2.7"
] | stackoverflow_0001763549_asynchronous_networking_python_python_2.7.txt |
Q:
Deploying a python CGI app
I have developed a python CGI application which works just fine on my development box. My hosting provider however gives me little control of its server: I use a lot of custom stuff in my python environment (like sqlalchemy and mako templating) and the servers python version is far too o... | Deploying a python CGI app | I have developed a python CGI application which works just fine on my development box. My hosting provider however gives me little control of its server: I use a lot of custom stuff in my python environment (like sqlalchemy and mako templating) and the servers python version is far too old to be used. My question is: h... | [
"\nhow do I set up a isolated, complete, standalone python environment in my home directory\n\n\nmkdir /home/me/.local (if it doesn't already exist. You don't have to use .local but it is becoming the normal place to put this)\nmkdir /home/me/.local/src (ditto)\ncd /home/me/.local/src\nwget http://python.org/ftp/py... | [
4,
1,
0,
0
] | [] | [] | [
"cgi",
"hosting",
"linux",
"python"
] | stackoverflow_0001759205_cgi_hosting_linux_python.txt |
Q:
len(object) or hasattr(object, __iter__)?
(The following is python3-related (if that matter).)
This this the code I've written (simplified) :
class MyClass:
def __init__(self):
self.__some_var = []
@property
def some_var(self):
return self.__some__var
@some_var.setter
def so... | len(object) or hasattr(object, __iter__)? | (The following is python3-related (if that matter).)
This this the code I've written (simplified) :
class MyClass:
def __init__(self):
self.__some_var = []
@property
def some_var(self):
return self.__some__var
@some_var.setter
def some_var(self, new_value):
if hasattr(new... | [
"There's no \"performance cost\" of hasattr that matters. It's fast enough that you would have a hard time measuring it.\nPlease do not use __ (double underscore) for your own attributes. It's confusing to the rest of us.\nIt's usually best to use the collections Abstract Base Class membership for this kind of th... | [
4,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0001763507_python.txt |
Q:
Scanning Keypress in Python
I have paused a script for lets say 3500 seconds by using time module for ex time.sleep(3500).
Now, my aim is to scan for keypresses while the script is on sleep, i mean its on this line.
Its like I want to restart the script if a "keypress Ctrl+R" is pressed.
For ex.. consider
#!/usr/... | Scanning Keypress in Python | I have paused a script for lets say 3500 seconds by using time module for ex time.sleep(3500).
Now, my aim is to scan for keypresses while the script is on sleep, i mean its on this line.
Its like I want to restart the script if a "keypress Ctrl+R" is pressed.
For ex.. consider
#!/usr/bin/python
import time
print "Hel... | [
"I am aware that this does not fully answer your question, but you could do the following:\n\nPut the program logic code in a function, say perform_actions. Call it when the program starts.\nAfter the code has been run, start listening for an interrupt.\n\n\nThat is, the user must press ctrl+c instead of ctrl+r.\n\... | [
4,
3
] | [
"in a for loop sleep 3500 times for 1 second checking if a key was pressed each time\n# sleep for 3500 seconds unless ctrl+r is pressed\nfor i in range(3500):\n time.sleep(1)\n # check if ctrl+r is pressed\n # if pressed -> do something\n # otherwise go back to sleep\n\n"
] | [
-2
] | [
"linux",
"python",
"scripting"
] | stackoverflow_0001762697_linux_python_scripting.txt |
Q:
How to find unique starts of strings?
If I have a list of strings (eg 'blah 1', 'blah 2' 'xyz fg','xyz penguin'), what would be the best way of finding the unique starts of strings ('xyz' and 'blah' in this case)? The starts of strings can be multiple words.
A:
Your question is confusing, as it is not clear what... | How to find unique starts of strings? | If I have a list of strings (eg 'blah 1', 'blah 2' 'xyz fg','xyz penguin'), what would be the best way of finding the unique starts of strings ('xyz' and 'blah' in this case)? The starts of strings can be multiple words.
| [
"Your question is confusing, as it is not clear what you really want. So I'll give three answers and hope that one of them at least partially answers your question.\n\nTo get all unique prefixes of a given list of string, you can do:\n>>> l = ['blah 1', 'blah 2', 'xyz fg', 'xyz penguin']\n>>> set(s[:i] for s in l f... | [
4,
2
] | [] | [] | [
"python"
] | stackoverflow_0001763510_python.txt |
Q:
Phonon VideoWidget error: "the video widget could not be initialized correctly"
I asked this question on the PyQt mailing list, and didn't get any responses, so I'll try my luck here.
I've encountered a frustrating issue (on Windows only): when trying to create a VideoWidget instance, I'm getting the error message... | Phonon VideoWidget error: "the video widget could not be initialized correctly" | I asked this question on the PyQt mailing list, and didn't get any responses, so I'll try my luck here.
I've encountered a frustrating issue (on Windows only): when trying to create a VideoWidget instance, I'm getting the error message "the video widget could not be initialized correctly". Oddly, this just surfaced in ... | [
"The code that generates that message is in 3rdparty/phonon/ds9/videorenderer_vmr9.cpp:\nm_filter = Filter(CLSID_VideoMixingRenderer9, IID_IBaseFilter);\nif (!m_filter) {\n qWarning(\"the video widget could not be initialized correctly\");\n return;\n }\n\nFilter is type ComPointer<IBaseFilter> and its constr... | [
3,
0
] | [] | [] | [
"phonon",
"pyqt",
"python",
"qt"
] | stackoverflow_0001291068_phonon_pyqt_python_qt.txt |
Q:
How do I do a "for each" , starting at a certain index of a list (Python)?
Suppose I have this list:
thelist = ['apple','orange','banana','grapes']
for fruit in thelist:
This would go through all the fruits.
However, what if I wanted to start at orange? Instead of starting at apple?
Sure, I could do "if ...contin... | How do I do a "for each" , starting at a certain index of a list (Python)? | Suppose I have this list:
thelist = ['apple','orange','banana','grapes']
for fruit in thelist:
This would go through all the fruits.
However, what if I wanted to start at orange? Instead of starting at apple?
Sure, I could do "if ...continue", but there must be a better way?
| [
"for fruit in thelist[1:]:\n ...\n\nthis of course suppose you know at which index to start. but you can find the index easily:\nfor fruit in thelist[thelist.index('orange'):]:\n ...\n\n",
"using python's elegant slices\n>>> for fruit in thelist[1:]:\n>>> print fruit\n\n",
"As mentioned by Paul McGuire... | [
14,
11,
3,
2,
1,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0001762571_list_python.txt |
Q:
Python os.getcwd paths
I'm using os.listdir() to get all the files from a directory and dump them out to a txt file. I'm going to use the txt file to import into access to generate hyperlinks. The problem I'm having is getting the correct path. So when the script is ran it uses whatever directory you are in. Here ... | Python os.getcwd paths | I'm using os.listdir() to get all the files from a directory and dump them out to a txt file. I'm going to use the txt file to import into access to generate hyperlinks. The problem I'm having is getting the correct path. So when the script is ran it uses whatever directory you are in. Here is an example. Right now it ... | [
"This line of yours:\nf.writelines([os.getcwd %s % (f) for f in myDirectory])\n\nis invalid Python syntax and it's very hard to guess what you had in mind for it -- for example, why would you care about the current directory when myDirectory lists, not files in the current directory, but rather files in subdirector... | [
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0001764322_python.txt |
Q:
String formatting expressions (Python)
String formatting expressions:
'This is %d %s example!' % (1, 'nice')
String formatting method calls:
'This is {0} {1} example!'.format(1, 'nice')
I personally prefer the method calls (second example) for readability but since it is new, there is some chance that one or the... | String formatting expressions (Python) | String formatting expressions:
'This is %d %s example!' % (1, 'nice')
String formatting method calls:
'This is {0} {1} example!'.format(1, 'nice')
I personally prefer the method calls (second example) for readability but since it is new, there is some chance that one or the other of these may become deprecated over t... | [
"Neither; the first one is used in a lot of places and the second one was just introduced. So the question is more which style you prefer. I actually prefer the dict based formatting:\nd = { 'count': 1, 'txt': 'nice' }\n'This is %(count)d %(txt)s example!' % d\n\nIt makes sure that the right parameter goes into the... | [
8,
6,
5
] | [] | [] | [
"deprecated",
"printf",
"python",
"string"
] | stackoverflow_0001763184_deprecated_printf_python_string.txt |
Q:
Width and Precision using *
I'm learning Python from a book and came across this example:
>>> '%f, %.2f, %.*f % (1/3.0, 1/3.0, 4, 1/3.0)
# Result: '0.333333, 0.33, 0.3333'
Don't quite understand what's happening here, especially the '4' in between.
A:
I think you meant something like this:
>>> '%f, %2.f, %.*f' ... | Width and Precision using * | I'm learning Python from a book and came across this example:
>>> '%f, %.2f, %.*f % (1/3.0, 1/3.0, 4, 1/3.0)
# Result: '0.333333, 0.33, 0.3333'
Don't quite understand what's happening here, especially the '4' in between.
| [
"I think you meant something like this:\n>>> '%f, %2.f, %.*f' % (1/3.0, 1.3, 4, 1/3.0)\n'0.333333, 1, 0.3333'\n\n4 is a wild card value that is used in place of asterisk *. When expanded it would be equivalent to:\n>>> '%f, %2.f, %.4f' % (1/3.0, 1.3, 1/3.0)\n\n",
"There are two syntax errors in the line you pos... | [
3,
1
] | [] | [] | [
"python",
"string_formatting"
] | stackoverflow_0001764812_python_string_formatting.txt |
Q:
Embedding a remote Python shell in an application
You can embed the IPython shell inside of your application so that it launches the shell in the foreground. Is there a way to embed a telnet server in a python app so that you can telnet to a certain port and launch a remote IPython shell?
Any tips for redirecti... | Embedding a remote Python shell in an application | You can embed the IPython shell inside of your application so that it launches the shell in the foreground. Is there a way to embed a telnet server in a python app so that you can telnet to a certain port and launch a remote IPython shell?
Any tips for redirecting the input/output streams for IPython or how to hook ... | [
"Python includes a telnet client, but not a telnet server. You can implement a telnet server using Twisted. Here's an example. As for hooking these things together, that's up to you.\n",
"Use Twisted Manhole. Docs are a bit lacking, but it's easy enough to set up a telnet-based remote server and it comes with ... | [
3,
1,
0,
0
] | [] | [] | [
"networking",
"python"
] | stackoverflow_0000048176_networking_python.txt |
Q:
Is there an algorithm to find unique combinations of 2 lists? 5 lists?
I have N Lists I'd like to find unique combinations of. I've written it out on my whiteboard and it all seems to have a pattern, I just haven't found it yet. I feel I can express a brute-force method and that will certainly be something I pursu... | Is there an algorithm to find unique combinations of 2 lists? 5 lists? | I have N Lists I'd like to find unique combinations of. I've written it out on my whiteboard and it all seems to have a pattern, I just haven't found it yet. I feel I can express a brute-force method and that will certainly be something I pursue. Is there an alternative? Would a different data structure (binary tree?) ... | [
"Perhaps you are looking for itertools.product:\n#!/usr/bin/env python\nimport itertools\na=[1,2]\nb=['a','b']\nc=[str(s)+str(t) for s,t in itertools.product(a,b)]\nprint(c)\n['1a', '1b', '2a', '2b']\n\nv=[1,'a']\nw=[1,'b']\nx=[1,'c']\ny=[1,'d']\nz=[1,'e']\n\nr=[''.join([str(elt) for elt in p]) for p in itertools.p... | [
8,
2,
2,
1,
1,
1,
0
] | [] | [] | [
"algorithm",
"php",
"python"
] | stackoverflow_0001764464_algorithm_php_python.txt |
Q:
List implemented using an inorder binary tree
For the new computer science assignment we are to implement a list/array using an inorder binary tree. I would just like a suggestion rather than a solution.
The idea is having a binary tree that has its nodes accessible via indexes, e.g.
t = ListTree()
t.insert(2,0)... | List implemented using an inorder binary tree | For the new computer science assignment we are to implement a list/array using an inorder binary tree. I would just like a suggestion rather than a solution.
The idea is having a binary tree that has its nodes accessible via indexes, e.g.
t = ListTree()
t.insert(2,0) # 1st argument is the value, 2nd the index to inse... | [
"You really wouldn't want to store it on the node itself, because then the index would have to be updated on inserts for all nodes with index less than insert index. I think the real question is how to do an in-order traversal. Try having your recursive function return the number of nodes to its left. \n",
"I ... | [
1,
1,
0,
0,
0
] | [] | [] | [
"algorithm",
"binary_tree",
"python"
] | stackoverflow_0001654947_algorithm_binary_tree_python.txt |
Q:
python multiprocessing db access is very slow
I have GUI that will interact with a postgres database, using psycopg2. I have db connection in a multiprocessing process, and send SQL via a multiprocessing queue, and receive via another queue.
The problem is that the speed is very very slow. A simple select * from... | python multiprocessing db access is very slow | I have GUI that will interact with a postgres database, using psycopg2. I have db connection in a multiprocessing process, and send SQL via a multiprocessing queue, and receive via another queue.
The problem is that the speed is very very slow. A simple select * from a small table (30 rows) can be 1/10th of a second,... | [
"Try to isolate what is taking the time - is it the multiprocessing or the database? For example try calling the database directly from the python interactive shell - the ipython shell has 'time' and 'timeit' commands for measuring things like this. Alternatively stub out DataBase.execute to return canned values,... | [
0,
0,
0
] | [] | [] | [
"multiprocessing",
"python"
] | stackoverflow_0001754438_multiprocessing_python.txt |
Q:
To have two Pg queries in one Python method
Thank you for Denis who solves the first bug!
How can you have two Postgres queries in one Python method?
Example where the 2nd query is not run
def comp_func(pgmasi):
pgmasi.query("""CREATE TABLE courses (
course_id SERIAL PRIMARY KEY)""")
... | To have two Pg queries in one Python method | Thank you for Denis who solves the first bug!
How can you have two Postgres queries in one Python method?
Example where the 2nd query is not run
def comp_func(pgmasi):
pgmasi.query("""CREATE TABLE courses (
course_id SERIAL PRIMARY KEY)""")
pgmasi.query("""CREATE TABLE files ( # not exe... | [
"Probably you missed closing parentheses in the line as error message says:\npgmasi.query(\"INSERT INTO files('binf','file_name') VALUES(file,file_name)\"\n\n"
] | [
2
] | [] | [] | [
"postgresql",
"python"
] | stackoverflow_0001765630_postgresql_python.txt |
Q:
Python: Binding method
In following example I am trying to bind a method object via types.MethodType(...). It does not seem to work. Any suggestions? Thanks in advance.
import types
class Base:
def payload(self, *args):
print "Base:payload"
class Drvd(Base):
def iter(self, func):
derived... | Python: Binding method | In following example I am trying to bind a method object via types.MethodType(...). It does not seem to work. Any suggestions? Thanks in advance.
import types
class Base:
def payload(self, *args):
print "Base:payload"
class Drvd(Base):
def iter(self, func):
derived_func = types.MethodType(fun... | [
"You're specifically requesting the use of the underlying function (im_func) of Base.payload, with a fake im_class of Drvd. Add after the existing print in iter:\n print \"w/class:\", derived_func.im_class\n print \"w/func:\", derived_func.im_func\n\nand you'll see the total output as:\n$ python bou.py \nbas... | [
2,
1,
0
] | [] | [] | [
"bind",
"binding",
"methods",
"python",
"types"
] | stackoverflow_0001765922_bind_binding_methods_python_types.txt |
Q:
What are the differences in variable scoping between Python and Scheme?
Refering to Variable Scoping.
I'm trying to figure out what are the differences between those 2.
For example, Anonymous functions in a scheme function has access to the variables local to that function. Does python have this?
Thanks!
A:
In P... | What are the differences in variable scoping between Python and Scheme? | Refering to Variable Scoping.
I'm trying to figure out what are the differences between those 2.
For example, Anonymous functions in a scheme function has access to the variables local to that function. Does python have this?
Thanks!
| [
"In Python variable scope can be either global or function. In Scheme, the scope can be any block.\nFor example, in Scheme you could define a variable inside a loop, and it wouldn't be accessible from outside the loop. In Python, the scope being the whole function, this variable would 'leak' out of the loop into ... | [
4,
3,
0,
0
] | [] | [] | [
"python",
"scheme"
] | stackoverflow_0001765560_python_scheme.txt |
Q:
Pygame: Sprite changing due to direction of movement
I've just started learning how to use pygame yesterday. I was read this one book that was super helpful and followed all its tutorials and examples and stuff. I wanted to try making a really simple side scroller/platforming game but the book sorta jumped pretty ... | Pygame: Sprite changing due to direction of movement | I've just started learning how to use pygame yesterday. I was read this one book that was super helpful and followed all its tutorials and examples and stuff. I wanted to try making a really simple side scroller/platforming game but the book sorta jumped pretty fast into 3D modeling with out instructing how to make cha... | [
"Here is a dumb example which alernates between two first images of the spritesheet when you press left/right:\nimport pygame\n\nquit = False\npygame.init()\ndisplay = pygame.display.set_mode((640,480))\nsprite_sheet = pygame.image.load('sprite.bmp').convert()\n\n# by default, display the first sprite\nimage_number... | [
1,
1,
0
] | [] | [] | [
"2d",
"pygame",
"python",
"sprite"
] | stackoverflow_0000733916_2d_pygame_python_sprite.txt |
Q:
Python, removing the \'s before getting them processed
I'm making a program that asks for a path, and Windows' paths contain backslashes, which can be interpreted as an escape sequence by python if the letter right next is the wrong one. I tried string.replace() but it doesn't work as these backslashes get transfo... | Python, removing the \'s before getting them processed | I'm making a program that asks for a path, and Windows' paths contain backslashes, which can be interpreted as an escape sequence by python if the letter right next is the wrong one. I tried string.replace() but it doesn't work as these backslashes get transformed into escape sequences before having the replace functio... | [
"No, the backslash is not interpreted as an escape sequence except in Python source code. Unless you're eval()ing the path, which would be Wrong, I'm not sure why you'd have a problem.\n",
"If you are asking for the user for input, then a \\ will go into a string as a \\ correctly. Only if you then eval the user'... | [
6,
3,
3
] | [] | [] | [
"backslash",
"escaping",
"python"
] | stackoverflow_0001766510_backslash_escaping_python.txt |
Q:
How to omit using python coverage lib?
I would like to omit some module that are in some particular directory : eggs and bin
coverage -r -i --omit=/usr/lib/,/usr/share/,eggs,bin
Name Stmts Exec Cover
------------------------------------------------... | How to omit using python coverage lib? | I would like to omit some module that are in some particular directory : eggs and bin
coverage -r -i --omit=/usr/lib/,/usr/share/,eggs,bin
Name Stmts Exec Cover
-----------------------------------------------------------------------------------------
bi... | [
"To tell you the truth, I think this might just be a bug in coverage.py. I'll look into it soon.\nUPDATED: OK, I've fixed this bug (I hope), and posted new kits: Coverage.py 3.2b2. Please let me know if it still is no good.\n"
] | [
6
] | [] | [] | [
"code_coverage",
"coverage.py",
"python"
] | stackoverflow_0001764806_code_coverage_coverage.py_python.txt |
Q:
Automatic string length in recarray
If I create a recarray in this way:
In [29]: np.rec.fromrecords([(1,'hello'),(2,'world')],names=['a','b'])
The result looks fine:
Out[29]:
rec.array([(1, 'hello'), (2, 'world')],
dtype=[('a', '<i8'), ('b', '|S5')])
But if I want to specify the data types:
In [32]: np.r... | Automatic string length in recarray | If I create a recarray in this way:
In [29]: np.rec.fromrecords([(1,'hello'),(2,'world')],names=['a','b'])
The result looks fine:
Out[29]:
rec.array([(1, 'hello'), (2, 'world')],
dtype=[('a', '<i8'), ('b', '|S5')])
But if I want to specify the data types:
In [32]: np.rec.fromrecords([(1,'hello'),(2,'world')],... | [
"If you don't need to manipulate the strings as bytes, you may use the object data-type to represent them. This essentially stores a pointer instead of the actual bytes:\nIn [38]: np.array(data, dtype=[('a', np.uint8), ('b', np.object)])\nOut[38]: \narray([(1, 'hello'), (2, 'world')], \n dtype=[('a', '|u1'), ... | [
2,
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0001664917_numpy_python.txt |
Q:
Sphinx templating
I am using Sphinx. I want to template it. So after reading the docs, what I am trying is, in my conf.py,
I put a line like,
templates_path = ['_templates']
and I created a file
_templates/page.html
But this does not override the default template provided by sphinx. What more should I do, and wh... | Sphinx templating | I am using Sphinx. I want to template it. So after reading the docs, what I am trying is, in my conf.py,
I put a line like,
templates_path = ['_templates']
and I created a file
_templates/page.html
But this does not override the default template provided by sphinx. What more should I do, and where does this template ... | [
"Be sure you are using the theme name as an explicit directory in your template. e.g.: \n{% extends \"basic/layout.html\" %}\nsee: HTML Theming Support\n",
"The documentation https://www.sphinx-doc.org/en/master/templating.html#working-with-the-builtin-templates\nsays that the template it's looking for is layout... | [
6,
1,
0
] | [] | [] | [
"python",
"python_sphinx",
"templates"
] | stackoverflow_0001079417_python_python_sphinx_templates.txt |
Q:
Django ajax formatting convention
What's the correct way to do an ajax request, I've seen people using a returning render_to_string so that they can do all their formatting within python using the template language. eg~
return render_to_string('calendar.html', {
'self' : self,
'month' : self.today.month,})
with t... | Django ajax formatting convention | What's the correct way to do an ajax request, I've seen people using a returning render_to_string so that they can do all their formatting within python using the template language. eg~
return render_to_string('calendar.html', {
'self' : self,
'month' : self.today.month,})
with this as the javascript:
$('#django_calen... | [
"I've been using JSON exclusively for AJAX, with simplejson returning whatever data is really easy, it looks like this:\nfrom django.utils import simplejson\nreply = simplejson.dumps({'comment_body': formatted_post, 'user_icon': request.user.profile.image.url })\nreturn HttpResponse(reply, mimetype=\"application/js... | [
2,
1
] | [] | [] | [
"django",
"dom",
"formatting",
"json",
"python"
] | stackoverflow_0001760538_django_dom_formatting_json_python.txt |
Q:
Python type long vs C 'long long'
I would like to represent a value as a 64bit signed long, such that values larger than (2**63)-1 are represented as negative, however Python long has infinite precision. Is there a 'quick' way for me to achieve this?
A:
You could use ctypes.c_longlong:
>>> from ctypes import c_l... | Python type long vs C 'long long' | I would like to represent a value as a 64bit signed long, such that values larger than (2**63)-1 are represented as negative, however Python long has infinite precision. Is there a 'quick' way for me to achieve this?
| [
"You could use ctypes.c_longlong:\n>>> from ctypes import c_longlong as ll\n>>> ll(2 ** 63 - 1)\nc_longlong(9223372036854775807L)\n>>> ll(2 ** 63)\nc_longlong(-9223372036854775808L)\n>>> ll(2 ** 63).value\n-9223372036854775808L\n\nThis is really only an option if you know for sure that a signed long long will be 64... | [
13,
13,
3,
1
] | [] | [] | [
"64_bit",
"long_integer",
"python"
] | stackoverflow_0001764548_64_bit_long_integer_python.txt |
Q:
Python won't refresh URL to receive new forex ticker data
I am trying to save updated Forex ticker data from this website: http://forex.offers4u.biz/TickDBReadDB.php?p=EURUSD
just hit refresh to update the ticker.
when I use my little python script, it saves the text once, but if i run it again, it makes a new fil... | Python won't refresh URL to receive new forex ticker data | I am trying to save updated Forex ticker data from this website: http://forex.offers4u.biz/TickDBReadDB.php?p=EURUSD
just hit refresh to update the ticker.
when I use my little python script, it saves the text once, but if i run it again, it makes a new file with the same old data. How can I add a "cachebreaker" so tha... | [
"urllib2 doesn't do any caching. Are you going through a proxy? Or the server may be caching.\nTry using a Cache-Control header described here, section 14.9\nEDIT: Mind you, the most recent data on that page is from 2009.11.16 20:47:37. Are you sure it's still being actively updated?\n"
] | [
0
] | [] | [] | [
"python",
"refresh",
"ticker",
"urllib"
] | stackoverflow_0001767616_python_refresh_ticker_urllib.txt |
Q:
how to insert a infomation on a table in Django
This is my form on models.py
class ItemForm(forms.Form):
itemname = forms.CharField(max_length=100)
itemwording = forms.CharField(max_length=100)
notes = forms.CharField()
abundance = forms.IntegerField(max_value=10)
collunit = forms.CharField(ma... | how to insert a infomation on a table in Django | This is my form on models.py
class ItemForm(forms.Form):
itemname = forms.CharField(max_length=100)
itemwording = forms.CharField(max_length=100)
notes = forms.CharField()
abundance = forms.IntegerField(max_value=10)
collunit = forms.CharField(max_length=50)
litref = forms.CharField(max_length=... | [
"The data you've posted doesn't indicate the source of the problem. Did you clear your database and run syncdb when you last changed your models?\nThe error you're seeing relates to trying to introduce a duplicate value into a column which must be unique, constrained at the database level. You have an object that's... | [
1
] | [] | [] | [
"django",
"django_forms",
"django_models",
"django_views",
"python"
] | stackoverflow_0001767506_django_django_forms_django_models_django_views_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.