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:
Shortest representation of this function in Python
Currently I have:
def func(points): #Input is a matrix with n lines and 2 columns.
centroid = numpy.mean(points, axis=0)
sum = 0
for point in points:
x = point[0] - centroid[0]
y = point[1] - centorid[1]
sum += x**2 + y**2
r... | Shortest representation of this function in Python |
Currently I have:
def func(points): #Input is a matrix with n lines and 2 columns.
centroid = numpy.mean(points, axis=0)
sum = 0
for point in points:
x = point[0] - centroid[0]
y = point[1] - centorid[1]
sum += x**2 + y**2
return math.sqrt(sum)
| [
"There is a builtin for summation of a sequence, called sum (oddly enough). We can create the data using a generator comprehension, and feed it directly to the sum function. Thus:\nreturn math.sqrt(sum((p[0]-centroid[0])**2 + (p[1]-centroid[1])**2 for p in points))\n\n",
"Since you're using NumPy, you can use num... | [
7,
1
] | [] | [] | [
"math",
"python"
] | stackoverflow_0004405968_math_python.txt |
Q:
Atomic file write operations (cross platform)
How do I build up an atomic file write operation? The file is to be written by a Java service and read by python scripts.
For the record, reads are far greater than writes. But the write happens in batches and tend to be long. The file size amounts to mega bytes.
Rig... | Atomic file write operations (cross platform) | How do I build up an atomic file write operation? The file is to be written by a Java service and read by python scripts.
For the record, reads are far greater than writes. But the write happens in batches and tend to be long. The file size amounts to mega bytes.
Right now my approach is:
Write file contents to a te... | [
"AFAIK no. \nAnd the reason is that for such an atomic operation to be possible, there has to be OS support in the form of a transactional file system. And none of the mainstream operating system offer a transactional file system.\nEDIT - I'm wrong for POSIX-compliant systems at least. The POSIX rename syscall p... | [
13,
7,
3,
2,
1,
1,
1
] | [] | [] | [
"file",
"file_io",
"java",
"python"
] | stackoverflow_0002049247_file_file_io_java_python.txt |
Q:
programmatically converting kml to image
Are there any open source libraries (preferably python) that will convert a kml file to an image file?
I have an open source web-based application that allows users to draw shapes on a Google Earth Map, and I would like to provide them with a pdf that contains their map w... | programmatically converting kml to image | Are there any open source libraries (preferably python) that will convert a kml file to an image file?
I have an open source web-based application that allows users to draw shapes on a Google Earth Map, and I would like to provide them with a pdf that contains their map with the shapes that they have drawn.
Right n... | [
"I recently did something like this with Mapnik. After installing Mapnik with all optional packages, this Python script can export a path from a KML file to a PDF or bitmap graphic:\n#!/usr/bin/env python\n\nimport mapnik\nimport cairo\n\nm = mapnik.Map(15000, 15000, \"+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +... | [
6,
3,
0,
0
] | [
"It's not really a question of \"convert\"; KML's can hold all sorts of things - polygons, icons, links, info, etc. \nHowever, KML is XML, so there's no reason why you couldn't parse the KML file with something like expat or etree to extract the polygon definitions. From there you could (for example) draw them on a... | [
-1
] | [
"google_earth",
"kml",
"open_source",
"python"
] | stackoverflow_0003568458_google_earth_kml_open_source_python.txt |
Q:
Python DNS server with custom backend
Is there any DNS server written in python where I can easily use a custom backend?
Basically, I just want to answer look-ups for some domain names with my own IPs, but pass the rest of the look-ups on to a real DNS server.
A:
I wrote such a thing recently, maybe you can use ... | Python DNS server with custom backend | Is there any DNS server written in python where I can easily use a custom backend?
Basically, I just want to answer look-ups for some domain names with my own IPs, but pass the rest of the look-ups on to a real DNS server.
| [
"I wrote such a thing recently, maybe you can use it as an example. It uses a DHT as the backend and looks up all .kad domains there. If you simply replace the P2PMapping with your own mapping (ie a dict like {'google.com' : '127.0.0.1'}) it should do what you want.\n\"\"\"\nCreated on 16.08.2010\n\n@author: Jochen... | [
13,
5,
4
] | [] | [] | [
"dns",
"python"
] | stackoverflow_0004399512_dns_python.txt |
Q:
How to use Python iterators elegantly
I am trying to use iterators more for looping since I heard it is faster than index looping. One thing I am not sure is about how to treat the end of the sequence nicely. The way I can think of is to use try and except StopIteration, which looks ugly to me.
To be more concrete... | How to use Python iterators elegantly | I am trying to use iterators more for looping since I heard it is faster than index looping. One thing I am not sure is about how to treat the end of the sequence nicely. The way I can think of is to use try and except StopIteration, which looks ugly to me.
To be more concrete, suppose we are asked to print the merged ... | [
"I think handling a and b more symmetrically would make it easier to read. Also, using the built-in next function in Python 2.6 with a default value avoids the need to handle StopIteration:\ndef merge(a, b):\n \"\"\"Merges two iterators a and b, returning a single iterator that yields\n the elements of a and... | [
9,
6,
0
] | [] | [] | [
"iterator",
"loops",
"python"
] | stackoverflow_0004407157_iterator_loops_python.txt |
Q:
call dbus method on proxy without blocking (or no timeout)
I'm trying to lock my GNOME screensaver, however the dbus .Lock method is waiting for a response. I would like it to not wait for a response (just send the signal to lock the screensaver, and continue on with life). How do I do this? (In practice this code... | call dbus method on proxy without blocking (or no timeout) | I'm trying to lock my GNOME screensaver, however the dbus .Lock method is waiting for a response. I would like it to not wait for a response (just send the signal to lock the screensaver, and continue on with life). How do I do this? (In practice this code is in a thread so I continue on with life, but I still get the ... | [
"Bah. Solution: http://dbus.freedesktop.org/doc/dbus-python/doc/tutorial.html#making-asynchronous-method-calls\n"
] | [
4
] | [] | [] | [
"dbus",
"python"
] | stackoverflow_0004408091_dbus_python.txt |
Q:
Python, SUM of multiply
My code:
import heapq
def makeHuffTree(symbolTupleList):
trees = list(symbolTupleList)
heapq.heapify(trees)
while len(trees) > 1:
childR, childL = heapq.heappop(trees), heapq.heappop(trees)
parent = (childL[0] + childR[0], childL, childR)
heapq.heappush(trees, p... | Python, SUM of multiply | My code:
import heapq
def makeHuffTree(symbolTupleList):
trees = list(symbolTupleList)
heapq.heapify(trees)
while len(trees) > 1:
childR, childL = heapq.heappop(trees), heapq.heappop(trees)
parent = (childL[0] + childR[0], childL, childR)
heapq.heappush(trees, parent)
return trees[0]
d... | [
"I think I see what you're after. First, I found it useful to convert your frequency table to a dictionary, thus:\nfreqs = dict([(b,a) for (a,b) in exampleData])\n\nThen you can pass this to the function that prints out the tree traversal. I modified your function to use this frequency data and track the sum:\nde... | [
0
] | [] | [] | [
"python",
"sum",
"text"
] | stackoverflow_0004407904_python_sum_text.txt |
Q:
How to build a decorator with optional parameters?
I would like to make a decorator which could be used with or without a parameter :
Something like this :
class d(object):
def __init__(self,msg='my default message'):
self.msg = msg
def __call__(self,fn):
def newfn():
print self... | How to build a decorator with optional parameters? | I would like to make a decorator which could be used with or without a parameter :
Something like this :
class d(object):
def __init__(self,msg='my default message'):
self.msg = msg
def __call__(self,fn):
def newfn():
print self.msg
return fn()
return newfn
@d('T... | [
"I found an example, you can use @trace or @trace('msg1','msg2'): nice!\ndef trace(*args):\n def _trace(func):\n def wrapper(*args, **kwargs):\n print enter_string\n func(*args, **kwargs)\n print exit_string\n return wrapper\n if len(args) == 1 and callable(args[... | [
53,
28,
17,
14,
5
] | [] | [] | [
"decorator",
"python"
] | stackoverflow_0003931627_decorator_python.txt |
Q:
Python appears to be dying before it finishes looping through these Hex values. How fix?
def generate_macs():
for i in xrange(0x000000, 0xFFFFFF + 1):
mac = hex(0x000000 + i)[2:].upper()
mac = [mac[x:x + 2] for x in range(0, len(mac), 2)]
yield ':'.join(mac)
for mac in generate_macs()... | Python appears to be dying before it finishes looping through these Hex values. How fix? | def generate_macs():
for i in xrange(0x000000, 0xFFFFFF + 1):
mac = hex(0x000000 + i)[2:].upper()
mac = [mac[x:x + 2] for x in range(0, len(mac), 2)]
yield ':'.join(mac)
for mac in generate_macs():
print 'E8:06:88:{0}'.format(mac)
I'm trying to generate a list of the MAC addresses bet... | [
"First, your generator function there doesn't output a full MAC address before it gets to the third digit; I solved that by using the following code:\ndef generate_macs_2():\n for a in range(0, 0x100):\n for b in range(0, 0x100):\n for c in range(0, 0x100):\n yield \"{0:02X}:{1:0... | [
5,
2,
0,
0,
0
] | [] | [] | [
"loops",
"memory",
"python"
] | stackoverflow_0004405909_loops_memory_python.txt |
Q:
python, dynamically implement a class onthefly
this is related to python, dynamically implement a class onthefly.
when i restarted my pc, couldnt get back to add comments to the post - below is an example to explain what meant by save the class_with_the_methods_used
class bank(object):
def __init__(self, bal=0)... | python, dynamically implement a class onthefly | this is related to python, dynamically implement a class onthefly.
when i restarted my pc, couldnt get back to add comments to the post - below is an example to explain what meant by save the class_with_the_methods_used
class bank(object):
def __init__(self, bal=0):
self.bal = bal
def deposit(self, amount)... | [
"Check out the new module (http://docs.python.org/library/new.html)\nIt has a lot of tools for doing things dynamically. The problem you are having is debit is not a instance method, it is just a normal function. Methods defined in classes are different than functions defined outside.\n",
"This is due to the way ... | [
1,
1
] | [] | [] | [
"methods",
"python"
] | stackoverflow_0004408950_methods_python.txt |
Q:
Python+sqlite: the LIKE query with wildcards
Hi
I'm trying to search an SQlite table based on a user input with wildcards. I've tried different methods by I can't get it to work.
This is the last thing I tried, it's a solution I found here actually, but it might have changed in python 3.
search = input("type n... | Python+sqlite: the LIKE query with wildcards | Hi
I'm trying to search an SQlite table based on a user input with wildcards. I've tried different methods by I can't get it to work.
This is the last thing I tried, it's a solution I found here actually, but it might have changed in python 3.
search = input("type name or partial name: ")
cur.execute("select * ... | [
"Your problem just seems to be that you have supplied a string as the second argument to cur.execute, when you probably meant to supply a single-element tuple containing the string.\nSince a string is a sequence, every character in the string will be interpreted as a separate parameter and that's why you see the \"... | [
18
] | [] | [] | [
"database",
"python",
"sqlite"
] | stackoverflow_0004409539_database_python_sqlite.txt |
Q:
Managing users data in app engine
I'm writing some Google App Egnine + Android service for self and my friends.
For each user this service will ask AuthSub token for another Google services.
And by cron will retrieve information from this services and send it via c2dm on their cell phones.
I need somewhere store ... | Managing users data in app engine |
I'm writing some Google App Egnine + Android service for self and my friends.
For each user this service will ask AuthSub token for another Google services.
And by cron will retrieve information from this services and send it via c2dm on their cell phones.
I need somewhere store user information and auth sub token fo... | [
"In order to store information in app-engine you need to use the Datastore.\nSee here of an example. You probably need to create a model with two string properties, the google id and the auth token.\n"
] | [
3
] | [] | [] | [
"authsub",
"cron",
"google_app_engine",
"python"
] | stackoverflow_0004409470_authsub_cron_google_app_engine_python.txt |
Q:
Having issues while downloading favicon using python script
I am using a script to crawl and download favicons from websites. Some sites gave me 2-3 favicon images of various sizes (16x16, 32x32) etc..embedded in the same image. When I try to use this image it is not displaying properly as a favicon. Is there anyt... | Having issues while downloading favicon using python script | I am using a script to crawl and download favicons from websites. Some sites gave me 2-3 favicon images of various sizes (16x16, 32x32) etc..embedded in the same image. When I try to use this image it is not displaying properly as a favicon. Is there anything that I can do to make sure I download a proper image?
| [
"That's a feature of the ico file format. They're perfectly valid files, but you're going to need to process them with something that actually understands Windows Icon files.\n"
] | [
1
] | [] | [] | [
"favicon",
"html",
"python",
"web_crawler"
] | stackoverflow_0004409789_favicon_html_python_web_crawler.txt |
Q:
the Eval function in Python
Hello there i have the following code:
path = some destination on your harddrive
def K(path):
try:
getfile = open(path + '/test.txt')
line = getfile.readlines()
print line
getfile.close()
except:
line = getfile.readlines()
eval(l... | the Eval function in Python | Hello there i have the following code:
path = some destination on your harddrive
def K(path):
try:
getfile = open(path + '/test.txt')
line = getfile.readlines()
print line
getfile.close()
except:
line = getfile.readlines()
eval(line)
d = dict()
v... | [
"Hint: \n>>> float(\"\\n1234\\n\")\n1234.0\n\n",
"your code is quite confused... to read a file that contains one float per line you can simply do:\nval = map(float, open(\"test.txt\"))\n\nval will be a list containing your data with each element being a float\n",
"I won't comment your code, just will post an e... | [
2,
1,
1,
0,
0
] | [] | [] | [
"eval",
"python"
] | stackoverflow_0004407433_eval_python.txt |
Q:
Need some Python datetime magic
Hey all. I don't think this should be very complicated but I just can't get it. I have a list of datetime objects starting at a certain date and ending at one. Some days can be skipped. I can print them out like this:
for entry in dates:
print entry
Which gives me the following... | Need some Python datetime magic | Hey all. I don't think this should be very complicated but I just can't get it. I have a list of datetime objects starting at a certain date and ending at one. Some days can be skipped. I can print them out like this:
for entry in dates:
print entry
Which gives me the following output:
2010-11-29 10:00:00.0
2010-1... | [
"Here is a way to do this by converting your datetimes to dates. Rather than try to iterate over the dates themselves, we take a timedelta of the last date and the first date (this requires your dates to be sorted, I added a sorted call in case they aren't). Then we see if the first date plus the number of days is ... | [
9,
5
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0004409549_datetime_python.txt |
Q:
Numpy *.npz internal file structure
can anyone share some info about internal data organization in *.npz ?
Some documentation etc..
Just can't find anything..
A:
Here are the docs:
Format of .npz files, referring to the
Format of .npy files
That said, I would not recommend trying to read or write files in this... | Numpy *.npz internal file structure | can anyone share some info about internal data organization in *.npz ?
Some documentation etc..
Just can't find anything..
| [
"Here are the docs:\n\nFormat of .npz files, referring to the\nFormat of .npy files\n\nThat said, I would not recommend trying to read or write files in this format yourself. It's fine for writing from NumPy and reading in with NumPy again. But if you want to write or read a file from a different environment, the... | [
21,
6
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0004409551_numpy_python.txt |
Q:
SQLAlchemy set index on coalesce
I am trying to set up an index for a table on the coalesce function, rather than on a column. I am using PostgreSQL and I am trying to achieve something like :
create index t on tbl using btree (coalesce(ts_updated, '2002-08-08'))
Anyone knows how can I achieve this with SQLAlchemy... | SQLAlchemy set index on coalesce | I am trying to set up an index for a table on the coalesce function, rather than on a column. I am using PostgreSQL and I am trying to achieve something like :
create index t on tbl using btree (coalesce(ts_updated, '2002-08-08'))
Anyone knows how can I achieve this with SQLAlchemy in the ORM framework?
| [
"SQLAlchemy doesn't support expression in index definitions yet, but it's a planned feature. Right now you have to use custom DDL (see examples in documentation).\n"
] | [
3
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0004407031_python_sqlalchemy.txt |
Q:
Close to serial textfile reading performance in MySQL
I am trying to perform some n-gram counting in python and I thought I could use MySQL (MySQLdb module) for organizing my text data.
I have a pretty big table, around 10mil records, representing documents that are indexed by a unique numeric id (auto-increment) ... | Close to serial textfile reading performance in MySQL | I am trying to perform some n-gram counting in python and I thought I could use MySQL (MySQLdb module) for organizing my text data.
I have a pretty big table, around 10mil records, representing documents that are indexed by a unique numeric id (auto-increment) and by a language varchar field (e.g. "en", "de", "es" etc.... | [
"You can use the HANDLER statement to traverse a table (or index) in chunks. This is not very portable and works in an \"interesting\" way with transactions if rows appear and disappear while you're looking at it (hint: you're not going to get consistency) but makes code simpler for some applications.\nIn general, ... | [
1,
0,
0
] | [] | [] | [
"mysql",
"n_gram",
"python",
"serial_processing",
"text_processing"
] | stackoverflow_0004409885_mysql_n_gram_python_serial_processing_text_processing.txt |
Q:
Pure python cross-platform font renderer?
I'm looking for a pure Python font renderer. I don't need it to render to anything special, I just need the pixel colors/alpha. I'm using PIL right now, but I am not sure if it needs to hook into any system libraries that may not be installed.
Pyglet manages this, somehow... | Pure python cross-platform font renderer? | I'm looking for a pure Python font renderer. I don't need it to render to anything special, I just need the pixel colors/alpha. I'm using PIL right now, but I am not sure if it needs to hook into any system libraries that may not be installed.
Pyglet manages this, somehow, but I wasn't able to determine the relevant c... | [
"Pyglet uses FreeType where available. I'd stick with that, even though it's not pure Python.\n",
"ReportLab can render to pixmaps:\nhttp://www.reportlab.com/apis/reportlab/2.4/graphics.html#module-reportlab.graphics.renderPM\nprobably a bit heavyweight for your needs though.\n"
] | [
4,
0
] | [] | [] | [
"fonts",
"python"
] | stackoverflow_0004410208_fonts_python.txt |
Q:
Custom multivaluefield isn't displayed in empty form
I'm trying to build a custom multivaluewidget in my django app.
Widget
class DayInputWidget(MultiWidget):
def __init__(self, attrs=None):
widgets = (DayInput(day_name='Mo'), DayInput(day_name='Di'), DayInput(day_name='Mi'), DayInput(day_name='Do'), ... | Custom multivaluefield isn't displayed in empty form | I'm trying to build a custom multivaluewidget in my django app.
Widget
class DayInputWidget(MultiWidget):
def __init__(self, attrs=None):
widgets = (DayInput(day_name='Mo'), DayInput(day_name='Di'), DayInput(day_name='Mi'), DayInput(day_name='Do'), DayInput(day_name='Fr'))
super(DayInputWidget, sel... | [
"Try the following: in your widget class, rewrite your decompress method, so that it does not return None, but []:\nclass DayInputWidget(MultiWidget):\ndef __init__(self, attrs=None):\n widgets = (DayInput(day_name='Mo'), DayInput(day_name='Di'), DayInput(day_name='Mi'), DayInput(day_name='Do'), DayInput(day_nam... | [
0
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0003747609_django_django_forms_python.txt |
Q:
How to make text strikethough in Sphinx
Is it possible to make text strikethrough in the Sphinx documentation generator?
A:
I've done this.
Require a .CSS in your conf.py
html_style = 'mydoc.css'
In the _static/mydoc.css, use something like this
@import url("default.css");
span.strikethrough { text-decoration:... | How to make text strikethough in Sphinx | Is it possible to make text strikethrough in the Sphinx documentation generator?
| [
"I've done this.\nRequire a .CSS in your conf.py\nhtml_style = 'mydoc.css'\n\nIn the _static/mydoc.css, use something like this\n@import url(\"default.css\");\n\nspan.strikethrough { text-decoration: line-through; }\n\nIn the document, do this.\n .. role:: strikethrough\n\n make text :strikethrough:`strikethrough`... | [
10
] | [] | [] | [
"python",
"python_sphinx",
"strikethrough"
] | stackoverflow_0004410100_python_python_sphinx_strikethrough.txt |
Q:
django forms not accepting request.user
I am trying to access request.user or get the current logged in user in order to filter content by the user ie only get the trophies or bag_list by the logged-in user.
my forms has a mixture or elements as seen below.
class HuntingReportForm(ModelForm):
date_travel_start... | django forms not accepting request.user | I am trying to access request.user or get the current logged in user in order to filter content by the user ie only get the trophies or bag_list by the logged-in user.
my forms has a mixture or elements as seen below.
class HuntingReportForm(ModelForm):
date_travel_started = forms.DateField(widget=extras.SelectDate... | [
"If you initialize the form with HuntingReportFrom(user=request.user), this should work:\n def __init__(self, *args, **kwargs):\n self.user = kwargs.pop('user', None)\n self.validate = kwargs.pop('validate', False)\n super(HuntingReportForm, self).__init__(*args, **kwargs)\n self.fields[... | [
7
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0004409133_django_django_forms_python.txt |
Q:
The use of $TM_FILEPATH with Python in TextMate
I'm making a TextMate command with python. The job is to get the current file name, get the html file name by changing the extension name, and run safari to open the html file.
#!/usr/bin/env python
import os.path
import os
oldName = $TM_FILEPATH
(name, ext) = os.pa... | The use of $TM_FILEPATH with Python in TextMate | I'm making a TextMate command with python. The job is to get the current file name, get the html file name by changing the extension name, and run safari to open the html file.
#!/usr/bin/env python
import os.path
import os
oldName = $TM_FILEPATH
(name, ext) = os.path.splitext(oldName)
rename = name + ".html"
os.syste... | [
"import os\nos.environ[\"TM_FILEPATH\"]\n\n(os.environ is how you access environment variables in Python. It's a dictionary-like object.)\n",
"You probably want os.environ['TM_FILEPATH'] instead.\n"
] | [
2,
1
] | [] | [] | [
"python",
"textmate"
] | stackoverflow_0004411116_python_textmate.txt |
Q:
Convert commented out print statements to logging calls - Python
I'm hacking on a framwork right now, and I'd like to use logging. However, the developers of the framework have been using print statements to debug, and they are all commented out for the production release. I was wondering, does anyone know of a re... | Convert commented out print statements to logging calls - Python | I'm hacking on a framwork right now, and I'd like to use logging. However, the developers of the framework have been using print statements to debug, and they are all commented out for the production release. I was wondering, does anyone know of a regex to find these, and convert them to logging calls.
This is what I w... | [
"If you want to do it in Python, consider using the fileinput module:\nimport fileinput\nimport sys\nimport re\n\ndef convert(paths):\n for line in fileinput.input(paths, inplace=True, backup='~'):\n line=re.sub(r'#\\s*print\\s*(.*)',r'logging.debug(\\1)',line)\n sys.stdout.write(line)\n\nif __name... | [
3,
1,
1,
0
] | [] | [] | [
"debugging",
"logging",
"python",
"regex"
] | stackoverflow_0004410450_debugging_logging_python_regex.txt |
Q:
Smart filter with python
Hi
I need filter out all rows that don't contain symbols from huge "necessary" list, example code:
def any_it(iterable):
for element in iterable:
if element: return True
return False
regexp = re.compile(r'fruit=([A-Z]+)')
necessary = ['YELLOW', 'GREEN', 'RED', ...] #... | Smart filter with python | Hi
I need filter out all rows that don't contain symbols from huge "necessary" list, example code:
def any_it(iterable):
for element in iterable:
if element: return True
return False
regexp = re.compile(r'fruit=([A-Z]+)')
necessary = ['YELLOW', 'GREEN', 'RED', ...] # huge list of 10 000 members
f... | [
"If you organized the necessary list as a trie, then you could look in that trie to check if the fruit starts with a valid prefix. That should be faster than comparing the fruit against every prefix.\nFor example (only mildly tested):\nimport bisect\nimport re\n\nclass Node(object):\n def __init__(self):\n ... | [
5,
1,
1,
1,
1,
1,
0,
0
] | [] | [] | [
"filter",
"optimization",
"python",
"python_2.4",
"text"
] | stackoverflow_0004397859_filter_optimization_python_python_2.4_text.txt |
Q:
Twisted, gevent eventlet - When would I use them
Under what circumstances would something like eventlet/gevent be better than twisted? Twisted seems like the most used, but eventlet/gevent must have some advantages...
I'm not looking for an answer to a specific scenario, just generalities.
A:
It's an issue of ae... | Twisted, gevent eventlet - When would I use them | Under what circumstances would something like eventlet/gevent be better than twisted? Twisted seems like the most used, but eventlet/gevent must have some advantages...
I'm not looking for an answer to a specific scenario, just generalities.
| [
"It's an issue of aesthetic preference, I think.\nFirst of all, eventlet can actually use Twisted for networking, so in a sense, it's not an either-or question, it's a this-is-built-on-top-of-that question.\nPersonally, I don't see the need for libraries like gevent or eventlet, especially since the advent of the @... | [
10
] | [] | [] | [
"eventlet",
"gevent",
"python",
"twisted"
] | stackoverflow_0004405667_eventlet_gevent_python_twisted.txt |
Q:
Python Find Forward Slash in a String
I am a beginner to Python so bear with me.
Basically I am searching a particular table cell for the forward slash character. If the cell contains that character, I want to delete the entire row.
counter = 0
for row in table:
if row[7].find("/") != -1:
del table[co... | Python Find Forward Slash in a String | I am a beginner to Python so bear with me.
Basically I am searching a particular table cell for the forward slash character. If the cell contains that character, I want to delete the entire row.
counter = 0
for row in table:
if row[7].find("/") != -1:
del table[counter]
continue
counter+=1
The... | [
"There's so many things wrong with that code it's easier to just re-write it.\ntable[:] = [row for row in table if '/' not in row[7]]\n\n"
] | [
4
] | [
"Could you not just maybe do..\nfor row in table:\n if '/' in row[7]:\n row.delete()\n\nOr if you really need the counter to del the row from the table, then just put the counter back in.\n"
] | [
-2
] | [
"python"
] | stackoverflow_0004411370_python.txt |
Q:
ImageOps Module missing in PIL?
I am trying to save images in Django and getting the error "The ImageOps module could not be imported"
For some reason I am unable to import or use the ImageOps Module from PIL in the django shell. I have tried deleting the egg and reinstalling PIL but that doesn't work. I looked in... | ImageOps Module missing in PIL? | I am trying to save images in Django and getting the error "The ImageOps module could not be imported"
For some reason I am unable to import or use the ImageOps Module from PIL in the django shell. I have tried deleting the egg and reinstalling PIL but that doesn't work. I looked inside the egg and ImageOps.py is there... | [
"The problem was being caused by django StdImageField. In site-packages/stdimage/fields.py line 71 I changed\nfrom PIL import Image, ImageOps\n\nto:\nimport Image, ImageOps\n\nNow everything works fine. \n"
] | [
5
] | [] | [] | [
"django",
"python",
"python_imaging_library"
] | stackoverflow_0004411643_django_python_python_imaging_library.txt |
Q:
When to use pack or grid layouts in tkinter?
Are there any best practice tips regarding when one should use pack vs. grid for their layouts?
From what I've been reading via google, the concencus seems to be that grid can handle any pack scenario but not vice-versa.
To start the conversation, it appears that one us... | When to use pack or grid layouts in tkinter? | Are there any best practice tips regarding when one should use pack vs. grid for their layouts?
From what I've been reading via google, the concencus seems to be that grid can handle any pack scenario but not vice-versa.
To start the conversation, it appears that one use case that favors grid vs. pack is when one wants... | [
"Neither is intrinsically better than the other. Each have strengths and weaknesses. Learn what those are and the choice of which to use becomes obvious.\ngrid is considerably easier to use if you need to lay things out in a grid. pack is generally easier to use if all you need to do is put some widgets in a single... | [
19,
10,
2
] | [] | [] | [
"layout",
"python",
"tkinter",
"ttk",
"user_interface"
] | stackoverflow_0004401202_layout_python_tkinter_ttk_user_interface.txt |
Q:
Forcing urlparse.urlsplit to preserve str case
Is there any way to force urlparse's urlsplit function to preserve the case of the str passed in? It preserves the case of the path in the returned tuple, but not of the netloc, and this is important to me. (I know domain names are case-insensitive, but, we're doing s... | Forcing urlparse.urlsplit to preserve str case | Is there any way to force urlparse's urlsplit function to preserve the case of the str passed in? It preserves the case of the path in the returned tuple, but not of the netloc, and this is important to me. (I know domain names are case-insensitive, but, we're doing some A/B testing with different capitalizations of th... | [
"There's no way to force urlsplit to do that.\nYou can, however, wrap it and then do some dirty work to restore case, or copy the source code and do the modification yourself. Or write the function from scratch, of course.\nI'd go for the second option.\n"
] | [
1
] | [] | [] | [
"python",
"urlparse"
] | stackoverflow_0004411980_python_urlparse.txt |
Q:
PyQt: current directory in QFileSystemModel
I am using following code from some official example:
model = QFileSystemModel()
model.setRootPath(QDir.currentPath())
view = QTreeView(parent=self);
view.setModel(model)
I expected it to expand directory structure in the tree view so dir... | PyQt: current directory in QFileSystemModel | I am using following code from some official example:
model = QFileSystemModel()
model.setRootPath(QDir.currentPath())
view = QTreeView(parent=self);
view.setModel(model)
I expected it to expand directory structure in the tree view so directory from which my program is run would be disp... | [
"You would have to use QTreeView.expand.\n"
] | [
0
] | [] | [] | [
"pyqt",
"python",
"qfilesystemmodel"
] | stackoverflow_0004411331_pyqt_python_qfilesystemmodel.txt |
Q:
Get Mouse Double Click with pyHook
I'm trying to get Mouse Double Clicks with pyHook, but instead I'm getting two pair entries of single clicks e.g. WM_LBUTTONDOWN (0x201) and WM_LBUTTONUP (0x202) . I'm expecting WM_LBUTTONDBLCLK (0x203). What am I misssing here?
import pythoncom, pyHook
def OnMouseEvent(event... | Get Mouse Double Click with pyHook | I'm trying to get Mouse Double Clicks with pyHook, but instead I'm getting two pair entries of single clicks e.g. WM_LBUTTONDOWN (0x201) and WM_LBUTTONUP (0x202) . I'm expecting WM_LBUTTONDBLCLK (0x203). What am I misssing here?
import pythoncom, pyHook
def OnMouseEvent(event):
print event.Message, e... | [
"The reason why you are getting two WM_LBUTTONDOWN and WM_LBUTTONUP and no WM_LBUTTONDBLCLK is because of what MrZebra says: the target window class' style does not include the CS_DBLCLKS style. Unless you can modify the source code for the target window class, it will never receive WM_LBUTTONDBLCLK, because Window... | [
1
] | [] | [] | [
"c#",
"c++",
"python",
"winapi"
] | stackoverflow_0004390845_c#_c++_python_winapi.txt |
Q:
How do I treat django's TemporaryUploadedFile as a regular python file
How can I do this? I notice that when you upload a file in django you access it as a TemporaryUploadedFile.
http://docs.djangoproject.com/en/dev/topics/http/file-uploads/
There is a method here that gives you the filename if django wrote it to ... | How do I treat django's TemporaryUploadedFile as a regular python file | How can I do this? I notice that when you upload a file in django you access it as a TemporaryUploadedFile.
http://docs.djangoproject.com/en/dev/topics/http/file-uploads/
There is a method here that gives you the filename if django wrote it to disk. Then you could open it as a standard python file. However, django does... | [
"If you need something with a file descriptor then you'll have to use os.pipe(). If it just needs a file-like then passing it what you have will do.\n"
] | [
0
] | [] | [] | [
"django",
"file",
"file_upload",
"python"
] | stackoverflow_0004412748_django_file_file_upload_python.txt |
Q:
Flash sockets with python server
I'm try to send and get data using sockets between Adobe flash client and python server.
Flash client:
var serverURL = "se.rv.er.ip";
var xmlSocket:XMLSocket = new XMLSocket();
xmlSocket.connect(serverURL, 50007);
xmlSocket.addEventListener(DataEvent.DATA, onIncomingData);
functi... | Flash sockets with python server | I'm try to send and get data using sockets between Adobe flash client and python server.
Flash client:
var serverURL = "se.rv.er.ip";
var xmlSocket:XMLSocket = new XMLSocket();
xmlSocket.connect(serverURL, 50007);
xmlSocket.addEventListener(DataEvent.DATA, onIncomingData);
function onIncomingData(event:DataEvent):voi... | [
"You shouldn't use the socket module if you don't have to. Use SocketServer when you want, well, a socket server.\nimport SocketServer\n\nclass MyTCPHandler(SocketServer.BaseRequestHandler):\n def handle(self):\n # self.request is the TCP socket connected to the client\n self.data = self.re... | [
1
] | [] | [] | [
"flash",
"python",
"sockets"
] | stackoverflow_0004410463_flash_python_sockets.txt |
Q:
Using Python or Other Scripting Language With IIOP
I have a java version of an IIOP client but I am having all sorts of issues with connectivity. I would like to build the client in python but haven't found anything that would let me. Is there such a thing?
A:
omniORB supports Python.
| Using Python or Other Scripting Language With IIOP | I have a java version of an IIOP client but I am having all sorts of issues with connectivity. I would like to build the client in python but haven't found anything that would let me. Is there such a thing?
| [
"omniORB supports Python.\n"
] | [
1
] | [] | [] | [
"iiop",
"python"
] | stackoverflow_0004411943_iiop_python.txt |
Q:
Why can't date and regexes in Python be as succinct as they are in JS?
Why is datetime a "child" of itself? Why is it datetime.datetime.now instead of datetime.now?
Why can't I use regex literals like in Javascript? EG /foo/.test('foo')
A:
datetime is a python module that contains datetime class that has a meth... | Why can't date and regexes in Python be as succinct as they are in JS? |
Why is datetime a "child" of itself? Why is it datetime.datetime.now instead of datetime.now?
Why can't I use regex literals like in Javascript? EG /foo/.test('foo')
| [
"datetime is a python module that contains datetime class that has a method now.\nI agree with you datetime.datetime only looks ugly because the module and class have the same name . I have myself been stumped at times due to this specific issue.\nI have mostly incorporated the class directly in my module by doing... | [
3,
1,
0,
0,
0
] | [] | [] | [
"javascript",
"python"
] | stackoverflow_0004412461_javascript_python.txt |
Q:
Python ctypes.cdll.LoadLibrary works differently between 2.6.5 and 2.7.1
I've got a system with both Python version 2.6.5 and 2.7.1 and I'm noticing that one LoadLibrary works, the other does not.
Python 2.7.1 (r271:86832, Nov 30 2010, 10:03:07)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license... | Python ctypes.cdll.LoadLibrary works differently between 2.6.5 and 2.7.1 | I've got a system with both Python version 2.6.5 and 2.7.1 and I'm noticing that one LoadLibrary works, the other does not.
Python 2.7.1 (r271:86832, Nov 30 2010, 10:03:07)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from ctypes import cdll
>>> cdll.LoadLibrary("./my... | [
"For some reason, Python ctypes gets super anal about library dependencies. I still have no figured out why 2.6.5 was working above, but doing the following fixes it:\nWhen compiling mylib.so, I needed to specify or link to the zlib library explicity. Since \"compress2\" is from the zlib library, I can do it by t... | [
1
] | [] | [] | [
"ctypes",
"loadlibrary",
"python"
] | stackoverflow_0004404974_ctypes_loadlibrary_python.txt |
Q:
minimalistic Java web interface like Pythons WSGI
Python has a minimalistic and elegant web interface called WSGI. The simplest possible application looks like this:
def simple_app(environ, start_response):
status = '200 OK'
response_headers = [('Content-type', 'text/plain')]
start_response(status, res... | minimalistic Java web interface like Pythons WSGI | Python has a minimalistic and elegant web interface called WSGI. The simplest possible application looks like this:
def simple_app(environ, start_response):
status = '200 OK'
response_headers = [('Content-type', 'text/plain')]
start_response(status, response_headers)
return ['Hello world!\n']
environ i... | [
"Using native IO and Network API of java, we can create ServerSocket of java.net package.\n"
] | [
0
] | [] | [] | [
"asp.net_mvc",
"java",
"python",
"servlets",
"wsgi"
] | stackoverflow_0004407698_asp.net_mvc_java_python_servlets_wsgi.txt |
Q:
lxml --pretty_print-- write file problem
I am write a raw data to xml file python program, in my design,we get the raw data line by line,
then write it into xml file like:
`<root>\n
<a> value </a>\n
<b> value </b>\n
</root>
The first time i write into xml file with pretty_print=True, i got what i want, but wh... | lxml --pretty_print-- write file problem | I am write a raw data to xml file python program, in my design,we get the raw data line by line,
then write it into xml file like:
`<root>\n
<a> value </a>\n
<b> value </b>\n
</root>
The first time i write into xml file with pretty_print=True, i got what i want, but when the second
time i read the file, get the el... | [
"You might find the answer in the lxml faq: Why doesn't the pretty_print option reformat my XML output?\n"
] | [
3
] | [] | [] | [
"lxml",
"python"
] | stackoverflow_0004407108_lxml_python.txt |
Q:
Python Most Efficient Way to Search a List
Bear with me as I am very new to Python. Basically I am looking for the most efficient way to search through a multi-dimensional list. So say I have the following list:
fruit = [
[banana, 6],
[apple, 5],
[banana, 9],
[apple, 10],
[pear, 2],
]
And... | Python Most Efficient Way to Search a List | Bear with me as I am very new to Python. Basically I am looking for the most efficient way to search through a multi-dimensional list. So say I have the following list:
fruit = [
[banana, 6],
[apple, 5],
[banana, 9],
[apple, 10],
[pear, 2],
]
And I wanted the outcome of my function to produce:... | [
"That is not in any way a search...\nWhat you want is\nimport collections\n\ndef count(items):\n data = collections.defaultdict(int)\n for kind, count in items:\n data[kind] += count\n return data\n\n",
"fruit = [['banana', 6], ['apple',5], ['banana',9],['apple',10],['pear',2]]\nf = {}\n\ndef frui... | [
9,
3,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004412484_python.txt |
Q:
PyQt4 and 64-bit python
I am trying to get the 64-bit version of python up and running with a program I wrote. That program uses a gui I wrote in PyQt4. I cannot find a 64-bit version of PyQt4 and I get the following error when attempting to use the 32-bit of PyQt4 with the 64-bit version of python:
S:\src>SimLaun... | PyQt4 and 64-bit python | I am trying to get the 64-bit version of python up and running with a program I wrote. That program uses a gui I wrote in PyQt4. I cannot find a 64-bit version of PyQt4 and I get the following error when attempting to use the 32-bit of PyQt4 with the 64-bit version of python:
S:\src>SimLauncher.py
Forcing DISTUTILS_USE... | [
"64 bit PyQt binaries for Windows are available at http://www.lfd.uci.edu/~gohlke/pythonlibs/#pyqt\nUpdate: 64 bit PyQt4 binaries for Windows, including the MySQL extension, are now officially available from Riverbank at http://www.riverbankcomputing.co.uk/software/pyqt/download\n",
"You can install PyQt4 using 6... | [
6,
1
] | [] | [] | [
"64_bit",
"dll",
"pyqt",
"python"
] | stackoverflow_0004381936_64_bit_dll_pyqt_python.txt |
Q:
Efficient way to create a diagonal sparse matrix
I have the following code in Python using Numpy:
p = np.diag(1.0 / np.array(x))
How can I transform it to get the sparse matrix p2 with the same values as p without creating p first?
A:
Use scipy.sparse.spdiags (which does a lot, and so may be confusing, at first... | Efficient way to create a diagonal sparse matrix | I have the following code in Python using Numpy:
p = np.diag(1.0 / np.array(x))
How can I transform it to get the sparse matrix p2 with the same values as p without creating p first?
| [
"Use scipy.sparse.spdiags (which does a lot, and so may be confusing, at first), scipy.sparse.dia_matrix and/or scipy.sparse.lil_diags. (depending on the format you want the sparse matrix in...)\nE.g. using spdiags:\nimport numpy as np\nimport scipy as sp\nimport scipy.sparse\n\nx = np.arange(10)\n\n# \"0\" here in... | [
11,
1
] | [] | [] | [
"numpy",
"python",
"scipy",
"sparse_matrix"
] | stackoverflow_0003695434_numpy_python_scipy_sparse_matrix.txt |
Q:
Python in java, is it possible
I have a class that is written in Java.
Can it be used in Python so i dont have to rewrite it?
A:
JYthon is a python implementation in java , you should check it out
www.jython.org
A:
See this: http://jpype.sourceforge.net/
Might not be worth the trouble, though..
| Python in java, is it possible | I have a class that is written in Java.
Can it be used in Python so i dont have to rewrite it?
| [
"JYthon is a python implementation in java , you should check it out\nwww.jython.org\n",
"See this: http://jpype.sourceforge.net/\nMight not be worth the trouble, though..\n"
] | [
13,
3
] | [] | [] | [
"java",
"python"
] | stackoverflow_0004413763_java_python.txt |
Q:
CSS Selectors: select element where (parent|children) don't match X
I'd like to select an element which has no children of a specific type, for example:
all <li> elements who have no <table class="someclass"> children, I'd like to select only the parent element, not the children that don't match table.
On a simila... | CSS Selectors: select element where (parent|children) don't match X | I'd like to select an element which has no children of a specific type, for example:
all <li> elements who have no <table class="someclass"> children, I'd like to select only the parent element, not the children that don't match table.
On a similar note, I'd like to match elements whose parents don't match X, for examp... | [
"The CSS3 :not selector will get you partly there. Unfortunately, there is no parent selector so you can't select an element based on characteristics of its children.\nFor your first question you have to explicitly do the traversal:\n# All <li> elements who have no <table class=\"someclass\"> children\n[e.getparen... | [
1,
0
] | [] | [] | [
"css",
"css_selectors",
"lxml",
"python"
] | stackoverflow_0004412253_css_css_selectors_lxml_python.txt |
Q:
Django avatar util problem
I've got a django project working on a development server(ubuntu) that we have been working on for a good while. I'm trying to install it now locally on my mac book pro.
I'm relatively new to the Django environment (10 years in LAMP). I tried installing all the relevant packages e.g. so... | Django avatar util problem | I've got a django project working on a development server(ubuntu) that we have been working on for a good while. I'm trying to install it now locally on my mac book pro.
I'm relatively new to the Django environment (10 years in LAMP). I tried installing all the relevant packages e.g. south, django-registration etc.
I'... | [
"It looks like you either have an older (or newer) version of fishpond than django-avatar - fishpond is trying to load up django-avatar's util module, but your version of django-avatar doesn't have a util module. You might want to check and see if there's a certain version of django-avatar that fishpond needs.\n"
] | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004413587_django_python.txt |
Q:
python restart the program after running a method
A noob question I'm sure.
For example, say I have a program that looks something like this.
def method1():
#do something here
def method2():
#do something here
#this is the menu
menu=input("What would you like to do?\ntype 1 for method1 or 2 for method2: ... | python restart the program after running a method | A noob question I'm sure.
For example, say I have a program that looks something like this.
def method1():
#do something here
def method2():
#do something here
#this is the menu
menu=input("What would you like to do?\ntype 1 for method1 or 2 for method2: ")
if(menu=="1"):
method1()
if(menu=="2"):
meth... | [
"while True:\n #this is the menu\n menu=input(\"What would you like to do?\\ntype 1 for method1 or 2 for method2: \")\n if(menu==\"1\"):\n method1()\n if(menu==\"2\"):\n method2()\n\nIf the endless loop \"doesn't feel right\", ask yourself when and why it should end. Should you have a thir... | [
5,
0
] | [] | [] | [
"python"
] | stackoverflow_0004413798_python.txt |
Q:
Interlinking GUI in some other language and Python
I have done coding for mathematical simulation of Theory of Computation concepts in Python such as grammar checking and other stuff. My Problem is that I have to build a decent looking GUI for it .
I have looked at PyQt4 and the lack of documentation is really a b... | Interlinking GUI in some other language and Python | I have done coding for mathematical simulation of Theory of Computation concepts in Python such as grammar checking and other stuff. My Problem is that I have to build a decent looking GUI for it .
I have looked at PyQt4 and the lack of documentation is really a big deterrent. I have looked at other graphical libraries... | [
"I'd look again at PyQT4 if you want something decent looking. PyQt has an an example directory in the source code. KDE uses QT and they have a lot examples too. You have to understand that it is a binding against QT4. When I use it with python I usually just have the QT docs open. Its pretty easy to translate.\nY... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004413692_python.txt |
Q:
Swap keys for unique values in a dictionary in Python
a = {0: 'PtpMotion', 1: 'PtpMotion', 2: 'LinMotion', 3: 'LinMotion', 4: 'LinMotion', 5: 'LinMotion', 6: 'LinMotion', 7: 'LinMotion', 8: 'LinMotion', 9: 'PtpMotion', 10: 'LinMotion', 11: 'Wait'}
b = {}
for key, val in a.items():
b[val] = key
print b
What I ... | Swap keys for unique values in a dictionary in Python | a = {0: 'PtpMotion', 1: 'PtpMotion', 2: 'LinMotion', 3: 'LinMotion', 4: 'LinMotion', 5: 'LinMotion', 6: 'LinMotion', 7: 'LinMotion', 8: 'LinMotion', 9: 'PtpMotion', 10: 'LinMotion', 11: 'Wait'}
b = {}
for key, val in a.items():
b[val] = key
print b
What I am trying to do is to swap value of the dictionary for key.... | [
"Each key can only occur once in a dictionary. You could store a list of indices for each key:\nimport collections\nb = collections.defaultdict(list)\nfor key, val in a.iteritems():\n b[val].append(key)\nprint b\n# {'LinMotion': [2, 3, 4, 5, 6, 7, 8, 10], 'PtpMotion': [0, 1, 9], 'Wait': [11]}\n\nEdit: As pointe... | [
4,
2,
1,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0004413976_dictionary_python.txt |
Q:
python give option if user inputs string
I'm using Python 2.6.6
I have this code:
height = 20
width = 10
x = input('Please insert a number between ' + str(width + 1) + ' and ' + str(height) + ': ')
while x < (width + 1) or x > 20:
print 'That option is not valid'
x = input('Please insert a number between... | python give option if user inputs string | I'm using Python 2.6.6
I have this code:
height = 20
width = 10
x = input('Please insert a number between ' + str(width + 1) + ' and ' + str(height) + ': ')
while x < (width + 1) or x > 20:
print 'That option is not valid'
x = input('Please insert a number between ' + str(width + 1) + ' and ' + str(height) + ... | [
"You must use raw_input instead of input in Python 2.x. input assumes that the user is inputting valid Python to be evaluated. Your best bet is to take the string input and then convert it as needed. In this case, you will want to try converting with int.\nJust as a reminder, from the documentation:\n\ninput([pr... | [
5
] | [] | [] | [
"python"
] | stackoverflow_0004413975_python.txt |
Q:
I have a MySQL database, I want to write an interface for it using Python. Help me get started, please!
The question pretty much says it all. The database is in MySQL using phpMyAdmin.
A little background: I'm writing the interface for a small non-profit organization. They need to be able to see which customer... | I have a MySQL database, I want to write an interface for it using Python. Help me get started, please! | The question pretty much says it all. The database is in MySQL using phpMyAdmin.
A little background: I'm writing the interface for a small non-profit organization. They need to be able to see which customers to ship to this month, which customers have recurring orders, etc. The current system is ancient, written ... | [
"I strongly advise you to take a look at SQLAlchemy, which is a fantastic python ORM that wraps nicely over existing schemas without a terrible level of pain. You could connect that to the framework of your choice, for instance Pylons has support for SQLAlchemy as a backend. \n",
"What can I say? Just download ... | [
1,
0,
0
] | [] | [] | [
"mysql",
"php",
"phpmyadmin",
"python"
] | stackoverflow_0004413840_mysql_php_phpmyadmin_python.txt |
Q:
How to find recurring patterns on a hexdump?
I need to find recurring patterns from an hexdump output.
Every line in my output file is something like:
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
Where 00 is a byte in hexadecimal.
The patterns aren't of fixed length but they always lie in one line.
I have an i... | How to find recurring patterns on a hexdump? | I need to find recurring patterns from an hexdump output.
Every line in my output file is something like:
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
Where 00 is a byte in hexadecimal.
The patterns aren't of fixed length but they always lie in one line.
I have an idea on how to do this but I'd like to know what wo... | [
"It is not apparent whether you know the substrings that you want to search for, or whether you need to discover a set of query substrings first. I think that discovery can be achieved by finding frequently occurring n-grams. One you have your set of query substrings, you can proceed to where they are, and how far ... | [
1
] | [] | [] | [
"design_patterns",
"python"
] | stackoverflow_0004406560_design_patterns_python.txt |
Q:
Python: Two Windows Opening
ok so for the past two weeks or so, ive been learning python as it is extremely simple to comprehend and a very handy method of creating a GUI for a program. However i have three problems.
First, when i open my .py file a command window opens , and then my program opens on top of that.... | Python: Two Windows Opening | ok so for the past two weeks or so, ive been learning python as it is extremely simple to comprehend and a very handy method of creating a GUI for a program. However i have three problems.
First, when i open my .py file a command window opens , and then my program opens on top of that. Is there a way to just open the ... | [
"To keep the command window from opening, you can save it as a .pyw file, as opposed to the usual .py. As for converting to exe, py2exe works best for me, I know there are several others, but not as fully developed as py2exe is. Python.org should contain a list of most modules. The same results could easily be proc... | [
3,
0
] | [] | [] | [
"python",
"user_interface"
] | stackoverflow_0004414102_python_user_interface.txt |
Q:
What's the easiest way to extract the links on a web page using python without BeautifulSoup?
I'm using cygwin and do not have BeautifulSoup installed.
A:
Getting the value of href attributes in all <a> tags on a html file with Python
python, regex to find anchor link html
Regular expression to extract URL from ... | What's the easiest way to extract the links on a web page using python without BeautifulSoup? | I'm using cygwin and do not have BeautifulSoup installed.
| [
"Getting the value of href attributes in all <a> tags on a html file with Python\npython, regex to find anchor link html\nRegular expression to extract URL from an HTML link\n",
"If you don't care much about performance you can use regular expressions:\nimport re\nlinkre = re.compile(r\"\"\"href=[\"']([^\"']+)[\"... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004414375_python.txt |
Q:
First,real programming project:Create a Database from a web dictionary
I want to create a programme that will take a word list, search on a web dictionary (like webster learning dictionary,cambridge learner's,..) and will create a text file in this shape:
word1 pronunciation definition example sentence ... ...
wo... | First,real programming project:Create a Database from a web dictionary | I want to create a programme that will take a word list, search on a web dictionary (like webster learning dictionary,cambridge learner's,..) and will create a text file in this shape:
word1 pronunciation definition example sentence ... ...
word2 pronunciation definition example sentence ... ...
....
and I have a fe... | [
"It would not be that difficult, the main thing would be figuring out how to query the website.\nThese would be the basic steps:\n\nmap query string to url: \n\nYou need to figure out how the website works (Examine the source ot the html to figure paramters of the forms.) Some websites have public API's that make i... | [
3
] | [
"This is possible, but in order to maintain scalability you will need the rigth algorithm:\nhttp://en.wikipedia.org/wiki/Aho%E2%80%93Corasick_string_matching_algorithm\nIn python this is: http://pypi.python.org/pypi/ahocorasick/0.9\nJust capture the event where the search tree reaches a state in which a search word... | [
-1
] | [
"database",
"dictionary",
"python"
] | stackoverflow_0004414435_database_dictionary_python.txt |
Q:
Is there a portable python interpreter that will run on Mac OS X 10.6 from a USB key?
I've been running myself ragged trying to find a portable interpreter that I can run from a USB key on my work computer. Work comp is running Mac OS X 10.6, fairly restricted environment, no access to terminal, can't install app... | Is there a portable python interpreter that will run on Mac OS X 10.6 from a USB key? | I've been running myself ragged trying to find a portable interpreter that I can run from a USB key on my work computer. Work comp is running Mac OS X 10.6, fairly restricted environment, no access to terminal, can't install apps but I do know that portable apps can be run from a USB drive. I've been using shell in a... | [
"Python is already on OS X. I would look at trying to find an editor/shell that will work from a usb drive.\n",
"If you don't have access to a terminal on the machine and can't install apps, using any Python is going to be problematic. The only useful out-of-the-box OS X GUI app provided by a standard Python bui... | [
2,
0
] | [] | [] | [
"interpreter",
"macos",
"portability",
"python",
"usb"
] | stackoverflow_0004414484_interpreter_macos_portability_python_usb.txt |
Q:
Detecting when the ball hits the paddle in pong?
I have been reading through this tutorial. I am in a chapter where you can build a pong game. However I am having trouble trying to make a function that can detect when the ball hits the paddle?
It says I should do this:
Make a boolean function hit(bx, by, r, px, p... | Detecting when the ball hits the paddle in pong? | I have been reading through this tutorial. I am in a chapter where you can build a pong game. However I am having trouble trying to make a function that can detect when the ball hits the paddle?
It says I should do this:
Make a boolean function hit(bx, by, r, px, py, h) that returns True when the vertical coordinate o... | [
"You're not accounting for the actual locations of the items - the coordinates you have refer to a specific point on the ball and paddle. What your code does is check that the ball is above the paddle and has a bigger radius than the distance from the y-origin to the paddle, then check that it's wider than the dist... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0003984541_python.txt |
Q:
Python Algorithm Efficiency
Say you have 32000 records with 89 bytes/record stored in a TSV file.
You stick this into a Python dictionary or Ruby hash and you index with a 9 byte key that is itself a field in each record. In other words, you have a dictionary with 32000 key-value pairs, where each key is 9 byte... | Python Algorithm Efficiency | Say you have 32000 records with 89 bytes/record stored in a TSV file.
You stick this into a Python dictionary or Ruby hash and you index with a 9 byte key that is itself a field in each record. In other words, you have a dictionary with 32000 key-value pairs, where each key is 9 bytes and each value is 89 bytes. On... | [
"A dictionary can typically retrieve keys in constant time so the answer to your question is \"very fast\".\nThe only way it would be slow if lots of your keys collided, but you can avoid this by using a good hash function. The default hash function will probably be fine.\n\nIs the implementation in Ruby slower tha... | [
4
] | [] | [] | [
"algorithm",
"python",
"ruby"
] | stackoverflow_0004414664_algorithm_python_ruby.txt |
Q:
How can I log into a website using python?
I've seen this other question: How to use Python to login to a webpage and retrieve cookies for later usage?
However, a straightforward modification of that answer did not work for me, so I'm wondering how I can achieve my goal.
To give context, I'm trying to log into htt... | How can I log into a website using python? | I've seen this other question: How to use Python to login to a webpage and retrieve cookies for later usage?
However, a straightforward modification of that answer did not work for me, so I'm wondering how I can achieve my goal.
To give context, I'm trying to log into https://mog.com/hp/sign_in and then extract the nam... | [
"Try with mechanize:\nimport mechanize\nbr=mechanize.Browser()\nbr.open('https://mog.com/hp/sign_in')\nbr.select_form(nr=0) \nbr['user[login]']= your_login\nbr['user[password]']= your_password\nbr.submit()\nbr.retrieve('http://mog.com/my_mog/playlists','playlist.html')\n\nEDIT:\nto get your links you can add this:\... | [
12
] | [] | [] | [
"authentication",
"python"
] | stackoverflow_0004414683_authentication_python.txt |
Q:
Is it possible to use batch scripts in a GUI made with Python?
I was wondering if it was possible to write a GUI in python, and then somewhere in the python script, insert a script switch to temporarily change the language to accomodate for the batch snippet.
I know this can be done in html and vbscript but what a... | Is it possible to use batch scripts in a GUI made with Python? | I was wondering if it was possible to write a GUI in python, and then somewhere in the python script, insert a script switch to temporarily change the language to accomodate for the batch snippet.
I know this can be done in html and vbscript but what about Python?
| [
"You can control other processes, written with any language, including bash using the subprocess module.\n",
"The subprocess module is the most powerful and complete method for executing other processes. However, there's also a very simple method using the os module: os.system(command) runs command just as if you... | [
3,
0
] | [] | [] | [
"batch_file",
"python",
"user_interface"
] | stackoverflow_0004414277_batch_file_python_user_interface.txt |
Q:
How can I remove all trailing dashes from a string?
Example:
string1 = 'title--'
string2 = 'title-'
string3 = 'this-is-a-title----'
>> print doSomething(string1)
>> title
>> print doSomething(string2)
>> title
>> print doSomething(string3)
>> this-is-a-title
A:
string1.rstrip("-")
# "title"
string2.rstrip("-"... | How can I remove all trailing dashes from a string? | Example:
string1 = 'title--'
string2 = 'title-'
string3 = 'this-is-a-title----'
>> print doSomething(string1)
>> title
>> print doSomething(string2)
>> title
>> print doSomething(string3)
>> this-is-a-title
| [
"string1.rstrip(\"-\")\n# \"title\"\nstring2.rstrip(\"-\")\n# \"title\"\nstring3.rstrip(\"-\")\n# \"title-is-a-title\"\n\n"
] | [
9
] | [] | [] | [
"python"
] | stackoverflow_0004414838_python.txt |
Q:
urllib2/lxml encoding problems
I'm new to python, and trying to use urllib2/lxml to fetch, and parse a page. Everything seems to work fine, except, the parsed page, when opened in my browser seems to have strange characters embedded in it. I'm guessing this is a unicode/lxml parsing problem. When I get the text co... | urllib2/lxml encoding problems | I'm new to python, and trying to use urllib2/lxml to fetch, and parse a page. Everything seems to work fine, except, the parsed page, when opened in my browser seems to have strange characters embedded in it. I'm guessing this is a unicode/lxml parsing problem. When I get the text content of an element, using .text_con... | [
"What is going on is that the website is using an \"endash\", which is a slightly longer dash (and the one you should use in ranges, like 40-56, really. Yeah, dashes is a whole science unto itself).\nIn Unicode, the endash has codepoint U+2013. The numbers you get, \\342\\200\\223 is the octal representation of the... | [
2,
0
] | [] | [] | [
"encoding",
"lxml",
"python",
"unicode",
"utf_8"
] | stackoverflow_0004413603_encoding_lxml_python_unicode_utf_8.txt |
Q:
video recording logic error - fps
I created a camera/videowriter with open CV, and everything records fine. The problem is when I play back the video, I'm getting a super-speed playback even though the video file only plays 30.0 fps. Can someone help me spot the logic error where I am not recording enough frames? ... | video recording logic error - fps | I created a camera/videowriter with open CV, and everything records fine. The problem is when I play back the video, I'm getting a super-speed playback even though the video file only plays 30.0 fps. Can someone help me spot the logic error where I am not recording enough frames? I do delay by some milliseconds based o... | [
"Nope, no clue, sounds like the delay function isn't delaying, strangeley enough. But, here are some additional comments:\n\nDon't use floats just to get division working properly. Use the future import instead:\n>>> from __future__ import division\n>>> 1000/30\n33.3333333333336\n\nNow you can do int(1000/30) inste... | [
1
] | [] | [] | [
"opencv",
"python"
] | stackoverflow_0004414890_opencv_python.txt |
Q:
Streaming mp3 files with django, read from a page with
I'm trying to make a small app to stream my mp3 files with a web interface, and I thought about playing with and do the server side in python with django.
I want to have urls like /stream/ID to stream the mp3 corresponding to that ID.
I made a view in django... | Streaming mp3 files with django, read from a page with | I'm trying to make a small app to stream my mp3 files with a web interface, and I thought about playing with and do the server side in python with django.
I want to have urls like /stream/ID to stream the mp3 corresponding to that ID.
I made a view in django to serve these files using different methods, the last one I... | [
"You could try using wireshark to observe your browser/media player/apache while it works correctly. \n"
] | [
0
] | [] | [] | [
"audio_streaming",
"django",
"python"
] | stackoverflow_0004414394_audio_streaming_django_python.txt |
Q:
python theading.Timer: how to pass argument to the callback?
My code:
import threading
def hello(arg, kargs):
print arg
t = threading.Timer(2, hello, "bb")
t.start()
while 1:
pass
The print out put is just:
b
How can I pass a argument to the callback? What does the kargs mean?
A:
Timer takes an ... | python theading.Timer: how to pass argument to the callback? | My code:
import threading
def hello(arg, kargs):
print arg
t = threading.Timer(2, hello, "bb")
t.start()
while 1:
pass
The print out put is just:
b
How can I pass a argument to the callback? What does the kargs mean?
| [
"Timer takes an array of arguments and a dict of keyword arguments, so you need to pass an array:\nimport threading\n\ndef hello(arg):\n print arg\n\nt = threading.Timer(2, hello, [\"bb\"])\nt.start()\n\nwhile 1:\n pass\n\nYou're seeing \"b\" because you're not giving it an array, so it treats \"bb\" an an it... | [
78,
4
] | [] | [] | [
"python",
"timer"
] | stackoverflow_0004415672_python_timer.txt |
Q:
"Flat is better than nested" - for data as well as code?
This question got me thinking: should we apply the principle that "flat is better than nested" to data as well as to code? Even when there is a "logical tree structure" to the data?
In this case, I suppose it would mean representing children as a list of IDs... | "Flat is better than nested" - for data as well as code? | This question got me thinking: should we apply the principle that "flat is better than nested" to data as well as to code? Even when there is a "logical tree structure" to the data?
In this case, I suppose it would mean representing children as a list of IDs, rather than an actual list of children, with all the nodes i... | [
"This is a completely subjective question. The answer is, \"it depends.\"\nIt depends on the primary use of your data. If you continually have to reference the nested structure, then it makes sense to represent it that way. And if you never reference the flat representation except when building the nested struct... | [
12,
10,
8,
6,
3,
3
] | [] | [] | [
"python",
"theory"
] | stackoverflow_0004372229_python_theory.txt |
Q:
how to save the 'user' object that not used to insert it everytime you need it using django
i want to do these thing:
1.open the login_view (which is the page user login)
2.write my username and password , and put 'login' button, then submit to the login_submit view
3.in login_submit view , if your username and pa... | how to save the 'user' object that not used to insert it everytime you need it using django | i want to do these thing:
1.open the login_view (which is the page user login)
2.write my username and password , and put 'login' button, then submit to the login_submit view
3.in login_submit view , if your username and password are right , you will return to the homepage
4.but when i return HttpResponseRedirect("/") ... | [
"Context processors.\n"
] | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004415932_django_python.txt |
Q:
python: array default value for index out-of-bounds
I need a good way to ask for an array/matrix value, but reporting a default (0) value for out-of-bound index:
b[2][4] should return 0 if the 2nd index length is 3, and
b[-1][2] also
I checked this:
Getting a default value on index out of range in Python, but it s... | python: array default value for index out-of-bounds | I need a good way to ask for an array/matrix value, but reporting a default (0) value for out-of-bound index:
b[2][4] should return 0 if the 2nd index length is 3, and
b[-1][2] also
I checked this:
Getting a default value on index out of range in Python, but it seems to me that it would not work for negative indices - ... | [
"If you want a indefinitely-sized sparse matrix, you can use defautldict:\npy> matrix=defaultdict(lambda:defaultdict(lambda:0))\npy> matrix[2][4]\n0\npy> matrix[2][4]=8\npy> matrix[2][4]\n8\npy> matrix[-1][2]\n0\n\n",
"I think your confusing the issue. \nlisty[-1] is a relative index such that, the true index equ... | [
8,
0,
0,
0
] | [] | [] | [
"arrays",
"python"
] | stackoverflow_0004413550_arrays_python.txt |
Q:
Can I make my class play nice with the Python '"in" keyword?
I'm heading into hour 5 or so of my experience with Python, and so far I've been pretty impressed with what it can do. My current endeavor is to make a short attempt at a Stream class, the code for which follows:
class Stream:
"""A Basic class imple... | Can I make my class play nice with the Python '"in" keyword? | I'm heading into hour 5 or so of my experience with Python, and so far I've been pretty impressed with what it can do. My current endeavor is to make a short attempt at a Stream class, the code for which follows:
class Stream:
"""A Basic class implementing the stream abstraction. """
def __init__(self,data,fu... | [
"For iterating as in for x in object, you need to provide an __iter__ method which will return a new iterator.\nAn iterator is an object which has a method next() (Python 2) or __next__ (Python 3) which either returns the next element or raises StopIteration exception when there are no more elements. (An iterator ... | [
14,
4,
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0004415939_python.txt |
Q:
how to Stay signed in 2 weeks when some user login using django
i want to make user dont need to login my site every day .
so what can i do using django ., does set cookies or other things ?
thanks
A:
The Django session documentation is fairly easy reading.
The defaults should already allow users to be signed... | how to Stay signed in 2 weeks when some user login using django | i want to make user dont need to login my site every day .
so what can i do using django ., does set cookies or other things ?
thanks
| [
"The Django session documentation is fairly easy reading.\nThe defaults should already allow users to be signed in for two weeks - in fact, the default value is exactly two weeks.\nTake a look at your settings for:\n\nSESSION_EXPIRE_AT_BROWSER_CLOSE - should be False\nSESSION_COOKIE_AGE - defaults to 1209600 (2 wee... | [
3
] | [] | [] | [
"authentication",
"django",
"python"
] | stackoverflow_0004415105_authentication_django_python.txt |
Q:
Python object in QMimeData
I'm implementing drag and drop QTreeView based on my custom model. All works fine, my tree displays data, drag and drop is enabled and now the last step lies ahead of me - to drop and trasfer dragged data. To do this I need to implement mimeTypes, mimeData and dropMimeData methods in my ... | Python object in QMimeData | I'm implementing drag and drop QTreeView based on my custom model. All works fine, my tree displays data, drag and drop is enabled and now the last step lies ahead of me - to drop and trasfer dragged data. To do this I need to implement mimeTypes, mimeData and dropMimeData methods in my model. And now my question: Is t... | [
"Do not try to implement drag and drop by reparenting the underlying python object. This won't work if the drag comes from outside your process; nor will it work for a copy operation (your node objects probably cannot exist in multiple places in the tree).\nThink of a drag and drop \"move\" as three operations:\n\... | [
2,
1
] | [] | [] | [
"drag_and_drop",
"pyqt",
"python",
"qtreeview"
] | stackoverflow_0004216139_drag_and_drop_pyqt_python_qtreeview.txt |
Q:
Extracting minimum and maximum x-values Python
i've written a function that takes a file with x,y coordinates as input, and simply show the coordinates in python. I want to work a bit more with the coordinates and here is my problem:
for example after reading a file i get:
32, 48.6
36, 49.0
30, 44.1
44, 60.1
46, 5... | Extracting minimum and maximum x-values Python | i've written a function that takes a file with x,y coordinates as input, and simply show the coordinates in python. I want to work a bit more with the coordinates and here is my problem:
for example after reading a file i get:
32, 48.6
36, 49.0
30, 44.1
44, 60.1
46, 57.7
and i want to extract the minimum and the maxim... | [
"from operator import itemgetter\n\n# replace the readfile function with this list comprehension\npoints = [map(float, r.split(\",\")) for r in open(sti + '/testdata.txt')]\n\n# This gets the point at the maximum x/y values\npoint_max_x = max(points, key=itemgetter(0))\npoint_max_y = max(points, key=itemgetter(1))\... | [
5,
1
] | [] | [] | [
"python"
] | stackoverflow_0004416435_python.txt |
Q:
python refcounts
So Python Essential Reference, 4 ed. says:
a = {}
b = {}
a['b'] = b
b['a'] = a
del a
del b
creates a memory leak, and the interpreter need a cycle detection algorithm to delete a and b.
However, when I tried to work out how the refcount are, it seems to me that at the end, the refcounts for a and... | python refcounts | So Python Essential Reference, 4 ed. says:
a = {}
b = {}
a['b'] = b
b['a'] = a
del a
del b
creates a memory leak, and the interpreter need a cycle detection algorithm to delete a and b.
However, when I tried to work out how the refcount are, it seems to me that at the end, the refcounts for a and b both go to zero, so... | [
"del a does not destory the object pointed to by the variable a, it only removes the variable a from the current namespace. After this, the dict lives on (since the other dict still references it) and therefore still references the second dict b. Likewise, del b does not cause the first dict's refcount to reach zer... | [
4,
3
] | [] | [] | [
"python",
"refcounting"
] | stackoverflow_0004416594_python_refcounting.txt |
Q:
"Invalid Filter" error for my custom Django template filters but not any other filters
I have a python file in my Django project which contains a custom template tag and a custom template filter.
My custom tag uses template.loader.get_template() to load another template file. This worked great... until I added my... | "Invalid Filter" error for my custom Django template filters but not any other filters | I have a python file in my Django project which contains a custom template tag and a custom template filter.
My custom tag uses template.loader.get_template() to load another template file. This worked great... until I added my custom filter to the loaded template.
Now I get a Django "Invalid Filter" TemplateSyntaxErr... | [
"The answer is maddeningly simple: split the custom tag and custom filter into two separate python files and it will work.\nI suspect the problem is this: the custom tag is using template.loader.get_template() to load another template. That template file contains a {% load %} tag which tries to load the same file ... | [
7
] | [] | [] | [
"django",
"django_template_filters",
"django_templates",
"python"
] | stackoverflow_0004417127_django_django_template_filters_django_templates_python.txt |
Q:
Update one surface in Pygame
I have a game with a background made of tiles, some are static (grass, mud), but i want water to be flowing. i have created a surface called water, then i have a loop that iterates through a series of 10 pngs for the frames of the water flowing. i want to then update this surface 10x a... | Update one surface in Pygame | I have a game with a background made of tiles, some are static (grass, mud), but i want water to be flowing. i have created a surface called water, then i have a loop that iterates through a series of 10 pngs for the frames of the water flowing. i want to then update this surface 10x as often as the rest of the game, a... | [
"It looks like you want to use pygame.display.update.\nJust pass it a list of all the water tiles' rects, and it will only update those parts of the screen. The only thing is that you can't use it with pygame.OPENGL displays, apparently.\nHowever, are you sure you want to animate your water at 300fps? It seems li... | [
2,
1
] | [] | [] | [
"animation",
"pygame",
"python",
"sprite"
] | stackoverflow_0004417108_animation_pygame_python_sprite.txt |
Q:
Argument packing and unpacking when instantiating a new class instance in PHP
In Python, you can pack and unpack arguments like so:
def myfunction(arg1, arg2, arg3):
pass
mydict = dict(arg1='foo', arg2='bar', arg3='baz')
myfunction(**mydict)
mylist = ['foo', 'bar', 'baz']
myfunction(*mylist)
Now, is there... | Argument packing and unpacking when instantiating a new class instance in PHP | In Python, you can pack and unpack arguments like so:
def myfunction(arg1, arg2, arg3):
pass
mydict = dict(arg1='foo', arg2='bar', arg3='baz')
myfunction(**mydict)
mylist = ['foo', 'bar', 'baz']
myfunction(*mylist)
Now, is there something similar in PHP? I have a class that is passed to a function, along with ... | [
"No you can't do it directly, you'll have to manually extract the values from the array and pass them to the constructor, or change it so that it accepts an array as argument.\nYou might take a look at call_user_func_array but I don't think you can use it with a constructor as you need an instance of the object to ... | [
0,
0
] | [] | [] | [
"dynamic",
"php",
"python"
] | stackoverflow_0004417117_dynamic_php_python.txt |
Q:
PyGame code doesn't execute properly when event is executed
I am trying to make the most simple pythong code that will respond when a button is pressed on a joystick. I used code from several different examples and I still cannot get it to work. The following code will not dispatch the event when I press the trigg... | PyGame code doesn't execute properly when event is executed | I am trying to make the most simple pythong code that will respond when a button is pressed on a joystick. I used code from several different examples and I still cannot get it to work. The following code will not dispatch the event when I press the trigger (or any button for that matter)
import pygame
joy = []
def h... | [
"I assume you've tried leaving off the if and just printing str?\nYour joystick might also not be working properly. Does it work in other programs?\nIf you are using linux you might need to install a joystick driver. For Windows, check the device manager.\n"
] | [
1
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0004416185_pygame_python.txt |
Q:
Transparent Desktop Widget in Python
I would like to write a desktop widget that has a transparent window and background, like Rainmeter, using Python. Also I should be able to lock the window in place, and make it so that it can not be above any other windows (ex. It can't be layered over Firefox). Is there a way... | Transparent Desktop Widget in Python | I would like to write a desktop widget that has a transparent window and background, like Rainmeter, using Python. Also I should be able to lock the window in place, and make it so that it can not be above any other windows (ex. It can't be layered over Firefox). Is there a way to do this?
| [
"I think this depends mostly on your OS and toolkit, and not so much Python. Any GUI library that supports opacity and has Python bindings, e.g., GTK+, will do the job.\n",
"if you're just looking for a graphic library, you can take a look at wx, that has a vaery powerful tool in make a windows transparent (this... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004417367_python.txt |
Q:
Permission denied when trying to install easy_install on OSX
I'm trying to install easy_install and, well... see for yourself:
sh setuptools-0.6c11-py2.6.egg
Processing setuptools-0.6c11-py2.6.egg
Copying setuptools-0.6c11-py2.6.egg to /Library/Python/2.6/site-packages
Adding setuptools 0.6c11 to easy-install.pth... | Permission denied when trying to install easy_install on OSX | I'm trying to install easy_install and, well... see for yourself:
sh setuptools-0.6c11-py2.6.egg
Processing setuptools-0.6c11-py2.6.egg
Copying setuptools-0.6c11-py2.6.egg to /Library/Python/2.6/site-packages
Adding setuptools 0.6c11 to easy-install.pth file
Installing easy_install script to /usr/local/bin
error: /usr... | [
"Use sudo. \nsudo sh setuptools-0.6c11-py2.6.egg\n\nI would also investigate MacPorts.\nEdit (5 years later): I now suggest Homebrew instead of MacPorts.\n",
"sudo sh setuptools-0.6c11-py2.6.egg\n\n",
"You should use sudo . You will need to enter your password.\n",
"Judging from the paths displayed, you are ... | [
12,
5,
3,
3
] | [] | [] | [
"easy_install",
"installation",
"macos",
"python"
] | stackoverflow_0004416984_easy_install_installation_macos_python.txt |
Q:
Python3.1 performance still disappointing - will it get better?
Here is a little program I wrote to measure the speed of a function that, for various reasons, is important to me:
import time,sys
count = 10 * 1000 * 1000
t1 = time.time()
d = dict()
for i in xrange(0,count):
d[i] = i
for i in xrange(0,count):
... | Python3.1 performance still disappointing - will it get better? | Here is a little program I wrote to measure the speed of a function that, for various reasons, is important to me:
import time,sys
count = 10 * 1000 * 1000
t1 = time.time()
d = dict()
for i in xrange(0,count):
d[i] = i
for i in xrange(0,count):
d[i] = d[i]*i
for i in xrange(0,count):
d[i] = d[i]-i
t2 = ti... | [
"1.\nPerformance, python doc:\n'''The net result of the 3.0 generalizations is that Python 3.0 runs the pystone benchmark around 10% slower than Python 2.5. Most likely the biggest cause is the removal of special-casing for small integers. There’s room for improvement, but it will happen after 3.0 is released!'''\n... | [
2
] | [] | [] | [
"performance",
"python",
"python_3.x"
] | stackoverflow_0004417775_performance_python_python_3.x.txt |
Q:
Why changing global does not give error?
Why on earth Python lets change not global declared list in function?
RE-UPDATED
numbers = []
num = 4
def add(n, thisnum=None):
# changing global list without global declaration!
numbers.append(n)
if thisnum:
num = thisnum
print 'num assigned... | Why changing global does not give error? | Why on earth Python lets change not global declared list in function?
RE-UPDATED
numbers = []
num = 4
def add(n, thisnum=None):
# changing global list without global declaration!
numbers.append(n)
if thisnum:
num = thisnum
print 'num assigned', thisnum
##numbers = ('one', 'two', 'thr... | [
"You aren't assigning to the global variable, you are calling a method on it which changes its contents. This is allowed.\nWhat you can't do without the global keyword is this:\ndef add(n):\n #global numbers\n numbers = numbers + [n]\n\nResult:\n\nTraceback (most recent call last):\n File \"C:\\Users\\Mark\\... | [
5,
1,
0
] | [] | [] | [
"global",
"list",
"python",
"side_effects"
] | stackoverflow_0004417869_global_list_python_side_effects.txt |
Q:
Hashlib in Windows and Linux
I'm writing a p2p application in Python and am using the hashlib module to identify files with the same contents but different names within the network.
The thing is that I tested the code that does the hash for the files in Windows (Vista), with Python 2.7 and it's very fast (less tha... | Hashlib in Windows and Linux | I'm writing a p2p application in Python and am using the hashlib module to identify files with the same contents but different names within the network.
The thing is that I tested the code that does the hash for the files in Windows (Vista), with Python 2.7 and it's very fast (less than a second, for a couple of gigaby... | [
"You're reading the file in 64 byte (hashlib.md5().block_size) blocks and hashing them.\nYou should use a much larger read value in the range of 256KB (262144 bytes) to 4MB (4194304 bytes) and then hash that; this one digup program reads in 1MB blocks i.e.:\nblock_size = 1048576 # 1MB\nwhile True:\n trozo = h.re... | [
3
] | [] | [] | [
"hashlib",
"linux",
"performance",
"python",
"windows"
] | stackoverflow_0004418042_hashlib_linux_performance_python_windows.txt |
Q:
best way to match these string or list?
main = ['123', '147', '159', '258', '369', '357', '456', '789']
match1 = 1374
match2 = 1892
here match1 has 1, 4 and 7 But main has '147' so it matches. match2 has 1,8,9,2 so it doesn't matches to main. What is the optimize solution?
A:
First you have to convert your in... | best way to match these string or list? | main = ['123', '147', '159', '258', '369', '357', '456', '789']
match1 = 1374
match2 = 1892
here match1 has 1, 4 and 7 But main has '147' so it matches. match2 has 1,8,9,2 so it doesn't matches to main. What is the optimize solution?
| [
"First you have to convert your inputs numbers to strings as you are interested in the digits they contain rather than actual values. You can use str to do this.\nTo solve your actual problem you want to check if there is any string in main such that all the characters in that string are contained in the string mat... | [
4,
4,
1
] | [] | [] | [
"python"
] | stackoverflow_0004418008_python.txt |
Q:
pydoc is inconsistent?
I have a package structured like this:
a/a1/a1.py
a/a2/a2.py
a/a3/a3.py
In a3.py, I imported modules a1 and a2 like these:
import a1.a1
import a2.a2
Then I run
pydoc -w a/
It produces a.html, a.a1.html, a.a1.a1.html, a.a2.html, a.a2.a2.html, a.a3.html, a.a3.a3.html.
The problem with a3 is,... | pydoc is inconsistent? | I have a package structured like this:
a/a1/a1.py
a/a2/a2.py
a/a3/a3.py
In a3.py, I imported modules a1 and a2 like these:
import a1.a1
import a2.a2
Then I run
pydoc -w a/
It produces a.html, a.a1.html, a.a1.a1.html, a.a2.html, a.a2.a2.html, a.a3.html, a.a3.a3.html.
The problem with a3 is, the links of the imports, i... | [
"Well, you could:\n\nChange into the a/ directory, then run pydoc on your directories separately\nBe strict with your import structure, as Python 3 forces you to (i.e. import a.a1.a1 or from ..a1 import a1)\nUse a newer way to make HTML documentation, like Sphinx (there is some learning curve, though).\n\n"
] | [
1
] | [] | [] | [
"pydoc",
"python"
] | stackoverflow_0004418547_pydoc_python.txt |
Q:
Remove a given element from the other set in a dict of two sets
I have a dict, { "foo": set(["a", "b"]), "bar": set(["c", "d"]) }, and I'm given an element of one of the two sets and the name of the other set. I need to remove that element. How would I go about doing this? My best attempt so far is this:
keys = di... | Remove a given element from the other set in a dict of two sets | I have a dict, { "foo": set(["a", "b"]), "bar": set(["c", "d"]) }, and I'm given an element of one of the two sets and the name of the other set. I need to remove that element. How would I go about doing this? My best attempt so far is this:
keys = dict.keys()
if Element in dict[keys[0]].union(dict[keys[1]]):
dict[ke... | [
"Try this:\ndictionary['foo' if otherset == 'bar' else 'bar'].discard(element)\n\n",
"Use a dictionary to look up the other set:\n>>> other={'foo':'bar','bar':'foo'}\n>>> d = { \"foo\": set([\"a\", \"b\"]), \"bar\": set([\"b\", \"c\"]) }\n>>> element = \"b\"\n>>> setname = \"bar\"\n>>> d[other[setname]].discard(e... | [
3,
2,
1,
1,
0,
0
] | [
"This is a much more \"pythonic\" way:\n>>> d = { \"foo\": set([\"a\", \"b\"]), \"bar\": set([\"b\", \"c\"]) }\n\n>>> d['foo']-=d['bar']\n>>> d\n{'foo': set(['a']), 'bar': set(['c', 'b'])}\n\nOf course d['foo'] could be d[hashable_key] with hashable_key having user input or what have you. \nRecall that the operato... | [
-1
] | [
"dictionary",
"python",
"set"
] | stackoverflow_0003368613_dictionary_python_set.txt |
Q:
Problems INSERTing record if similar doesn't already exist
I'm trying to check whether a record already exists in the database (by similar title), and insert it if not. I've tried it two ways and neither quite works.
More elegant way (?) using IF NOT EXISTS
if mode=="update":
#check if book is already present ... | Problems INSERTing record if similar doesn't already exist | I'm trying to check whether a record already exists in the database (by similar title), and insert it if not. I've tried it two ways and neither quite works.
More elegant way (?) using IF NOT EXISTS
if mode=="update":
#check if book is already present in the system
cursor.execute('IF NOT EXISTS (SELECT * FROM b... | [
"This doesn't answer your question since it's for Postgresql rather than MySQL, but I figured I'd drop it in for people searching their way here.\nIn Postgres, you can batch insert items if they don't exist:\nCREATE TABLE book (title TEXT, author TEXT, isbn TEXT);\n\n# Create a row of test data:\nINSERT INTO book (... | [
0,
0
] | [] | [] | [
"mysql",
"python",
"select"
] | stackoverflow_0004418506_mysql_python_select.txt |
Q:
How to maintain order of paragraphs in a Django document revision system?
I'm having trouble figuring out how to best implement a document (paragraph-) revision system in Django.
I want to save a revision history of a document, paragraph-by-paragraph. In other words, there will be a class Document, which has a Man... | How to maintain order of paragraphs in a Django document revision system? | I'm having trouble figuring out how to best implement a document (paragraph-) revision system in Django.
I want to save a revision history of a document, paragraph-by-paragraph. In other words, there will be a class Document, which has a ManyToManyField to Paragraph. To maintain the order of the paragraphs, a third cla... | [
"Editors often solve this problem with a Piece Table. The table is a list of objects that point to spans of characters that are a) contiguous in memory, and b) share common attributes. The order of the pieces in the table is used for mapping character-in-document addresses to memory and vice versa. By reordering th... | [
2,
1
] | [] | [] | [
"database_design",
"django",
"python"
] | stackoverflow_0004418461_database_design_django_python.txt |
Q:
How do I setup a portable pydoc server that closes when portable browsers have been shut down?
I've set up a portable environment on my flash drive consisting of Chromium Portable, Firefox Portable and Python 3. I am trying to write a Python 3 script that will launch a pydoc server to be accessed either in Chromiu... | How do I setup a portable pydoc server that closes when portable browsers have been shut down? | I've set up a portable environment on my flash drive consisting of Chromium Portable, Firefox Portable and Python 3. I am trying to write a Python 3 script that will launch a pydoc server to be accessed either in Chromium Portable or Firefox Portable. If Chromium Portable is already active, a new tab to the server will... | [
"In principle, you should be able to use the wait() method of your Popen objects. Something like this:\npydoc_process = launch_pydoc()\nbrowser_process = launch_browser()\nbrowser_process.wait()\npydoc_process.terminate()\n\n(Modify your launch functions to end with return subprocess.Popen(...)\nBut I don't know h... | [
0
] | [] | [] | [
"pydoc",
"python"
] | stackoverflow_0004293701_pydoc_python.txt |
Q:
Python - structure of application
Morning,
Got a python app I have been working on.
Currently it consits of just a couple of files but as it gets bigger I am creating more and more files and the top of my main python file I am doing
import url_thread
import task_database
import xxxx
import yyyy
and I am going to ... | Python - structure of application | Morning,
Got a python app I have been working on.
Currently it consits of just a couple of files but as it gets bigger I am creating more and more files and the top of my main python file I am doing
import url_thread
import task_database
import xxxx
import yyyy
and I am going to be adding another class today which is ... | [
"yes, you can do what you are asking, but it is not advised.\nyou can create a package containing all your modules and then pollute your namespace by just importing everything:\nfrom foo import *\n\n... or a better way would be to create a nicely structured package of modules and then explicitly import them as need... | [
1,
0,
0
] | [] | [] | [
"directory_structure",
"import",
"python"
] | stackoverflow_0004418865_directory_structure_import_python.txt |
Q:
Implementing efficient audit trail of record changes in Google App Engine - design patterns
I have a quite common design problem: I need to implement a history log (audit trail) for records in Google App Engine. The history log has to be structured, i.e I cannot join all changes into some free-form text and store ... | Implementing efficient audit trail of record changes in Google App Engine - design patterns | I have a quite common design problem: I need to implement a history log (audit trail) for records in Google App Engine. The history log has to be structured, i.e I cannot join all changes into some free-form text and store in string field.
I've considered the following options for the history model and, after noticing... | [
"If I would have to choose I would go for option 1. The reads are as (if not more) performant for the other options. And all other options only have speed advantages under specific circumstances (small or very large sets of changes). It will also get you lots of flexibility (with more ease) like purging history aft... | [
3
] | [] | [] | [
"audit",
"expando",
"google_app_engine",
"performance",
"python"
] | stackoverflow_0004417130_audit_expando_google_app_engine_performance_python.txt |
Q:
Is there any harm to encoding (with the same encoding format) a string multiple times? (in Python)
Is there any harm to encoding a string multiple times in python, with the same encoding format? (i.e, UTF-8)?
I have a function that uses another function to get a string from a document, and then serialize the strin... | Is there any harm to encoding (with the same encoding format) a string multiple times? (in Python) | Is there any harm to encoding a string multiple times in python, with the same encoding format? (i.e, UTF-8)?
I have a function that uses another function to get a string from a document, and then serialize the string. Currently, the only user of the second function(the one which gets the string from the document) is t... | [
"You can't encode multiple times, it doesn't work.\n>>> s = u\"ä\".encode('latin1')\n>>> s = s.encode('latin1')\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nUnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128)\n\nSee, you get \"ascii code... | [
5,
1,
1,
0
] | [] | [] | [
"encoding",
"python",
"unicode",
"utf_8"
] | stackoverflow_0004418931_encoding_python_unicode_utf_8.txt |
Q:
I need a stand alone python interpreter/compiler!
Ok so i am in need of a python compiler (from .py or .pyw to .exe).
the only ones i have come across are:
- cx_freeze (doesnt work)
- py2exe (way too complicated)
EDIT:
both of the programs above are complicated (to me) because you have to make all these setup fil... | I need a stand alone python interpreter/compiler! | Ok so i am in need of a python compiler (from .py or .pyw to .exe).
the only ones i have come across are:
- cx_freeze (doesnt work)
- py2exe (way too complicated)
EDIT:
both of the programs above are complicated (to me) because you have to make all these setup files, and type in a bunch of parameters and commands to g... | [
"Pyinstallet might help...\nhowever py2exe is not complicated...\ntake a look at this py2exe sample setup (from here, but it's italian, so i translated it http://bancaldo.wordpress.com/2010/05/13/python-py2exe-setup-py-sample/)\n#!/usr/bin/python\n\nfrom distutils.core import setup\nimport py2exe, sys, wx, os\n\n# ... | [
5,
2,
1,
1,
0,
0
] | [] | [] | [
"compiler_construction",
"python"
] | stackoverflow_0004417316_compiler_construction_python.txt |
Q:
Passing extra arguments with Tkinter Bindings
I'm trying to bind an extra argument opt to the following radiobuttons below. I'm trying to make it so that when WSRB_UD is triggered I can know which radiobutton triggered it. How do I go about this?
Snippet:
self.WS.SW.SearchFrame = []
self.WS.SW.Se... | Passing extra arguments with Tkinter Bindings | I'm trying to bind an extra argument opt to the following radiobuttons below. I'm trying to make it so that when WSRB_UD is triggered I can know which radiobutton triggered it. How do I go about this?
Snippet:
self.WS.SW.SearchFrame = []
self.WS.SW.SearchRB = []
self.WS.RBvar = Tkinter.IntVa... | [
"You can use lambda to define an anonymous partial function:\nRB.bind( \"<Enter>\", lambda event: self.WSRB_UD(event, i) )\n\nYou could also use functools.partial if you don't like the lambda syntax.\n"
] | [
3
] | [] | [] | [
"arguments",
"binding",
"python",
"tkinter"
] | stackoverflow_0004419101_arguments_binding_python_tkinter.txt |
Q:
does the `context_instance=RequestContext(request)` use cookies in django
when i change the homepage view:
def home(request):
return render_to_response('homepage.html')
to
def home(request):
return render_to_response('homepage.html',context_instance=RequestContext(request))
the user who login my site wil... | does the `context_instance=RequestContext(request)` use cookies in django | when i change the homepage view:
def home(request):
return render_to_response('homepage.html')
to
def home(request):
return render_to_response('homepage.html',context_instance=RequestContext(request))
the user who login my site will always login even when i close the web Browser(firefox)
why context_instance... | [
"Adding the RequestContext does not change the user's logged-in state at all. And your question about cookies makes no sense at all. What the RequestContext does is make certain variables accessible in the template context - among them, assuming you have the auth context processor enabled, is a user variable.\nWith... | [
3,
0
] | [] | [] | [
"cookies",
"django",
"python",
"requestcontext"
] | stackoverflow_0004419385_cookies_django_python_requestcontext.txt |
Q:
python threading.Timer: do i need to protect the variable accessed inside the callback?
I am trying to use threading.Timer, I am wondering is this timer is started in another thread? So I need to protect the variables accessed by this timer?
A:
You could see in the threading.py file that threading.Timer() return... | python threading.Timer: do i need to protect the variable accessed inside the callback? | I am trying to use threading.Timer, I am wondering is this timer is started in another thread? So I need to protect the variables accessed by this timer?
| [
"You could see in the threading.py file that threading.Timer() returns an instance of a new Thread. Or you could run an example:\nimport threading\n\ndef ontimer():\n print threading.current_thread()\n\ndef main():\n threading.Timer(2, ontimer).start()\n print threading.current_thread()\n\nif __name__==\"_... | [
1
] | [] | [] | [
"multithreading",
"python",
"thread_safety",
"timer"
] | stackoverflow_0004417058_multithreading_python_thread_safety_timer.txt |
Q:
Python - How to alter variable in a module imported as "from module import *"
"""Making a better version of my IF(Interactive Fiction) module so you can just create a module that imports it and you can start adding crap
Three things- Well four if you count the DEBUG variable-
The variables PLAYER_NAME, PLAYER_LOCA... | Python - How to alter variable in a module imported as "from module import *" | """Making a better version of my IF(Interactive Fiction) module so you can just create a module that imports it and you can start adding crap
Three things- Well four if you count the DEBUG variable-
The variables PLAYER_NAME, PLAYER_LOCATION, and PLAYER_INVENTORY. In the base they are "Luke", None, and list
The adventu... | [
"You can't do this, for the reason you have given. It can be simulated by creating an object with the appropriate attributes, but then you may as well not import * to begin with.\n",
"Yeah, you can't do it. the \"from mask_IF import *\" is creating a new variable named PLAYER_NAME in your current module, which ha... | [
3,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004419459_python.txt |
Q:
How to see function signature in Python?
Is there a way to introspect a function so that it shows me information on the arguments it takes (like number of args, type if possible, name of arguments if named) and the return value? dir() doesn't seem to do what I want. The __doc__ string sometimes includes method/fun... | How to see function signature in Python? | Is there a way to introspect a function so that it shows me information on the arguments it takes (like number of args, type if possible, name of arguments if named) and the return value? dir() doesn't seem to do what I want. The __doc__ string sometimes includes method/function arguments, but often doesn't.
| [
"help(the_funcion) should give you all of that information.\nSample:\n>>> help(enumerate)\nHelp on class enumerate in module __builtin__:\n\nclass enumerate(object)\n | enumerate(iterable[, start]) -> iterator for index, value of iterable\n |\n | Return an enumerate object. iterable must be another object that s... | [
20
] | [] | [] | [
"introspection",
"python"
] | stackoverflow_0004419829_introspection_python.txt |
Q:
How do I create a package protected constructor in Python?
I'd like to create a factory pattern in Python, where one class has some configuration, and knows how to build another class' object (or several classes) on demand. To make this complete, I would like to prevent the created class from being created outsid... | How do I create a package protected constructor in Python? | I'd like to create a factory pattern in Python, where one class has some configuration, and knows how to build another class' object (or several classes) on demand. To make this complete, I would like to prevent the created class from being created outside of the factory. In Java, I would put both in the same package... | [
"You can't. The Python mentality is often summed up as \"we're all grown-ups here\"; that is, you can't stop people calling methods, changing attributes, instantiating classes, and so on. Instead, you should make an obvious way to construct an instance of your class and then assume that it will be used.\n",
"Don'... | [
3,
2,
2,
1
] | [] | [] | [
"constructor",
"oop",
"python"
] | stackoverflow_0004411044_constructor_oop_python.txt |
Q:
How can I heapify a heapq in O(lgn)?
Possible Duplicate:
How can I implement decrease-key functionality in Python's heapq?
Hi,
I'm using heapq in Python to implement a priority queue. The items inside the queue get their priorities changed a lot, and when that happens I need to heapify the heapq.
The problem is ... | How can I heapify a heapq in O(lgn)? |
Possible Duplicate:
How can I implement decrease-key functionality in Python's heapq?
Hi,
I'm using heapq in Python to implement a priority queue. The items inside the queue get their priorities changed a lot, and when that happens I need to heapify the heapq.
The problem is that heapq only has a heapify function th... | [
"I was able to avoid this particuler issue with heapify by invalidating current heap item (raise a flag inside the item) and push an identical item to the heap (which is O(lgn)).\nThat may inflate the heap with some invalid items (which I clean at pop()), but avoids reimplementing the heap with heap items aware of ... | [
0
] | [] | [] | [
"heap",
"python"
] | stackoverflow_0004414235_heap_python.txt |
Q:
Corba Event Client ETIMEDOUT
I have built a CORBA event service client with omniOrb and Python. I had the same issue with a Java client. I'm very certain I'm experiencing the same thing as this post because my strace looks very similar but he doesn't explain exactly how he fixed it: Java's 'tnameserv' takes 3+ m... | Corba Event Client ETIMEDOUT | I have built a CORBA event service client with omniOrb and Python. I had the same issue with a Java client. I'm very certain I'm experiencing the same thing as this post because my strace looks very similar but he doesn't explain exactly how he fixed it: Java's 'tnameserv' takes 3+ minutes to be "Ready", why?
Bottom ... | [
"I fixed this issue by adding the following line to my firewall script\n ip6tables -A INPUT -i lo -j ACCEPT\n\n",
"I ended up figuring out that since I'm on a different subnet than the server, the ORB as publishing the wrong IP address, and couldn't figure out the route back to my client when an even triggered.\n... | [
0,
0
] | [] | [] | [
"corba",
"linux",
"python"
] | stackoverflow_0004418446_corba_linux_python.txt |
Q:
add a local variables to a function
is it possible to add a local varible to a function, just before calling it ? if yes how ?
EDIT:REASON
i noticed that all my views in django are using
render_to_response(template_name,locals())
now i created a middleware and i wanted to add one more local variable using the
d... | add a local variables to a function | is it possible to add a local varible to a function, just before calling it ? if yes how ?
EDIT:REASON
i noticed that all my views in django are using
render_to_response(template_name,locals())
now i created a middleware and i wanted to add one more local variable using the
def process_view():
method of it .so that... | [
"The local scope for a function does not exist until the function is called, so it's not possible to do this. You could do this for a closure, but the next person to have to maintain the code would hunt you down and kill you.\n",
"Although I also think it is pretty useless, I thought that you may enclose the func... | [
7,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004368527_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.