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:
File Manipulation: Scripting Question
I have a script which connects to database and gets all records which statisfy the query. These record results are files present on a server, so now I have a text file which has all file names in it.
I want a script which would know:
What is the size of each file in the outpu... | File Manipulation: Scripting Question | I have a script which connects to database and gets all records which statisfy the query. These record results are files present on a server, so now I have a text file which has all file names in it.
I want a script which would know:
What is the size of each file in the output.txt file?
What is the total size of all t... | [
"Eyeballing, you can make YOUR script work this way:\n1) Delete the line filename=filename.replace(' ', '\\ ') Escaping is more complicated than that, and you should just quote the full path or use a Python library to escape it based on the specific OS;\n2) You are probably missing a delimiter between the path and ... | [
1,
1,
0,
0
] | [] | [] | [
"file",
"perl",
"python",
"scripting",
"unix"
] | stackoverflow_0003746552_file_perl_python_scripting_unix.txt |
Q:
'from sqlite3 import dbapi2 as sqlite3' vs 'import sqlite3'?
When I see the examples for pysqlite, there are two use cases for the SQLite library.
from sqlite3 import dbapi2 as sqlite3
and
import sqlite3
Why there are two ways to support the sqlite3 api? What's the difference between the two? Are they the same? ... | 'from sqlite3 import dbapi2 as sqlite3' vs 'import sqlite3'? | When I see the examples for pysqlite, there are two use cases for the SQLite library.
from sqlite3 import dbapi2 as sqlite3
and
import sqlite3
Why there are two ways to support the sqlite3 api? What's the difference between the two? Are they the same? In normal use, which would be preferred.
ADDED
I knew that they a... | [
"They are the same. In the Lib/ directory of my Python installation (v2.6), the sqlite3 package contains a __init__.py file with this:\nfrom dbapi2 import *\n\nWhich means that the two ways of importing are absolutely identical.\nThat said, I definitely recommend just using import sqlite3 - as this is the documente... | [
8,
2
] | [] | [] | [
"pysqlite",
"python"
] | stackoverflow_0003754080_pysqlite_python.txt |
Q:
Help converting Python app to C#
Everyone,
here is a link to a small python app:
http://en.wikipedia.org/wiki/File:Beta-skeleton.svg
I think I've correctly converted it. (Source at bottom of post)
But, the Math.Acos always returns NaN. Is there a difference between the python version of acos and Math.Acos?
pr... | Help converting Python app to C# | Everyone,
here is a link to a small python app:
http://en.wikipedia.org/wiki/File:Beta-skeleton.svg
I think I've correctly converted it. (Source at bottom of post)
But, the Math.Acos always returns NaN. Is there a difference between the python version of acos and Math.Acos?
private Random rnd = new Random();
p... | [
"What you need to do to get the angle from the dot product is to take away the lengths before you acos.\nWhat python has:\nprq = acos(dot(p,q,r) / (dot(p,p,r)*dot(q,q,r))**0.5)\n\nWhat you're doing is not dividing in the Acos, but dividing after.\nso:\nint r = pnt;\nint ppr = Dot(p,p,r);\nint qqr = Dot(q,q,r);\nint... | [
3,
2,
0
] | [] | [] | [
"c#",
"math",
"python"
] | stackoverflow_0003753925_c#_math_python.txt |
Q:
Ruby To Python Syntax Confusion
I'm trying to convert someone's Ruby code into my Python code. The originally developer is no longer with us and I don't know Ruby. Most of his code is easy enough to follow, but some of the following syntax is tripping me up.
Example:
myTable = ''
m... | Ruby To Python Syntax Confusion | I'm trying to convert someone's Ruby code into my Python code. The originally developer is no longer with us and I don't know Ruby. Most of his code is easy enough to follow, but some of the following syntax is tripping me up.
Example:
myTable = ''
myTable << [ 0, 1, 0, 0, 0, 300].pack(... | [
"You're wrong about the second line, though strangely you're right that it's similar to struct.pack. myTable is a string. Array#pack() returns a string of the packed data (much like struct.pack), and String#<< appends a string to the receiving string. The third line sets 4 bytes at index 40 to be the result of [413... | [
3,
2,
1
] | [] | [] | [
"python",
"ruby",
"syntax"
] | stackoverflow_0003754450_python_ruby_syntax.txt |
Q:
Execute external application and send some key events to it
I wasn't able to find a solution for Python.
I am abelt o launch the application (using subprocess.Popen or subprocess.call), but I can't find a way to do the other part:
I want to send a serie of keys (kind of macro) to the application I just opened. Lik... | Execute external application and send some key events to it | I wasn't able to find a solution for Python.
I am abelt o launch the application (using subprocess.Popen or subprocess.call), but I can't find a way to do the other part:
I want to send a serie of keys (kind of macro) to the application I just opened. Like:
Tab
Tab
Enter
Tab
Tab
Delete
...
Is there a way to do this tha... | [
"Under windows you could use the venerable SendKeys to do this. There's a few implementations floating around. One, using the win32 extentions or two, there's even a couple ready-to-use modules available\n",
"Run the subprocess.Popen() command with the argument stdin=subprocess.PIPE then use the Popen object's ... | [
2,
1,
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0003684594_python_wxpython.txt |
Q:
The open/close function of SQLite implementation
I'm trying to come up with SQLiteDB object, and following is the open/close code for it.
Does this work without problem? Am I missing something important?
For close(), I use con.close() and cursor.close(), but I'm wondering if cursor.close() is necessary.
class SQL... | The open/close function of SQLite implementation | I'm trying to come up with SQLiteDB object, and following is the open/close code for it.
Does this work without problem? Am I missing something important?
For close(), I use con.close() and cursor.close(), but I'm wondering if cursor.close() is necessary.
class SQLiteDB(object):
def __init__(self, dbFile, connect ... | [
"What happens on Cursor.close() depends on the underlying database implementation. For SQLite it might currently work without closing, but for other implementations or a future SQLite version it might not, so I would recommend to close the Cursor object. You can find further information on Cursor.close() in PEP 249... | [
1
] | [] | [] | [
"pysqlite",
"python"
] | stackoverflow_0003754151_pysqlite_python.txt |
Q:
How can we use ms office communicator client exposed APIs in python, is that possible?
I want to use ms office communicator client apis, and i wan to use those in python is it possible to do ?
A:
>>> import win32com.client
>>> msg = win32com.client.Dispatch('Communicator.UIAutomation')
>>> msg.InstantMessage('us... | How can we use ms office communicator client exposed APIs in python, is that possible? | I want to use ms office communicator client apis, and i wan to use those in python is it possible to do ?
| [
"\n>>> import win32com.client\n>>> msg = win32com.client.Dispatch('Communicator.UIAutomation')\n>>> msg.InstantMessage('user@domain.com')\n\n\n",
"There is an JSON API to access all office communicator functions via \"office communicator web access\". You can download a description for that API. But nobody has im... | [
2,
1,
0
] | [] | [] | [
"api",
"office_communicator",
"python"
] | stackoverflow_0002286790_api_office_communicator_python.txt |
Q:
shopify xml request from GAE python
I'm trying to make requests to the shopify.com API over GAE python
the url i have to request is not formed in the usual format.
it is composed like http://apikey:password@hostname/admin/resource.xml
with urllib I can request it but i cant set the headers for an xml request so it... | shopify xml request from GAE python | I'm trying to make requests to the shopify.com API over GAE python
the url i have to request is not formed in the usual format.
it is composed like http://apikey:password@hostname/admin/resource.xml
with urllib I can request it but i cant set the headers for an xml request so it doesn't work.
urllib2, httplib... are ha... | [
"Look into how to do HTTP Basic authentication in Python. See especially the section on Doing it Properly.\n"
] | [
2
] | [] | [] | [
"google_app_engine",
"python",
"xml"
] | stackoverflow_0003753951_google_app_engine_python_xml.txt |
Q:
How to copy directory permissions
I'm curious how to copy the permission from directory to another.
Any idea?
Thanks
A:
shutil.copymode should help you out. From the documentation:
shutil.copymode(src, dst)
Copy the permission bits from src to dst. The file contents, owner, and group are unaffected. src and dst... | How to copy directory permissions | I'm curious how to copy the permission from directory to another.
Any idea?
Thanks
| [
"shutil.copymode should help you out. From the documentation:\n\nshutil.copymode(src, dst)\nCopy the permission bits from src to dst. The file contents, owner, and group are unaffected. src and dst are path names given as strings.\n\nI tested this in Ubuntu Jaunty using Python 2.6.2 and it worked for me.\n",
"Sin... | [
5,
2,
1
] | [] | [] | [
"permissions",
"python"
] | stackoverflow_0003754848_permissions_python.txt |
Q:
Scheduling a time in the future to send an email in Java or Python
I'm writing an application and I'd like it to somehow schedule an email to be sent at a later date (likely an hour after it is run). The programming language will be Python or Java.
Any open-source tools available for that purpose?
EDIT: I forgot t... | Scheduling a time in the future to send an email in Java or Python | I'm writing an application and I'd like it to somehow schedule an email to be sent at a later date (likely an hour after it is run). The programming language will be Python or Java.
Any open-source tools available for that purpose?
EDIT: I forgot to mention it's to be run after a test run, so the application will alrea... | [
"Quartz Scheduler can be user for this kind of asynchronous jobs.\n",
"Quartz is a great Java library for functions that you want to run at a certain time, after a certain time interval, etc.\nThere is also the Timer class in the JDK.\n",
"If you are to use Java, try Quartz, an open source job scheduling framew... | [
7,
3,
2,
2,
1,
1
] | [] | [] | [
"email",
"java",
"python",
"scheduling"
] | stackoverflow_0003753982_email_java_python_scheduling.txt |
Q:
How to use a generator to iterate over a tree's leafs
The problem:
I have a trie and I want to return the information stored in it. Some leaves have information (set as value > 0) and some leaves do not. I would like to return only those leaves that have a value.
As in all trie's number of leaves on each node is v... | How to use a generator to iterate over a tree's leafs | The problem:
I have a trie and I want to return the information stored in it. Some leaves have information (set as value > 0) and some leaves do not. I would like to return only those leaves that have a value.
As in all trie's number of leaves on each node is variable, and the key to each value is actually made up of t... | [
"Change \nself.postorder(child)\n\nto\nfor n in self.postorder(child):\n yield n\n\nseems to make it work.\nP.S. It is very helpful for you to left out the blank lines for ease of cut & paste :)\n"
] | [
2
] | [] | [] | [
"generator",
"python",
"tree"
] | stackoverflow_0003755242_generator_python_tree.txt |
Q:
Python or SQL Logistic Regression
Given time-series data, I want to find the best fitting logarithmic curve. What are good libraries for doing this in either Python or SQL?
Edit: Specifically, what I'm looking for is a library that can fit data resembling a sigmoid function, with upper and lower horizontal asympto... | Python or SQL Logistic Regression | Given time-series data, I want to find the best fitting logarithmic curve. What are good libraries for doing this in either Python or SQL?
Edit: Specifically, what I'm looking for is a library that can fit data resembling a sigmoid function, with upper and lower horizontal asymptotes.
| [
"If your data were categorical, then you could use a logistic regression to fit the probabilities of belonging to a class (classification).\nHowever, I understand you are trying to fit the data to a sigmoid curve, which means you just want to minimize the mean squared error of the fit.\nI would redirect you to the ... | [
3
] | [] | [] | [
"machine_learning",
"math",
"python",
"regression",
"sql"
] | stackoverflow_0003754051_machine_learning_math_python_regression_sql.txt |
Q:
Django newbie question regarding defining an object with subobjects from models for use in templates
I am somewhat new to Django and have searched for some simple examples of creating objects with subobjects in views so that in templates I can have nested for loops.
Here is my models.py for this application...
fro... | Django newbie question regarding defining an object with subobjects from models for use in templates | I am somewhat new to Django and have searched for some simple examples of creating objects with subobjects in views so that in templates I can have nested for loops.
Here is my models.py for this application...
from django.db import models
from django import forms
class Market(models.Model):
name = models.CharFi... | [
"I don't see a need to use distinct here. By representing the states as separate model and using relations you would gain much more flexibility.\nI suggest you create a third State model and use a ForeignKey to relate the models together so that each Market has a one to many relation to single State, i guess you al... | [
2
] | [] | [] | [
"django",
"models",
"python",
"templates",
"views"
] | stackoverflow_0003755164_django_models_python_templates_views.txt |
Q:
Using Relative Paths To Log Files In Pylons' development.ini
I am working on a Pylons app that runs on top of Apache with mod_wsgi. I would like to send logging messages that my app generates to files in my app's directory, instead of to Apache's logs. Further, I would like to specify the location of logfiles vi... | Using Relative Paths To Log Files In Pylons' development.ini | I am working on a Pylons app that runs on top of Apache with mod_wsgi. I would like to send logging messages that my app generates to files in my app's directory, instead of to Apache's logs. Further, I would like to specify the location of logfiles via a relative path so that it'll be easier to deploy my app on othe... | [
"The problem is that Paste Deploy creates one ConfigParser object to store the 'here' tag in it's set of defaults, and logging.config.fileConfig() is never passed that set of defaults. Therefore, when fileConfig() reads the .ini file, it doesn't have access to the 'here' tag, and the ConfigParser's interpolation ca... | [
8,
0
] | [] | [] | [
"logging",
"mod_wsgi",
"pylons",
"python"
] | stackoverflow_0003752982_logging_mod_wsgi_pylons_python.txt |
Q:
Does IronPython .net based DLL need to be deployed with Python Standard Library if it uses the Standard Library?
If I reference the Python Standard Library using IronPython do I have to deploy any Python related libraries or runtimes along with my .net dll? Or, can I just deploy the dll?
A:
you need to deploy t... | Does IronPython .net based DLL need to be deployed with Python Standard Library if it uses the Standard Library? | If I reference the Python Standard Library using IronPython do I have to deploy any Python related libraries or runtimes along with my .net dll? Or, can I just deploy the dll?
| [
"you need to deploy the python libraries you're referencing along with your dll. it wont be included statically in there for you.\n"
] | [
3
] | [] | [] | [
".net",
"ironpython",
"python"
] | stackoverflow_0003755493_.net_ironpython_python.txt |
Q:
Sharing data between nodes (app servers) in cloud
I'm building a Python/Pylons webapp that has been served by single server so far, now I want to investigate how it would scale among several servers with some kind of load balancer in front.
The main concern is server-side state, of course. It includes user sessio... | Sharing data between nodes (app servers) in cloud | I'm building a Python/Pylons webapp that has been served by single server so far, now I want to investigate how it would scale among several servers with some kind of load balancer in front.
The main concern is server-side state, of course. It includes user session data, user uploaded data (pictures and the like), and... | [
"caching is easily accomplished using standard memecached - which can be distributed over multiple servers.\nNFS sounds like a bad idea since you'll need to implement your own locking mechanism to avoid race conditions.\nI would go for one of the distributed no-sql solutions like cassandra.\n",
"I'd strongly reco... | [
1,
1
] | [] | [] | [
"architecture",
"cloud",
"python",
"scaling"
] | stackoverflow_0003440521_architecture_cloud_python_scaling.txt |
Q:
importing modules' files into submodules
i have a module with many files, which i import in themselves for sharing of functionality
myModule/
-myFile1.py
-myFile2.py
-mySubmodule/
--myFile3.py
i can do import myFile2, inside of myFile1, but how can i do a import myFile2 in myFile3 without referencing the base mo... | importing modules' files into submodules | i have a module with many files, which i import in themselves for sharing of functionality
myModule/
-myFile1.py
-myFile2.py
-mySubmodule/
--myFile3.py
i can do import myFile2, inside of myFile1, but how can i do a import myFile2 in myFile3 without referencing the base module? i dont want to reference myModule, becau... | [
"You're asking about relative imports. See this question\nWithin myFile3, you want:\nfrom .. import myFile2\n\n"
] | [
0
] | [] | [] | [
"import",
"module",
"python"
] | stackoverflow_0003755330_import_module_python.txt |
Q:
Trying to use my subnet address in python code
I'm trying to get my ip subnet address (192.168.1.xxx) into my python code. I'm running linux/osx. How do I do this/ What is the best way to do this?
A:
The easiest way to to this in my experience is to use two third party packages:
python-netifaces: Portable netwo... | Trying to use my subnet address in python code | I'm trying to get my ip subnet address (192.168.1.xxx) into my python code. I'm running linux/osx. How do I do this/ What is the best way to do this?
| [
"The easiest way to to this in my experience is to use two third party packages:\n\npython-netifaces: Portable network interface information\npython-netaddr: Pythonic manipulation of IPv4, IPv6, CIDR, EUI and MAC network addresses\n\nSo install those modules and then it's as easy as this:\nimport netifaces\nimport ... | [
9
] | [] | [] | [
"linux",
"networking",
"python"
] | stackoverflow_0003755863_linux_networking_python.txt |
Q:
Form.save(commit=False) behaving differently in Django 1.2.3?
Prior to today, I've been using Django 1.1. To ensure I'm keeping up with the times, I decided to update my Django environment to use Django 1.2.3. Unfortunately, I've encountered an issue.
The following code did not raise a ValueError in 1.1:
... | Form.save(commit=False) behaving differently in Django 1.2.3? | Prior to today, I've been using Django 1.1. To ensure I'm keeping up with the times, I decided to update my Django environment to use Django 1.2.3. Unfortunately, I've encountered an issue.
The following code did not raise a ValueError in 1.1:
instance = FormClass(
request.POST,
instanc... | [
"According to the 1.2 docs on the save() method, \"If you call save() with commit=False, then it will return an object that hasn't yet been saved to the database.\" So I'm not sure why there would have been a change in functionality, but it's possible that in 1.1 validation/check code ran only when an object was sa... | [
3
] | [] | [] | [
"django",
"django_forms",
"pre_commit",
"python"
] | stackoverflow_0003755738_django_django_forms_pre_commit_python.txt |
Q:
How would I write some values/strings in particular columns of a file in python
I have some values that I want to write in a text file with the constraint that each value has to go to a particular column of each line.
For example, lets say that I have values = [a, b, c, d] and I want to write them in a line so tha... | How would I write some values/strings in particular columns of a file in python | I have some values that I want to write in a text file with the constraint that each value has to go to a particular column of each line.
For example, lets say that I have values = [a, b, c, d] and I want to write them in a line so that a is going to be written in the 10th column of the line, b on the 25th, c on the 34... | [
"In this case, I'd think you'd just use the padding functions with python's string formatting syntax.\nSomething like \"%10d%15d%9d%14d\"%values will place the right-most digit of a,b,c,d on the columns you listed.\nIf you want to have the left-most digits placed there, then you could use: \"%<15d%<9d%<14d%d\"%valu... | [
3,
1
] | [
"You can use the mmap module to memory-map a file.\nhttp://docs.python.org/library/mmap.html\nWith mmap you can do something like this:\nfh = file('your_file', 'wb')\nmap = mmap.mmap(fh.fileno(), <length of the file you want to create>)\nmap[10] = a\nmap[25] = b\n\nNot sure if that is what you're looking for, but i... | [
-1
] | [
"file",
"file_io",
"python"
] | stackoverflow_0003756097_file_file_io_python.txt |
Q:
How to declare a method that takes an instance as an argument in Python?
I know it is probably a stupid question, but I am new to OOP in Python and if I declare a function def myFunction( b) and pass an instance of an object to it, I get TypeError: expected string or buffer.
To be more specific, I have a following... | How to declare a method that takes an instance as an argument in Python? | I know it is probably a stupid question, but I am new to OOP in Python and if I declare a function def myFunction( b) and pass an instance of an object to it, I get TypeError: expected string or buffer.
To be more specific, I have a following code that I use to parse a summary molecular formula and make an object out o... | [
"Firstly, the program needs to include the re module.\nSecondly, you have a typo at line 4:\nfor atom in re.finditer( \"([A-Z][a-z]{0,2})(\\d*)\", SummaryFormula):\n\nshould read\nfor atom in re.finditer( \"([A-Z][a-z]{0,2})(\\d*)\", summaryFormula):\n\ni.e. lower-case s in summaryFormula.\nSummaryFormula refers to... | [
1,
1,
1
] | [] | [] | [
"object",
"python"
] | stackoverflow_0003755948_object_python.txt |
Q:
Do I have to manually create the combined folder when using Python's Minimatic module?
I'm using the Python library Minimatic found at this site: Minimatic
What this essentially does is it minifies and combines all your css and js files into one file. When deploying my Pylons web application on the server, does ... | Do I have to manually create the combined folder when using Python's Minimatic module? | I'm using the Python library Minimatic found at this site: Minimatic
What this essentially does is it minifies and combines all your css and js files into one file. When deploying my Pylons web application on the server, does this mean I have to manually create the combined folders? So if I have the the directory as... | [
"Yes, Minimatic will, as of this writing, create the directories for you. I found this out by reading the source code on GitHub - lines 149 to 166 or so have your answer. \n"
] | [
0
] | [] | [] | [
"pylons",
"python"
] | stackoverflow_0003714407_pylons_python.txt |
Q:
Unable to load profile in django
I am trying to add additional fields to the default User model. I had a look around the internet and done something like this:
Made a new model named UserProfile with the following in /UserProfile/models.py:
from django.db import models
from django.contrib.auth.models import User
... | Unable to load profile in django | I am trying to add additional fields to the default User model. I had a look around the internet and done something like this:
Made a new model named UserProfile with the following in /UserProfile/models.py:
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
#... | [
"If you really did create an app caled UserProfile and put the models.py there, then you should put\nAUTH_PROFILE_MODULE = \"userprofile.userprofile\"\n\ninto your settings.py file instead.\nYou should make your UserProfile folder lowercase: userprofile\n"
] | [
4
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003756449_django_python.txt |
Q:
Timing/Recording input() in Python 3.1
I am a beginner at using Python,
I am trying to request input from the user via stdin as a string, but record the time it takes for the user to enter the input, so that it may be played back later.
For example:
"It could take me 10 seconds to type this sentence"
and then if ... | Timing/Recording input() in Python 3.1 | I am a beginner at using Python,
I am trying to request input from the user via stdin as a string, but record the time it takes for the user to enter the input, so that it may be played back later.
For example:
"It could take me 10 seconds to type this sentence"
and then if I played that sentence back it would take th... | [
"The input built-in function is fine for the input itself, and standard Python library module time probably the best way to measure time for your purposes. A simple function you can write easily puts them together:\nimport time\n\ndef timed_input(prompt):\n start = time.time()\n s = input(prompt)\n return... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0003756278_python.txt |
Q:
Implementing Server Push
Read about Server push here.
I want to push data to client from my web application in real time.
I was looking at TCP sockets as one of the options.
For HTTP I found a variety of frameworks for Java, PHP, Python and others over here.
However I don't know whether any of these support Push. ... | Implementing Server Push | Read about Server push here.
I want to push data to client from my web application in real time.
I was looking at TCP sockets as one of the options.
For HTTP I found a variety of frameworks for Java, PHP, Python and others over here.
However I don't know whether any of these support Push.
What options and frameworks... | [
"How about Orbited, it's very good and being used by Echowaves\n",
"I'm using Orbited right now, it's great!\nIf you are doing chat or subscription type stuff use stompservice and orbited.\nIf you are doing 1 to 1 client mapping use TCPSocket.\nI can give you some code examples if you want.\n",
"Comet is the pr... | [
3,
3,
3,
3,
2,
2,
1,
0
] | [] | [] | [
"java",
"php",
"python",
"ruby",
"server_push"
] | stackoverflow_0001425048_java_php_python_ruby_server_push.txt |
Q:
Python multiprocessing : progress report from processes
I have some tasks in an application that are CPU bound and I want to use the multiprocessing module to use the multi-cores processors.
I take a big task (a video file analysis) and I split it into several smaller tasks which are put in a queue and done by wor... | Python multiprocessing : progress report from processes | I have some tasks in an application that are CPU bound and I want to use the multiprocessing module to use the multi-cores processors.
I take a big task (a video file analysis) and I split it into several smaller tasks which are put in a queue and done by worker processes.
What I want to know is how to report progress ... | [
"I would recommend a multiprocessing.Queue: nothing easier than for the worker processes to post their updates (presumably as tuples with the various aspect of their progress updates) there, while the main process just wait for such messages and when they come updates the GUI (or textual UI;-) to keep the user appr... | [
14
] | [] | [] | [
"multiprocessing",
"python"
] | stackoverflow_0003756533_multiprocessing_python.txt |
Q:
Deep copy of a derived python object
I have an object in python that is derived from QtGui.QGraphicsPixmapItem with a few basic attributes and methods. After calling deepcopy on a reference to this object, I get an error saying that underlying C/C++ object has been deleted when I try to use the copy. I had receive... | Deep copy of a derived python object | I have an object in python that is derived from QtGui.QGraphicsPixmapItem with a few basic attributes and methods. After calling deepcopy on a reference to this object, I get an error saying that underlying C/C++ object has been deleted when I try to use the copy. I had received this error before, and it occured when I... | [
"QGraphicsPixmapItem is not copyable. It inherits QGraphicsItem which is declared using the Q_DISABLE_COPY macro which is the same mechanism used for QObjects to disable copying. The documentation explains it a bit better.\n"
] | [
4
] | [] | [] | [
"deep_copy",
"derived_class",
"object",
"pyqt",
"python"
] | stackoverflow_0003705994_deep_copy_derived_class_object_pyqt_python.txt |
Q:
python regex retrieve only one group
I have juste a little experience with the regex, and now I have a little problem.
I must retrieve the strings between the .
So here is a sample :
Categories: <a href="/car/2/page1.html">2</a>, <a href="/car/nissan/">nissan</a>,<a href="/car/all/page1.html">all</a>
And this is ... | python regex retrieve only one group | I have juste a little experience with the regex, and now I have a little problem.
I must retrieve the strings between the .
So here is a sample :
Categories: <a href="/car/2/page1.html">2</a>, <a href="/car/nissan/">nissan</a>,<a href="/car/all/page1.html">all</a>
And this is my little regex:
re.findall("""<a href=".*... | [
"Use parentheses to form a capturing group:\n'<a href=\".*\">(.*)</a>'\n\nYou also probably want to use a non-greedy quantifier to avoid matching far more than you intended.\n'<a href=\".*?\">(.*?)</a>'\n\nResult:\n['2', 'nissan', 'all']\n\nOr even better, consider using an HTML parser, such as BeautifulSoup.\n",
... | [
2,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003756429_python_regex.txt |
Q:
Google app engine key value error
I am writing a google app engine app and I have this key value error upon requests coming in
from the backtrace I just access and cause the key error
self.request.headers
entire code snippet is here, I just forward the headers unmodified
response = fetch( "%s%s?%s" % (
... | Google app engine key value error | I am writing a google app engine app and I have this key value error upon requests coming in
from the backtrace I just access and cause the key error
self.request.headers
entire code snippet is here, I just forward the headers unmodified
response = fetch( "%s%s?%s" % (
self... | [
"This looks weird. The docs mention that response \"Headers objects do not raise an error when you try to get or delete a key that isn't in the wrapped header list. Getting a nonexistent header just returns None\". It's not clear from the request documentation if request.headers are also objects of this class, but ... | [
2,
1,
0,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003094418_google_app_engine_python.txt |
Q:
How to create a rollback button in django with MySQLdb?
I want to create a rollback button in my django project using MySQLdb. I have tried to use commit() and rollback() with InnoDB as database engine, rollback() seems not work because the database was updated even though rollback() was put after commit(). Here i... | How to create a rollback button in django with MySQLdb? | I want to create a rollback button in my django project using MySQLdb. I have tried to use commit() and rollback() with InnoDB as database engine, rollback() seems not work because the database was updated even though rollback() was put after commit(). Here is some related lines in python code:
def update(request):
... | [
"I have no experience with MySQLdb directly, but most of the time, the rollback method is only good during a transaction. That is, if a transaction is still open, then rollback will undo everything that has happened since the start of the transaction. So when you call commit, you are ending the transaction and can ... | [
1
] | [] | [] | [
"django",
"mysql",
"python"
] | stackoverflow_0003757266_django_mysql_python.txt |
Q:
running PIL on 64bit
Is there any way of running PIL(Python Imaging Library) on a 64bit OS?
it is windows 7 64bit
A:
PIL-1.1.7.win-amd64-py2.x installers are available at http://www.lfd.uci.edu/~gohlke/pythonlibs/#pil
| running PIL on 64bit | Is there any way of running PIL(Python Imaging Library) on a 64bit OS?
it is windows 7 64bit
| [
"PIL-1.1.7.win-amd64-py2.x installers are available at http://www.lfd.uci.edu/~gohlke/pythonlibs/#pil\n"
] | [
23
] | [] | [] | [
"64_bit",
"python",
"python_imaging_library"
] | stackoverflow_0003754574_64_bit_python_python_imaging_library.txt |
Q:
findString program python
I have an assignment said that to create a findString function that accept 2 string which are 'target' and 'query', and that returns
a
list
of
all
indices
in
target
where
query
appears.
If
target
does
not
contain
query,
return
an
empty
list.
For example:
findString(‘at... | findString program python | I have an assignment said that to create a findString function that accept 2 string which are 'target' and 'query', and that returns
a
list
of
all
indices
in
target
where
query
appears.
If
target
does
not
contain
query,
return
an
empty
list.
For example:
findString(‘attaggtttattgg’,’gg’)
return:
[4,... | [
"since an answer has already been given:\ndef find_matches(strng, substrng):\n substrg_len = len(substr)\n return [i for i in range(len(strg) + 1 - substrg_len) \n if strg[i:i+substrg_len] == substrg]\n\n",
"\ndef find_string(search, needle):\n start = -1\n results = []\nwhile start + 1... | [
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003757326_python.txt |
Q:
Python programming
My assignment ask to make a function call readFasta that
accepts
one
argument:
the
name
of
a
fasta
format
file
(fn)
containing
one
or
more
sequences.
The
function
should
read
the
file
and
return
a
dictionary
where
the
keys
are
the
fasta
headers
and
the
values
... | Python programming | My assignment ask to make a function call readFasta that
accepts
one
argument:
the
name
of
a
fasta
format
file
(fn)
containing
one
or
more
sequences.
The
function
should
read
the
file
and
return
a
dictionary
where
the
keys
are
the
fasta
headers
and
the
values
are
the
corresponding ... | [
"your post is slightly confusing. I assume that you want it to return a dict. in that case, you would write it as {'one': 'actg', 'two': 'aaccttgg' }. if you correctly presented the file format, then this function should do the trick.\nimport gzip\n\ndef read_fasta(filename):\n with gzip.open(filename) as f:\n ... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0003757480_python.txt |
Q:
How to replace digits in string?
Ok say I have a string in python:
str="martin added 1 new photo to the <a href=''>martins photos</a> album."
the string contains a lot more css/html in real world use
What is the fastest way to change the 1 ('1 new photo') to say '2 new photos'. of course later the '1' may say '12... | How to replace digits in string? | Ok say I have a string in python:
str="martin added 1 new photo to the <a href=''>martins photos</a> album."
the string contains a lot more css/html in real world use
What is the fastest way to change the 1 ('1 new photo') to say '2 new photos'. of course later the '1' may say '12'.
Note, I don't know what the number ... | [
"Update\nNever mind. From the comments it is evident that the OP's requirement is more complicated than it appears in the question. I don't think it can be solved by my answer.\nOriginal Answer\nYou can convert the string to a template and store it. Use placeholders for the variables.\ntemplate = \"\"\"%(user)s add... | [
3,
2,
2
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003757738_python_regex.txt |
Q:
How would I go about reading bittorrent pieces?
I'm currently developing a torrent metainfo management library for Ruby.
I'm having trouble reading the pieces from the files. I just don't understand how I'm supposed to go about it. I know I'm supposed to SHA1 digest piece length bytes of a file once (or read piece... | How would I go about reading bittorrent pieces? | I'm currently developing a torrent metainfo management library for Ruby.
I'm having trouble reading the pieces from the files. I just don't understand how I'm supposed to go about it. I know I'm supposed to SHA1 digest piece length bytes of a file once (or read piece length bytes multiple times, or what?)
I'm counting ... | [
"C#\n// Open the file\nusing (var file = File.Open(...))\n{\n // Move to the relevant place in the file where the piece begins\n file.Seek(piece * pieceLength, SeekOrigin.Begin);\n\n // Attempt to read up to pieceLength bytes from the file into a buffer\n byte[] buffer = new byte[pieceLength];\n int ... | [
1
] | [
"Please taker a look at this distribution here:\nhttp://prdownload.berlios.de/torrentparse/TorrentParse.GTK.0.21.zip\nWritten in PHP, it contains an Encoder and Decoder and the in's and out I believe!\n"
] | [
-1
] | [
"c#",
"php",
"pseudocode",
"python",
"ruby"
] | stackoverflow_0003757965_c#_php_pseudocode_python_ruby.txt |
Q:
How to specify argument type in a dynamically typed language, i.e. Python?
Is there any such equivalent of Java
String myMethod (MyClass argument) {...}
in Python?
Thank you, Tomas
A:
No. (And more stuff to round this up to 15 characters...)
A:
No, there is not.
In fact, checking types is considered "un-Pyth... | How to specify argument type in a dynamically typed language, i.e. Python? | Is there any such equivalent of Java
String myMethod (MyClass argument) {...}
in Python?
Thank you, Tomas
| [
"No. (And more stuff to round this up to 15 characters...)\n",
"No, there is not.\nIn fact, checking types is considered \"un-Pythonic\", because an object of any type that looks enough like the expected type should be treated equally.\n",
"Python 3.x has function annotations where you can declare argument and ... | [
13,
12,
8,
4,
1
] | [] | [] | [
"dynamic",
"java",
"python",
"static"
] | stackoverflow_0003753364_dynamic_java_python_static.txt |
Q:
counting records of files on directory with python
I have wxpython application that run over a list of files on some directory and proccess the files line by line
I need to build a progress bar that show the status how records already done with wx.gauge control
I need to count the number of the records before i u... | counting records of files on directory with python | I have wxpython application that run over a list of files on some directory and proccess the files line by line
I need to build a progress bar that show the status how records already done with wx.gauge control
I need to count the number of the records before i use the wx.guage in order to build the progress bar ,
is ... | [
"I think you could do 2 progress bars, one for files, and second for line in just read file. This will be similar to copy progress in TotalCommander.\nIf you want one progress bar you could just count file sizes using os.path.getsize(path) and then show how many bytes have you processed/bytes total.\n"
] | [
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0003758468_python_wxpython.txt |
Q:
What languages would be a good replacement for Java?
I may be posting a premature question, and maybe I'm just freaking out for no reason, but the way Oracle is handling Java is not very promising. I am a nerd who fell in love with Java from the first sight, and use it all the time in my personal/freelance project... | What languages would be a good replacement for Java? | I may be posting a premature question, and maybe I'm just freaking out for no reason, but the way Oracle is handling Java is not very promising. I am a nerd who fell in love with Java from the first sight, and use it all the time in my personal/freelance projects but now I am thinking of a replacement.
I am fluent in C... | [
"Not so long ago, I decided to explore away from the JVM. I set foot on python, and even though i'm nowhere near the expert/ guru level, I dont regret it. Didn't choose C# (considered it) because I consider it to be more of the same. I alredy know (and like a lot) C++, so python seemed like something new, which is ... | [
15,
6,
3,
2,
2,
1,
1,
0,
0,
0
] | [] | [] | [
"java",
"programming_languages",
"python",
"qt",
"replace"
] | stackoverflow_0003506252_java_programming_languages_python_qt_replace.txt |
Q:
Assign class methods from YAML file
In short,I've written an application that parses text files in specified formats from different email feeds. Currently, there are two formats allowed by users in order to correctly upload information. I've also included a simple YAML file that allows people with non-programmin... | Assign class methods from YAML file | In short,I've written an application that parses text files in specified formats from different email feeds. Currently, there are two formats allowed by users in order to correctly upload information. I've also included a simple YAML file that allows people with non-programming backgrounds (ie sysadmins) to define th... | [
"I don't think the idea of having \"executable config files\" is a bad one, but I think having a mix of YAML and Python code could be confusing. Perhaps instead you could go the route of Xen, SCons, hellanzb, etc. and have your \"config file\" just be a Python script?\n"
] | [
1
] | [] | [] | [
"class_design",
"python",
"yaml"
] | stackoverflow_0003755386_class_design_python_yaml.txt |
Q:
Problem when Serving static files in Django
I have my css file in
/var/www/media/static/style.css
and added
(r'^media/(?P<path>.*)$', 'django.views.static.serve',{'document_root': '/var/www/media/static'}),
to my urls but when I go to http://localhost:8000/media/style.css I get: "Page not found: /media/style.c... | Problem when Serving static files in Django | I have my css file in
/var/www/media/static/style.css
and added
(r'^media/(?P<path>.*)$', 'django.views.static.serve',{'document_root': '/var/www/media/static'}),
to my urls but when I go to http://localhost:8000/media/style.css I get: "Page not found: /media/style.css" what is wrong?
| [
"Have you updated your settings.MEDIA_ROOT (the filesystem path) and settings.MEDIA_URL (the URL for static assets) to reflect the setup of your project?\n",
"Check the logging output to see what's actually been requested - I've found that to be particularly helpful in diagnosing these issues.\n",
"The problem ... | [
0,
0,
0
] | [] | [] | [
"django",
"python",
"static"
] | stackoverflow_0003746586_django_python_static.txt |
Q:
What encoding looks exactly like ASCII but has NULL bytes before each byte?
I have a string that looks and behaves as follows (Python code provided). WTF?! What encoding is it in?
s = u'\x00Q\x00u\x00i\x00c\x00k'
>>> print s
Quick
>>>
>>> s == 'Quick'
False
>>>
>>> import re
>>> re.search('Quick', s)
>>>
>>> impor... | What encoding looks exactly like ASCII but has NULL bytes before each byte? | I have a string that looks and behaves as follows (Python code provided). WTF?! What encoding is it in?
s = u'\x00Q\x00u\x00i\x00c\x00k'
>>> print s
Quick
>>>
>>> s == 'Quick'
False
>>>
>>> import re
>>> re.search('Quick', s)
>>>
>>> import chardet
>>> chardet.detect(s)
/usr/lib/pymodules/python2.6/chardet/universaldet... | [
"UTF-16 big endian\n",
"You have UTF-16BE without a BOM. As documented, chardet doesn't grok UTF-nnxE without a BOM.\n>>> s = '\\x00Q\\x00u\\x00i\\x00c\\x00k' #### Note: dropping the spurious `u` prefix\n>>> s.decode('utf_16be')\nu'Quick'\n>>>\n\nchardet is also not smart enough to raise a DontBeSilly exception i... | [
8,
2
] | [] | [] | [
"character_encoding",
"python"
] | stackoverflow_0003759189_character_encoding_python.txt |
Q:
creating xml tree from a textfile with Python
I need to avoid creating double branches in an xml tree when parsing a text file. Let's say the textfile is as follows (the order of lines is random):
branch1:branch11:message11
branch1:branch12:message12
branch2:branch21:message21
branch2:branch22:message22
So the res... | creating xml tree from a textfile with Python | I need to avoid creating double branches in an xml tree when parsing a text file. Let's say the textfile is as follows (the order of lines is random):
branch1:branch11:message11
branch1:branch12:message12
branch2:branch21:message21
branch2:branch22:message22
So the resulting xml tree should have a root with two branche... | [
"with open(\"xmlbasic.txt\") as lines_file:\n lines = lines_file.read()\n\nimport xml.etree.ElementTree as ET\n\nroot = ET.Element('root')\n\nfor line in lines:\n head, subhead, tail = line.split(\":\")\n\n head_branch = root.find(head)\n if not head_branch:\n head_branch = ET.SubElement(root, he... | [
1,
0
] | [] | [] | [
"elementtree",
"python",
"xml"
] | stackoverflow_0003759200_elementtree_python_xml.txt |
Q:
How to use delete() method in Google App Engine Python's request handler
In GAE Python, I could use
class MyRequestHandler(webapp.RequestHandler):
def get(self):
pass #Do Something...
def post(self):
pass #Do Something...
To handle GET and POST request. But how can I handle DELETE and PUT... | How to use delete() method in Google App Engine Python's request handler | In GAE Python, I could use
class MyRequestHandler(webapp.RequestHandler):
def get(self):
pass #Do Something...
def post(self):
pass #Do Something...
To handle GET and POST request. But how can I handle DELETE and PUT? I see delete() and put() in API documentation, but I don't know how to write... | [
"You can use the request method which accepts all the methods like get,post,delete and put.\nThen you can check it for the request type accordingly.\nCheck this:\nhttp://gdata-python-client.googlecode.com/svn/trunk/pydocs/gdata.urlfetch.html\n<form method=\"post\" action=\"\">\n <input type=\"hidden\" name=\"_metho... | [
6,
4,
0,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003740823_google_app_engine_python.txt |
Q:
Django string in unicode pattern
Django when i send the following string from an ajax submit i get the following string in unicode.How to decode this
$.post("/records/save_t/",snddata,
function(data){
if(data == 0 ){
}
},"json");
In django
def save_t(request):
if request.method == 'GE... | Django string in unicode pattern | Django when i send the following string from an ajax submit i get the following string in unicode.How to decode this
$.post("/records/save_t/",snddata,
function(data){
if(data == 0 ){
}
},"json");
In django
def save_t(request):
if request.method == 'GET':
qd = request.GET
elif ... | [
"Why do you think you need to convert it to a string? What's wrong with it as Unicode? It should be perfectly usable as it is.\nIn any case, what you have is a list containing a single unicode string (because you've used getlist, which always unsurprisingly returns a list). Is the actual problem just that you want ... | [
0
] | [] | [] | [
"django",
"django_models",
"django_views",
"python"
] | stackoverflow_0003759598_django_django_models_django_views_python.txt |
Q:
is it possible to have keyname and an id for an entity in Appengine?
I'm building a facebook app, and my users table's keyName is set to the Uid of the facebook user. I found this to be efficient because I can use db.Key.from_path() to efficiently query the datastore for a particular user instead of doing a query ... | is it possible to have keyname and an id for an entity in Appengine? | I'm building a facebook app, and my users table's keyName is set to the Uid of the facebook user. I found this to be efficient because I can use db.Key.from_path() to efficiently query the datastore for a particular user instead of doing a query (where uid = x, limit = 1). This is actually my first time using key names... | [
"No. An entity's Key is composed of the application ID, the Kind, the path of the parent entity (if any) and either a key name or an auto-generated ID. It's not possible to have both. The entire Key is the \"primary key\".\n"
] | [
2
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003759021_google_app_engine_python.txt |
Q:
What are the downsides of using Python instead of Objective-C?
I know some Python and I'm really impressed by the language's ease of use. From what I've seen of Objective-C it looks a lot less pretty, but it seems to be the lingua franca for Mac OS X development (which means it has better documentation).
I'm thin... | What are the downsides of using Python instead of Objective-C? | I know some Python and I'm really impressed by the language's ease of use. From what I've seen of Objective-C it looks a lot less pretty, but it seems to be the lingua franca for Mac OS X development (which means it has better documentation).
I'm thinking about starting Mac development - will using PyObjC+Python make ... | [
"Yes.\nFor one thing, as you note, all the documentation is written for Objective-C, which is a very different language.\nOne difference is method name. In Objective-C, when you send a message to (Python would say “call a method of”) an object, the method name (selector) and arguments are mixed:\nNSURL *URL = /*…*/... | [
37,
18,
3,
2,
0,
0,
0,
0
] | [] | [] | [
"cocoa",
"macos",
"pyobjc",
"python"
] | stackoverflow_0002175573_cocoa_macos_pyobjc_python.txt |
Q:
Python: get path to file in sister directory?
I have a file structure like this:
data
mydata.xls
scripts
myscript.py
From within myscript.py, how can I get the filepath of mydata.xls?
I need to pass it to xlrd:
book = xlrd.open_workbook(filename)
and relative filepaths like '../data/mydata.xls' don't seem ... | Python: get path to file in sister directory? | I have a file structure like this:
data
mydata.xls
scripts
myscript.py
From within myscript.py, how can I get the filepath of mydata.xls?
I need to pass it to xlrd:
book = xlrd.open_workbook(filename)
and relative filepaths like '../data/mydata.xls' don't seem to work.
| [
"You can use os.path.abspath(<relpath>) to get an absolute path from a relative one.\nvinko@parrot:~/p/f$ more a.py\nimport os\nprint os.path.abspath('../g/a')\n\nvinko@parrot:~/p/f$ python a.py\n/home/vinko/p/g/a\n\nThe dir structure:\nvinko@parrot:~/p$ tree\n.\n|-- f\n| `-- a.py\n`-- g\n `-- a\n\n2 directori... | [
10,
9,
4
] | [
"From you comments, it seems that book = xlrd.open_workbook(filename) doesn't like relative path. You can create a path relative to the current file __file__ and then take the absolute path that will remove the relative portions (..)\nimport os\n\nfilename = os.path.join(os.path.dirname(__file__), '../data/mydata.x... | [
-1
] | [
"python"
] | stackoverflow_0003758866_python.txt |
Q:
python string pattern matching
new_str="@@2@@*##1"
new_str1="@@3@@*##5##7"
How to split the above string in python
for val in new_str.split("@@*"):
logging.debug("=======")
logging.debug(val[2:]) // will give
for st in val.split("@@*"):
... | python string pattern matching | new_str="@@2@@*##1"
new_str1="@@3@@*##5##7"
How to split the above string in python
for val in new_str.split("@@*"):
logging.debug("=======")
logging.debug(val[2:]) // will give
for st in val.split("@@*"):
//how to get the values after ## i... | [
"I don't understand the question.\nAre you trying to split a string by a delimiter? Then use split:\n>>> a = \"@@2@@*##1\"\n>>> b = \"@@3@@*##5##7\"\n>>>\n>>> a.split(\"@@*\")\n['@@2', '##1']\n>>> b.split(\"@@*\")\n['@@3', '##5##7']\n\nAre you trying to strip extraneous characters from a string? Then use strip:\n>>... | [
4
] | [] | [] | [
"python"
] | stackoverflow_0003760075_python.txt |
Q:
What is the equivalent of Ruby require?
I am coming to Python from Ruby.
What is the equivalent statement of require in Python?
A:
The import statement.
Maybe it's advisable you follow a Python tutorial where much of the basics are explained
| What is the equivalent of Ruby require? | I am coming to Python from Ruby.
What is the equivalent statement of require in Python?
| [
"The import statement.\nMaybe it's advisable you follow a Python tutorial where much of the basics are explained\n"
] | [
5
] | [] | [] | [
"equivalent",
"python",
"require"
] | stackoverflow_0003760247_equivalent_python_require.txt |
Q:
allow_none in twisted XML-RPC server
I am building xml rpc service using twisted and I would like to use None just as it can be done in standard python lib. How can I pass allow_none to the twisted version of xmlrpc server?
EDIT
In [28]: sock = rpc.ServerProxy('http://localhost:7080',allow_none=True)
In [29]: soc... | allow_none in twisted XML-RPC server | I am building xml rpc service using twisted and I would like to use None just as it can be done in standard python lib. How can I pass allow_none to the twisted version of xmlrpc server?
EDIT
In [28]: sock = rpc.ServerProxy('http://localhost:7080',allow_none=True)
In [29]: sock
Out[29]: <ServerProxy for localhost:7080... | [
"XMLRPC accepts allowNone as an argument to its initializer. So, pass True when instantiating your resources if you want to support None.\nfrom twisted.web.xmlrpc import XMLRPC\nresource = XMLRPC(allowNone=True)\n\n",
"I think it should be specified on client side...\nwhen you create the proxy from your xmlrpc c... | [
8,
0
] | [] | [] | [
"python",
"twisted",
"xml_rpc"
] | stackoverflow_0003760043_python_twisted_xml_rpc.txt |
Q:
What are the WordPress analogs\clones that would run under Google App Engine?
So I want it to run on free google app engine version, I want it to be more or less structured like WP (meaning end user experience). I need clean readable source so I could change it as I wish.
If there are no such alike WP ones than s... | What are the WordPress analogs\clones that would run under Google App Engine? | So I want it to run on free google app engine version, I want it to be more or less structured like WP (meaning end user experience). I need clean readable source so I could change it as I wish.
If there are no such alike WP ones than some other Blog Engine would work for me.
What are the WordPress analogs\clones that... | [
"Roller is a good Java-based blog engine. I'm not sure if it works with GAE but I can't see why it wouldn't.\n"
] | [
1
] | [] | [] | [
"blogs",
"google_app_engine",
"java",
"python",
"wordpress"
] | stackoverflow_0003760384_blogs_google_app_engine_java_python_wordpress.txt |
Q:
Setting window style in PyQT/PySide?
I've been looking for how to do this and I've found places where the subject comes up, but none of the suggestions actually work for me, even though they seem to work out okay for the questioner (they don't even list what to import). I ran across self.setWindowFlags(Qt.Frameles... | Setting window style in PyQT/PySide? | I've been looking for how to do this and I've found places where the subject comes up, but none of the suggestions actually work for me, even though they seem to work out okay for the questioner (they don't even list what to import). I ran across self.setWindowFlags(Qt.FramelessWindowHint) but it doesn't seem to work r... | [
"u need to import QtCore\n\n\nso the code will look like this : \n self.setWindowFlags(QtCore.Qt.FramelessWindowHint) \nwhenever you see Qt.something put in mind that they are talking about the Qt class inside QtCore module .\nhope this helps \n"
] | [
13
] | [] | [] | [
"pyqt",
"pyside",
"python"
] | stackoverflow_0003758648_pyqt_pyside_python.txt |
Q:
Converting domain names to idn in python
I have a long list of domain names which I need to generate some reports on. The list contains some IDN domains, and although I know how to convert them in python on the command line:
>>> domain = u"pfarmerü.com"
>>> domain
u'pfarmer\xfc.com'
>>> domain.encode("idna")
'xn--... | Converting domain names to idn in python | I have a long list of domain names which I need to generate some reports on. The list contains some IDN domains, and although I know how to convert them in python on the command line:
>>> domain = u"pfarmerü.com"
>>> domain
u'pfarmer\xfc.com'
>>> domain.encode("idna")
'xn--pfarmer-t2a.com'
>>>
I'm struggling to get i... | [
"you need to know in which encoding you file was saved. This would be something like 'utf-8' (which is NOT Unicode) or 'iso-8859-1' or 'cp1252' or alike.\nThen you can do (assuming 'utf-8'):\n\ninfile = open(sys.argv[1])\n\nfor line in infile:\n print line,\n domain = line.strip().decode('utf-8')\n print t... | [
22,
2
] | [] | [] | [
"python",
"unicode"
] | stackoverflow_0003760338_python_unicode.txt |
Q:
How to order by ancestor/parent Google App Engine query?
I would like to order entities by ancestor, GQL reference only mentions properties in ordering. Do I have to store a parent as a property to involve it in the ordering?
I trying to achieve something like this:
Foo.all().ancestor(bar).order('ancestor').order(... | How to order by ancestor/parent Google App Engine query? | I would like to order entities by ancestor, GQL reference only mentions properties in ordering. Do I have to store a parent as a property to involve it in the ordering?
I trying to achieve something like this:
Foo.all().ancestor(bar).order('ancestor').order('-value').fetch(100)
EDIT:
I have something like this:
bar
├... | [
"Ordering by key will sort first by ancestors, then by the id or name of the entity. If you want to sort by ancestor but not by id/name of the entity itself then yes, you'll need to include an explicit 'ancestor' SelfReferenceProperty to sort on.\n"
] | [
4
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0003759713_google_app_engine_google_cloud_datastore_python.txt |
Q:
Java oneliner for list cleanup
Is there a construct in java that does something like this(here implemented in python):
[] = [item for item in oldList if item.getInt() > 5]
Today I'm using something like:
ItemType newList = new ArrayList();
for( ItemType item : oldList ) {
if( item.getInt > 5) {
newList.a... | Java oneliner for list cleanup | Is there a construct in java that does something like this(here implemented in python):
[] = [item for item in oldList if item.getInt() > 5]
Today I'm using something like:
ItemType newList = new ArrayList();
for( ItemType item : oldList ) {
if( item.getInt > 5) {
newList.add(item);
}
}
And to me the fir... | [
"Java 7 might or might not implement closures and hence support functionality like this, but currently it doesn't, so on the Java VM you have the options to do it in Groovy, Scala or Clojure (possible others, too), but in java you can only get close to that by using helpers like Guava's Collections2.filter().\nJDK ... | [
5,
3,
1,
1,
0
] | [] | [] | [
"closures",
"collections",
"java",
"python"
] | stackoverflow_0003760120_closures_collections_java_python.txt |
Q:
How to stay under GAE quotas? Algorithm design
I have a function in my app that uses a lot of resources, and takes time to execute.
This is normal and control, however I often get errors due to GAE limit of 30 secs/request.
My function takes the argument and returns several results one after the other, decreasing ... | How to stay under GAE quotas? Algorithm design | I have a function in my app that uses a lot of resources, and takes time to execute.
This is normal and control, however I often get errors due to GAE limit of 30 secs/request.
My function takes the argument and returns several results one after the other, decreasing the size of the argument (a unicode string)
Summary:... | [
"I would suggest that you use the Task Queue API, which is perfectly suited to this kind of problems.\nBe aware that if you enable billing on your application, you automatically get much larger free quotas : the Task Queue API calls daily limit increases to 20,000,000.\nYou can set your max daily budget as low as $... | [
1
] | [] | [] | [
"algorithm",
"google_app_engine",
"python"
] | stackoverflow_0003759637_algorithm_google_app_engine_python.txt |
Q:
Create one keybord shortcut for 2 objects in PyQt
How can i create for "Ctrl+C" bindings for 2 objects: self.table, self.editor
I have:
shortcut = QtGui.QShortcut(QtGui.QKeySequence("Ctrl+C"), self.table, None, self.copyTable)
shortcut2 = QtGui.QShortcut(QtGui.QKeySequence("Ctrl+C"), self.editor, None, self.copyTe... | Create one keybord shortcut for 2 objects in PyQt | How can i create for "Ctrl+C" bindings for 2 objects: self.table, self.editor
I have:
shortcut = QtGui.QShortcut(QtGui.QKeySequence("Ctrl+C"), self.table, None, self.copyTable)
shortcut2 = QtGui.QShortcut(QtGui.QKeySequence("Ctrl+C"), self.editor, None, self.copyText)
This works, but is toogled. If i have focus on sel... | [
"You have to set the correct context for short cuts: by default they are window-\"global\", you probably want them to be widget-\"local\". See setShortcutContext.\n",
"i did that already here and it worked fine ^_^. very simple idea .\n\njust make one shortcut and one slot.\n\nQtGui.QShortcut(QtGui.QKeySequence(... | [
3,
3
] | [] | [] | [
"pyqt",
"python"
] | stackoverflow_0003724697_pyqt_python.txt |
Q:
Python not recognising directories os.path.isdir()
I have the following Python code to remove files in a directory.
For some reason my .svn directories are not being recognised as directories.
And I get the following output:
.svn not a dir
Any ideas would be appreciated.
def rmfiles(path, pattern):
pattern =... | Python not recognising directories os.path.isdir() | I have the following Python code to remove files in a directory.
For some reason my .svn directories are not being recognised as directories.
And I get the following output:
.svn not a dir
Any ideas would be appreciated.
def rmfiles(path, pattern):
pattern = re.compile(pattern)
for each in os.listdir(path):
... | [
"You need to create the full path name before checking:\nif not os.path.isdir(os.path.join(path, each)):\n ...\n\n",
"You will need to os.path.join the path you invoke listdir on with the found file/directory, i.e.\nfor each in os.listdir(path):\n if os.path.isdir(os.path.join(path, each)):\n ....\n\nI... | [
59,
3,
0
] | [] | [] | [
"directory",
"file_io",
"path",
"python"
] | stackoverflow_0003761473_directory_file_io_path_python.txt |
Q:
How to Compare 2 very large matrices using Python
I have an interesting problem.
I have a very large (larger than 300MB, more than 10,000,000 lines/rows in the file) CSV file with time series data points inside. Every month I get a new CSV file that is almost the same as the previous file, except for a few new lin... | How to Compare 2 very large matrices using Python | I have an interesting problem.
I have a very large (larger than 300MB, more than 10,000,000 lines/rows in the file) CSV file with time series data points inside. Every month I get a new CSV file that is almost the same as the previous file, except for a few new lines have been added and/or removed and perhaps a couple ... | [
"Like this.\nStep 1. Sort. \nStep 2. Read each file, doing line-by-line comparison. Write differences to another file.\nYou can easily write this yourself. Or you can use difflib. http://docs.python.org/library/difflib.html\nNote that the general solution is quite slow as it searches for matching lines near a... | [
4,
1
] | [] | [] | [
"data_structures",
"django",
"matrix",
"python"
] | stackoverflow_0003760615_data_structures_django_matrix_python.txt |
Q:
Problem Accessing WSDL-Service with python suds raises TypeNotFound: ArrayOfint
Type not found: '(ArrayOfint, http://schemas.microsoft.com/2003/10/Serialization/Arrays, )'
is what suds resolver raises.
In ...2003/10/Serialization/Arrays ArrayOfInt is defined, so I guess linux' case sensitivity is the problem.
An... | Problem Accessing WSDL-Service with python suds raises TypeNotFound: ArrayOfint | Type not found: '(ArrayOfint, http://schemas.microsoft.com/2003/10/Serialization/Arrays, )'
is what suds resolver raises.
In ...2003/10/Serialization/Arrays ArrayOfInt is defined, so I guess linux' case sensitivity is the problem.
Any Idea how I can get around that?
from suds.client import Client
c = Client("https:/... | [
"Sounds like you have a broken WSDL. This is where you'll need to use the ImportDoctor provided by SUDS. You need use this to help the Client constructor use the ArrayOfint type found at http://schemas.microsoft.com/2003/10/Serialization/Arrays. \nI have done this in the past with other services but without seein... | [
6
] | [] | [] | [
"python",
"suds",
"wsdl"
] | stackoverflow_0003760427_python_suds_wsdl.txt |
Q:
Python Music Library?
I'm looking at writing a little drum machine in Python for fun. I've googled some and found the python pages on music and basic audio as well as a StackOverflow question on generating audio files, but what I'm looking for is a decent library for music creation. Has anyone on here tried to d... | Python Music Library? | I'm looking at writing a little drum machine in Python for fun. I've googled some and found the python pages on music and basic audio as well as a StackOverflow question on generating audio files, but what I'm looking for is a decent library for music creation. Has anyone on here tried to do something like this befor... | [
"Take a close look at cSounds. There are Python bindings allow you to do pretty flexible digital synthesis. There are some pretty complete packages available, too. \nSee http://www.csounds.com/node/188 for a package.\nSee http://www.csounds.com/journal/issue6/pythonOpcodes.html for information on Python scriptin... | [
14,
8,
4,
3,
2
] | [] | [] | [
"audio",
"python"
] | stackoverflow_0000108848_audio_python.txt |
Q:
Using PayPal with AppEngine (Python)
I'm looking to use Google AppEngine (Python). The Tipfy framework looks very good. How do I add PayPal and/or Google Web Payments into my app.
Is there a simple extension or similar that I can drop in?
A:
Here's the blog entry where they introduce the PayPal X toolkit for GA... | Using PayPal with AppEngine (Python) | I'm looking to use Google AppEngine (Python). The Tipfy framework looks very good. How do I add PayPal and/or Google Web Payments into my app.
Is there a simple extension or similar that I can drop in?
| [
"Here's the blog entry where they introduce the PayPal X toolkit for GAE/J:\nWednesday, June 30, 2010\nPayPal introduces PayPal X Platform Toolkit for Google App Engine\nhttp://googleappengine.blogspot.com/2010/06/paypal-introduces-paypal-x-platform.html\nIn that article it says that they are working on the Python ... | [
2
] | [] | [] | [
"google_app_engine",
"paypal_ipn",
"python",
"tipfy"
] | stackoverflow_0003758827_google_app_engine_paypal_ipn_python_tipfy.txt |
Q:
Wrap std::vector of std::vectors, C++ SWIG Python
I want to wrap a C++ vector of vectors to Python code by using SWIG.
Is it possible to wrap this type of vector of vectors?
std::vector<std::vector<MyClass*>>;
In the interface file MyApplication.i I added these lines:
%include "std_vector.i"
%{
#include <vector>... | Wrap std::vector of std::vectors, C++ SWIG Python | I want to wrap a C++ vector of vectors to Python code by using SWIG.
Is it possible to wrap this type of vector of vectors?
std::vector<std::vector<MyClass*>>;
In the interface file MyApplication.i I added these lines:
%include "std_vector.i"
%{
#include <vector>
%}
namespace std {
%template(VectorOfStructVecto... | [
"Is it a C++ parsing issue?\n std::vector<std::vector<MyClass*> >;\n ---Important space---------------^\n\n"
] | [
4
] | [] | [] | [
"c++",
"python",
"swig",
"vector"
] | stackoverflow_0003761861_c++_python_swig_vector.txt |
Q:
Passing data from a virtual printer to python
I am trying to make a thing where in other applications you can print to a certain printer and python will get the data. How would I go about making this? It would have to work in all applications, so it would appear as a normal printer, and work on Linux and Windows, ... | Passing data from a virtual printer to python | I am trying to make a thing where in other applications you can print to a certain printer and python will get the data. How would I go about making this? It would have to work in all applications, so it would appear as a normal printer, and work on Linux and Windows, even if I have to rewrite it for both.
So to reca... | [
"Most Linux distros (and OS X) and use CUPS to do printing these days. A CUPS backends for a specific printer is ultimately just an executable, which you can make do anything you want. The CUPS project provides filter/backend API documentation. There also exists at least one open-source CUPS virtual printer in th... | [
2
] | [] | [] | [
"printing",
"python",
"virtual"
] | stackoverflow_0003761865_printing_python_virtual.txt |
Q:
Understanding python variable scope within class
I am trying to define a variable in a class that then can be accessed/changed from functions within that class.
For example:
class MyFunctions():
def __init__( self):
self.listOfItems = []
def displayList( self):
"""Prints all items in listO... | Understanding python variable scope within class | I am trying to define a variable in a class that then can be accessed/changed from functions within that class.
For example:
class MyFunctions():
def __init__( self):
self.listOfItems = []
def displayList( self):
"""Prints all items in listOfItems)"""
for item in self.listOfItems:
... | [
"f.addToList and f.displayList do not invoke the methods addToList and displayList respectively. They simply evaluate to the method (bound to the object f in this case) themselves. Add parentheses to invoke the methods as in the corrected version of the program:\nclass MyFunctions():\n def __init__( self):\n ... | [
6
] | [] | [] | [
"call",
"methods",
"python",
"syntax"
] | stackoverflow_0003762197_call_methods_python_syntax.txt |
Q:
Checking Version of Python Interpreter Upon Execution of Script With Invalid Syntax
I have a Python script that uses Python version 2.6 syntax (Except error as value:) which version 2.5 complains about. So in my script I have included some code to check for the Python interpreter version before proceeding so that ... | Checking Version of Python Interpreter Upon Execution of Script With Invalid Syntax | I have a Python script that uses Python version 2.6 syntax (Except error as value:) which version 2.5 complains about. So in my script I have included some code to check for the Python interpreter version before proceeding so that the user doesn't get hit with a nasty error, however, no matter where I place that code, ... | [
"Create a wrapper script that checks the version and calls your real script -- this gives you a chance to check the version before the interpreter tries to syntax-check the real script.\n",
"Something like this in beginning of code?\nimport sys\nif sys.version_info<(2,6):\n raise SystemExit('Sorry, this code n... | [
15,
15,
9,
1
] | [] | [] | [
"interpreter",
"python"
] | stackoverflow_0003760098_interpreter_python.txt |
Q:
SWIG - Problem with namespaces
I'm having trouble getting the following simple example to work with SWIG 1.3.40 (and I also tried 1.3.31). The Foo structure comes through as a Python module as long as I don't wrap it in a namespace, but as soon as I do I get a compilation error in the generated test_wrap.c.
test.... | SWIG - Problem with namespaces | I'm having trouble getting the following simple example to work with SWIG 1.3.40 (and I also tried 1.3.31). The Foo structure comes through as a Python module as long as I don't wrap it in a namespace, but as soon as I do I get a compilation error in the generated test_wrap.c.
test.h:
#ifndef __TEST_H__
#define __TEST... | [
"In your test.i file, add a \"using namespace ns\" line after the #include. Without that, your swig wrapper code won't know to look for Foo in the \"ns\" namespace.\n"
] | [
18
] | [] | [] | [
"c++",
"macos",
"namespaces",
"python",
"swig"
] | stackoverflow_0003696084_c++_macos_namespaces_python_swig.txt |
Q:
How's Python GUI development today (Sep/2010)?
Last time I saw, GUIs in Python were extremely ugly, how's it today?
(saw some beautiful images on google images, but I don't know if are really Python's)
A:
Python 2.7 and 3.0 ships with the themed tk ("ttk") widgets which look much better than previous versions of... | How's Python GUI development today (Sep/2010)? | Last time I saw, GUIs in Python were extremely ugly, how's it today?
(saw some beautiful images on google images, but I don't know if are really Python's)
| [
"Python 2.7 and 3.0 ships with the themed tk (\"ttk\") widgets which look much better than previous versions of Tk (though, honestly, any competent GUI developer can make even older Tk look good). Don't let the people who don't know much about Tk sway you from using it, it's still a very viable toolkit for many, ma... | [
7,
2,
1,
1
] | [] | [] | [
"python",
"user_interface"
] | stackoverflow_0003760714_python_user_interface.txt |
Q:
How do I find out the Python, Django versions and path that a Django site is running?
I currently have multiple Django sites running from one Apache server through WSGI and each site has their own virtualenv with possibly slight Python and Django version difference. For each site, I want to display the Python and... | How do I find out the Python, Django versions and path that a Django site is running? | I currently have multiple Django sites running from one Apache server through WSGI and each site has their own virtualenv with possibly slight Python and Django version difference. For each site, I want to display the Python and Django version it is using as well as from which path it's pulling the Python binaries fro... | [
"\nbut I'm not sure if it's showing the Python that the site is using or the system's Python. Any help on that?\n\nNope.\nHowever, if you want to know something about your Django app, do this.\n\nUse logging. Write to sys.stderr that's usually routed to errors_log by mod_wsgi. Or look inside the request for the w... | [
0,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003761681_django_python.txt |
Q:
Python daemon will not run in the background on Ubuntu
My Python daemon runs fine in the foreground of my Ubuntu system using this command in the terminal:
python /opt/my-daemon.py foreground
However when I try to call the daemon using the "start" command it fails, why?
python /opt/my-daemon.py start
This is how... | Python daemon will not run in the background on Ubuntu | My Python daemon runs fine in the foreground of my Ubuntu system using this command in the terminal:
python /opt/my-daemon.py foreground
However when I try to call the daemon using the "start" command it fails, why?
python /opt/my-daemon.py start
This is how I call the command in the /etc/rc.local file:
python /opt/m... | [
"SOLVED. I was under the impression that the foreground and the start parameter was two different things. It turns out I just needed to do the following.\ndef run(self):\n while True:\n time.sleep(2)\n\nto \ndef start(self):\n while True:\n time.sleep(2)\n\nI then removed the foreground paramete... | [
1,
0,
0
] | [] | [] | [
"daemon",
"linux",
"python",
"ubuntu_10.04",
"unix"
] | stackoverflow_0003449066_daemon_linux_python_ubuntu_10.04_unix.txt |
Q:
python line editing telnet server
I am creating a server in python (what it is doing is irrelevant), but I would like it to accept telnet connections and provide a command line interface with line editing capabilities (tabcompletion, emacs/vi-mode, etc) and history per session. I have successfully created the teln... | python line editing telnet server | I am creating a server in python (what it is doing is irrelevant), but I would like it to accept telnet connections and provide a command line interface with line editing capabilities (tabcompletion, emacs/vi-mode, etc) and history per session. I have successfully created the telnet session, disabled line mode and enab... | [
"It sounds like you've got the TELNET part sorted, and now you want to provide features commonly found in shells like BASH, KSH etc. I've not tried it myself, but have a look as shython: \"a versatile shell having features of both bash and python\".\n",
"Perhaps the cmd library could be of interest/help?\n",
"Y... | [
2,
1,
0
] | [] | [] | [
"libreadline",
"python",
"sockets",
"telnet"
] | stackoverflow_0003412832_libreadline_python_sockets_telnet.txt |
Q:
Python vs. C++ for an application that does sparse linear algebra
I'm writing an application where quite a bit of the computational time will be devoted to performing basic linear algebra operations (add, multiply, multiply by vector, multiply by scalar, etc.) on sparse matrices and vectors. Up to this point, we'v... | Python vs. C++ for an application that does sparse linear algebra | I'm writing an application where quite a bit of the computational time will be devoted to performing basic linear algebra operations (add, multiply, multiply by vector, multiply by scalar, etc.) on sparse matrices and vectors. Up to this point, we've built a prototype using C++ and the Boost matrix library.
I'm consid... | [
"My advice is to fully test the algorithm in Python before translating it into any other language (otherwise you run the risk of optimizing prematurely a bad algorithm). Once you have clearly defined the best interface for your problems, you can factor it out to external code.\nLet me explain.\nSuppose your final a... | [
7,
4,
4,
2,
1
] | [] | [] | [
"c++",
"linear_algebra",
"python"
] | stackoverflow_0003761994_c++_linear_algebra_python.txt |
Q:
Python: subprocess with different working directory
I have a python script that is under this directory:
work/project/test/a.py
Inside a.py, I use subprocess.POPEN to launch the process from another directory,
work/to_launch/file1.pl, file2.py, file3.py, ...
Python Code:
subprocess.POPEN("usr/bin/perl ../to_laun... | Python: subprocess with different working directory | I have a python script that is under this directory:
work/project/test/a.py
Inside a.py, I use subprocess.POPEN to launch the process from another directory,
work/to_launch/file1.pl, file2.py, file3.py, ...
Python Code:
subprocess.POPEN("usr/bin/perl ../to_launch/file1.pl")
and under work/project/, I type the follo... | [
"Your code does not work, because the relative path is seen relatively to your current location (one level above the test/a.py).\nIn sys.path[0] you have the path of your currently running script.\nUse os.path.join(os.path.abspath(sys.path[0]), relPathToLaunch) with relPathToLaunch = '../to_launch/file1.pl' to get ... | [
17,
3,
0
] | [] | [] | [
"python",
"subprocess",
"working_directory"
] | stackoverflow_0003762468_python_subprocess_working_directory.txt |
Q:
How to connect to internet & load html using python/urllib in ubuntu?
I am new to programming, i had some problem with the code..
Here i have posted the code below.
Actually after running the program its shows some error...
ERROR:
It shows some traceback error
import urllib
proxies = {'http' : 'http://proxy:80'}
... | How to connect to internet & load html using python/urllib in ubuntu? | I am new to programming, i had some problem with the code..
Here i have posted the code below.
Actually after running the program its shows some error...
ERROR:
It shows some traceback error
import urllib
proxies = {'http' : 'http://proxy:80'}
urlopener = urllib.FancyURLopener(proxies)
htmlpage = urlopener.open('http:... | [
"You need indent your python and replace readlines() with read()\nimport urllib \nproxies = {'http' : 'http://proxy:80'} \nurlopener = urllib.FancyURLopener(proxies) \nhtmlpage = urlopener.open('http://www.google.com') \ndata = htmlpage.read() \nprint data\n\n"
] | [
1
] | [] | [] | [
"python",
"urllib"
] | stackoverflow_0003509284_python_urllib.txt |
Q:
examples of common middleware people use in pylons?
Just trying to get a feel for what common middleware people use in pylons?
Is middleware just the main pipeline for the request and response object?
i.e. would it be possbile to create a very simple middleware that outputs 'hello world' to the screen?
A:
The de... | examples of common middleware people use in pylons? | Just trying to get a feel for what common middleware people use in pylons?
Is middleware just the main pipeline for the request and response object?
i.e. would it be possbile to create a very simple middleware that outputs 'hello world' to the screen?
| [
"The default middleware is the pipeline, as you guessed. However, my impression is that after that, \"common middleware\" is slightly oxymoronic, especially for a loosely coupled framework like Pylons. The framework's setup suggests \"here is the basic middleware - and here's where to put middleware that you write... | [
1
] | [] | [] | [
"middleware",
"pylons",
"python"
] | stackoverflow_0003709385_middleware_pylons_python.txt |
Q:
login_form_seq ? in python
can some one give me example and explain how to use login_form_seq in python and login_form_data .. and this simple example but i don't know really how to deal with that !!
login_form_seq = [
('log', sys.argv[2]),
('pwd', word),
('rememberme', 'forever'),
('wp-submit', 'Login >>'),
(... | login_form_seq ? in python | can some one give me example and explain how to use login_form_seq in python and login_form_data .. and this simple example but i don't know really how to deal with that !!
login_form_seq = [
('log', sys.argv[2]),
('pwd', word),
('rememberme', 'forever'),
('wp-submit', 'Login >>'),
('redirect_to', 'wp-admin/')]
z=0... | [
"You may try this...\nimport sys, urllib, urllib2\nword = \"YOUR WORD\"\n login_form_seq = { \n 'log', sys.argv[2],\n 'pwd', word,\n 'rememberme', 'forever',\n 'wp-submit', 'Login >>',\n 'redirect_to', 'wp-admin/'\n }\n z=0\n login_form_data = urllib.urlencode(... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0003595189_python.txt |
Q:
Finding maximum value in a dictionary containing mixed items in Python
I have a dictionary with either a integer or a tuple of integers as value. How do I find the maximum integer present in dicts' values?
Example:
x1 = {0:2, 2:1, 3:(1, 2), 20:3}
should return 3
and
x2 = {0:2, 2:1, 3:(1, 5), 20:3}
should return ... | Finding maximum value in a dictionary containing mixed items in Python | I have a dictionary with either a integer or a tuple of integers as value. How do I find the maximum integer present in dicts' values?
Example:
x1 = {0:2, 2:1, 3:(1, 2), 20:3}
should return 3
and
x2 = {0:2, 2:1, 3:(1, 5), 20:3}
should return 5
| [
"A one-liner:\nmax(max(v) if isinstance(v, collections.Iterable) else v for v in d.itervalues())\n\nNeeds at least Python 2.6 due to collections.Iterable ABC.\n",
"max(max(k,max(v) if isinstance(v,collections.Iterable) else v) for k,v in x1.items())\n\nThe other one-liner does not take account of the keys.\nThis ... | [
3,
1,
1,
0,
0,
0
] | [] | [] | [
"max",
"python"
] | stackoverflow_0003761124_max_python.txt |
Q:
How can I get all the attributes of a HTML tag?
How can I get all the attributes of a HTML tag?
listinp = soup('input')
for input in listinp:
# get all attr on this tag in dict
A:
Use attrs:
for tag in listinp:
print dict(tag.attrs)
A:
use pretiffy() in BeautifulSoup
import urllib2, BeautifulSoup
opene... | How can I get all the attributes of a HTML tag? | How can I get all the attributes of a HTML tag?
listinp = soup('input')
for input in listinp:
# get all attr on this tag in dict
| [
"Use attrs:\nfor tag in listinp:\n print dict(tag.attrs)\n\n",
"use pretiffy() in BeautifulSoup\nimport urllib2, BeautifulSoup\nopener = urllib2.build_opener()\nhost = \"http://google.com\"\nsite = opener.open(host)\nhtml = site.read()\nsoup = BeautifulSoup(html)\nprint soup.pretiffy()\n\n"
] | [
2,
0
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0003543197_beautifulsoup_python.txt |
Q:
Python, parse html form
how I can get input from html forms on other sites?
I want it to return a dictionary such as:
form = [('name' = 'somename', 'type' = 'text', 'value':''},{' name' = 'somename', 'type' = 'submit', 'value': ' submit ').
Sorry for my English.
A:
you probably wont be able to retrieve form d... | Python, parse html form | how I can get input from html forms on other sites?
I want it to return a dictionary such as:
form = [('name' = 'somename', 'type' = 'text', 'value':''},{' name' = 'somename', 'type' = 'submit', 'value': ' submit ').
Sorry for my English.
| [
"you probably wont be able to retrieve form data from other users on other sites. If you wish to use a script to send data to a form, mechanize is one tool that makes this quite easy.\n",
"Yeah mechanize is sweet !\nimport mechanize\n\n# Browser\nbr = mechanize.Browser()\nbr.set_handle_equiv(True)\nbr.set_handle_... | [
3,
2,
1
] | [] | [] | [
"forms",
"html",
"python"
] | stackoverflow_0003541098_forms_html_python.txt |
Q:
Why does python think this is a local variable?
I have a global variable I called Y_VAL which is initialized to a value of 2.
I then have a function, called f() (for brevity), which uses Y_VAL.
def f():
y = Y_VAL
Y_VAL += 2
However, when trying to run my code, python gives the error message:
UnboundLocal... | Why does python think this is a local variable? | I have a global variable I called Y_VAL which is initialized to a value of 2.
I then have a function, called f() (for brevity), which uses Y_VAL.
def f():
y = Y_VAL
Y_VAL += 2
However, when trying to run my code, python gives the error message:
UnboundLocalError: local variable 'Y_VAL' referenced before assig... | [
"You're missing the line global Y_VAL inside the function.\nWhen Y_VAL occurs on the right-hand-side of an assignment, it's no problem because the local scope is searched first, then the global scope is searched. However, on the left-hand-side, you can only assign to a global that way when you've explicitly declar... | [
15,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0003241930_python.txt |
Q:
Is there a way to run a python script that is inside a zip file from bash?
I know there is a way to import modules which are in a zip file with python. I created kind of custom python package library in a zip file.
I would like to put as well my "task" script in this package, those are using the library. Then, wi... | Is there a way to run a python script that is inside a zip file from bash? | I know there is a way to import modules which are in a zip file with python. I created kind of custom python package library in a zip file.
I would like to put as well my "task" script in this package, those are using the library. Then, with bash, I would like to call the desired script in the zip file without extract... | [
"I finally found a way to do this. If I create a zip file, I must create __main__.py at the root of the zip. Thus, it is possible to launch the script inside the main and call if from bash with the following command :\npython myArchive.zip\nThis command will run the __main__.py file! :)\nThen I can create .command ... | [
18,
3
] | [] | [] | [
"bash",
"macos",
"python",
"python_module",
"zip"
] | stackoverflow_0003760970_bash_macos_python_python_module_zip.txt |
Q:
Returning all characters before the first underscore
Using re in Python, I would like to return all of the characters in a string that precede the first appearance of an underscore. In addition, I would like the string that is being returned to be in all uppercase and without any non-alpanumeric characters.
For ex... | Returning all characters before the first underscore | Using re in Python, I would like to return all of the characters in a string that precede the first appearance of an underscore. In addition, I would like the string that is being returned to be in all uppercase and without any non-alpanumeric characters.
For example:
AG.av08_binloop_v6 = AGAV08
TL.av1_binloopv2 = TL... | [
"Even without re:\ntext.split('_', 1)[0].replace('.', '').upper()\n\n",
"Try this:\nre.sub(\"[^A-Z\\d]\", \"\", re.search(\"^[^_]*\", str).group(0).upper())\n\n",
"Since everyone is giving their favorite implementation, here's mine that doesn't use re:\n>>> for s in ('AG.av08_binloop_v6', 'TL.av1_binloopv2'):\n... | [
22,
7,
3,
2,
2,
1
] | [] | [] | [
"python",
"regex",
"string"
] | stackoverflow_0003762420_python_regex_string.txt |
Q:
how to create hyperlink in piechart
I want to do a pie chart in matplotlib.
This pie chart will be a representation of two variables: male and female.
That's easy to do :)
What I would like to do next, I'm not even sure if it's possible to do with matplotlib, I would like to make these two variables clickable so i... | how to create hyperlink in piechart | I want to do a pie chart in matplotlib.
This pie chart will be a representation of two variables: male and female.
That's easy to do :)
What I would like to do next, I'm not even sure if it's possible to do with matplotlib, I would like to make these two variables clickable so if I click on male, I would see another pa... | [
"While it's not really in a workably stable state yet, have a look at the html5 canvas backend for matplotlib. It looks interesting, anyway, and will probably be the best way to do this sort of thing (interactive webpage with a matplotlib plot) in the future.\nIn the meantime, as @Mark suggested, it's not too hard... | [
5,
1
] | [] | [] | [
"hyperlink",
"javascript",
"jquery",
"matplotlib",
"python"
] | stackoverflow_0003758658_hyperlink_javascript_jquery_matplotlib_python.txt |
Q:
Using reverse operators in Python
I have never handled reverse operators before. I just finished learning about them so wanted to try them out. But for some reason, it is not working. Here is the code:
>>> class Subtract(object):
def __init__(self, number):
self.number = number
def __rsub__(self, o... | Using reverse operators in Python | I have never handled reverse operators before. I just finished learning about them so wanted to try them out. But for some reason, it is not working. Here is the code:
>>> class Subtract(object):
def __init__(self, number):
self.number = number
def __rsub__(self, other):
return self.number - oth... | [
"__rsub__() will only be called if the operands are of different types; when they're of the same type it's assumed that if __sub__ isn't present they can't be subtracted.\nAlso note that your logic is reversed in any case; you're returning self - other instead of other - self\n",
"The point of these methods is to... | [
6,
5,
4,
3
] | [] | [] | [
"operators",
"python"
] | stackoverflow_0003763683_operators_python.txt |
Q:
Python cProfile: how to filter out specific calls from the profiling data?
I've started profiling a script which has many sleep(n) statements. All in all, I get over 99% of the run time spent sleeping. Nevertheless, it occasionally runs into performance problems during the time that it does real work but the relev... | Python cProfile: how to filter out specific calls from the profiling data? | I've started profiling a script which has many sleep(n) statements. All in all, I get over 99% of the run time spent sleeping. Nevertheless, it occasionally runs into performance problems during the time that it does real work but the relevant, interesting profiling data becomes very difficult to identify when e.g. usi... | [
"You need more than just excluding samples during sleep(). You need the remaining samples to tell you something useful. That would be stack sampling, on wall-clock time, summarizing percent at the line-of-code level. Zoom is a good tool for this kind of sampling, and I would hope it's not too hard to ignore samples... | [
2
] | [] | [] | [
"cprofile",
"kcachegrind",
"profiling",
"python"
] | stackoverflow_0003761671_cprofile_kcachegrind_profiling_python.txt |
Q:
How do you handle timezones for data processing?
curious how people have solved this problem...
I have a series of jobs that run overnight that roll up reports based on that day's data for customers. They're now asking for timezone support.
One of the reports is.. you had x number of orders last night, however la... | How do you handle timezones for data processing? | curious how people have solved this problem...
I have a series of jobs that run overnight that roll up reports based on that day's data for customers. They're now asking for timezone support.
One of the reports is.. you had x number of orders last night, however last night could be different depending on timezone. Wha... | [
"It is good practice to represent all the dates in the UTC time zone. This timezone has no confusing daylight savings time. Then the customer in the US/Pacific timezone can ask for a report on orders between 2010-09-20T00:00-700 to 2010-09-21T00:00-700 (using ISO 8601 format). The input layer of your program should... | [
3,
1,
0
] | [] | [] | [
"data_processing",
"java",
"python",
"timezone"
] | stackoverflow_0003761655_data_processing_java_python_timezone.txt |
Q:
How to add the binary of a int with the binary of a string
Basically i want to be able to get a 32bit int and attach its binary to the binary of a string.
E.g.
(IM going to use 8bit instead of 32bit)
i want
255 + hi
11111111 + 0110100001101001 = 111111110110100001101001
So the int holds its binary value,i dont car... | How to add the binary of a int with the binary of a string | Basically i want to be able to get a 32bit int and attach its binary to the binary of a string.
E.g.
(IM going to use 8bit instead of 32bit)
i want
255 + hi
11111111 + 0110100001101001 = 111111110110100001101001
So the int holds its binary value,i dont care how it comes out i just want it to be able to send the data ov... | [
"Something like \nstruct.pack(\"!i%ds\" % len(your_string), your_int, your_string)\n\nshould do pretty much what you want !\n",
"Is this what you're looking for? Don't know whether you're after a hexdigest or a digest, and I couldn't tell where the keys started and stopped, which is a shame as they are whitespace... | [
3,
2
] | [] | [] | [
"python",
"websocket"
] | stackoverflow_0003761871_python_websocket.txt |
Q:
Calling Tcl procedures with Function pointers as argument from Python
Is it possible to call Tcl procedures that have function pointers (or callback functions) from Python?
I am using Tkinter to call Tcl procedures from Python.
Python Snippet :
proc callbackFunc():
print "I am in callbackFunc"
cb = callbackFu... | Calling Tcl procedures with Function pointers as argument from Python | Is it possible to call Tcl procedures that have function pointers (or callback functions) from Python?
I am using Tkinter to call Tcl procedures from Python.
Python Snippet :
proc callbackFunc():
print "I am in callbackFunc"
cb = callbackFunc
Tkinter.Tk.call('tclproc::RetrieveInfo', cb)
Tcl Snippet :
proc tclproc... | [
"Yes, and your pseudocode is pretty close. You have to register your python code with the Tcl interpreter. This will create a tcl command that will call your python code. You then reference this new tcl command whenever you pass it to a Tcl procedure that expects a procedure name. It goes something like this:\nimpo... | [
7
] | [] | [] | [
"python",
"tcl",
"tkinter"
] | stackoverflow_0003763904_python_tcl_tkinter.txt |
Q:
Using pydbgr with Emacs
Has anyone used Pydbgr with Emacs and if so would they mind sharing their .emacs configuration plus any associated elisp sources required.
The installation instructions can be found at:
http://code.google.com/p/pydbgr/wiki/Tutorial#Installation
Pydbgr looks like a really useful extension ... | Using pydbgr with Emacs | Has anyone used Pydbgr with Emacs and if so would they mind sharing their .emacs configuration plus any associated elisp sources required.
The installation instructions can be found at:
http://code.google.com/p/pydbgr/wiki/Tutorial#Installation
Pydbgr looks like a really useful extension to the capabilities of pdb, e... | [
"see http://github.com/rocky/emacs-dbgr which supports a number of debuggers, pydbgr being one of them.\n"
] | [
1
] | [] | [] | [
"debugging",
"dot_emacs",
"elisp",
"emacs",
"python"
] | stackoverflow_0003764575_debugging_dot_emacs_elisp_emacs_python.txt |
Q:
upload docs and web pages using drag and drop interface using python desktop app
i have desktop interface in python which uses drag and drop and where users can login. right now if i drop a file it will be stored in local directory. now what i want is, i want to upload user dropeed file to remote web server. can a... | upload docs and web pages using drag and drop interface using python desktop app | i have desktop interface in python which uses drag and drop and where users can login. right now if i drop a file it will be stored in local directory. now what i want is, i want to upload user dropeed file to remote web server. can anybody help me in direction ? i have been exploring python's ftp library's and everyth... | [
"In order to avoid reinventing the wheel, I recommend using FTP. With that being said, you'll need, of course, to have an FTP server.\nBy using FTP, this entirely avoids the creation of a proprietary file transferring server and client system. That would entail massive amounts of coding of sockets – perhaps even th... | [
1
] | [] | [] | [
"desktop",
"desktop_application",
"python"
] | stackoverflow_0003763783_desktop_desktop_application_python.txt |
Q:
Adding Readline Functionality Without Recompiling Python
I recently upgraded to Ubuntu 10.04 LTS and refreshed my Python environment. I installed Python 2.7 from source. Unfortunately, I didn't notice that Setup.dist has the readline line commented out by default - by default, there is no readline support instal... | Adding Readline Functionality Without Recompiling Python | I recently upgraded to Ubuntu 10.04 LTS and refreshed my Python environment. I installed Python 2.7 from source. Unfortunately, I didn't notice that Setup.dist has the readline line commented out by default - by default, there is no readline support installed. I'm now using the Python interpreter as a REPL enough th... | [
"There's a standalone gnureadline package available, you can install it using setuptools\n$ easy_install readline\n\nYou might also consider using ipython instead.\n"
] | [
12
] | [] | [] | [
"python",
"readline"
] | stackoverflow_0003764730_python_readline.txt |
Q:
When __repr__() is called?
print OBJECT calls OBJECT.__str__(), then when OBJECT.__repr__() is called? I see that print OBJECT calls OBJECT.__repr__() when OBJECT.__str__() doesn't exist, but I expect that's not the only way to call __repr__().
A:
repr(obj)
calls
obj.__repr__
the purpose of __repr__ is that it... | When __repr__() is called? | print OBJECT calls OBJECT.__str__(), then when OBJECT.__repr__() is called? I see that print OBJECT calls OBJECT.__repr__() when OBJECT.__str__() doesn't exist, but I expect that's not the only way to call __repr__().
| [
"repr(obj)\n\ncalls\nobj.__repr__\n\nthe purpose of __repr__ is that it provides a 'formal' representation of the object that is supposed to be a expression that can be evaled to create the object. that is,\nobj == eval(repr(obj))\n\nshould, but does not always in practice, yield True\nI was asked in the comments f... | [
27,
10,
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0003764360_python.txt |
Q:
Designing my domain model around one 3rd-party library
I'm working on a poker analysis tool with the following use case:
User create Strategy class with one method: input GameState, output PokerAction
User runs Analysis script, which launches a PokerGame between various Strategy subclasses (i.e. various strategie... | Designing my domain model around one 3rd-party library | I'm working on a poker analysis tool with the following use case:
User create Strategy class with one method: input GameState, output PokerAction
User runs Analysis script, which launches a PokerGame between various Strategy subclasses (i.e. various strategies)
PokerGame generates random deck
PokerGame sends GameState... | [
"If I really felt my domain model better suited me going forward, I would try to create an abstraction layer to map between the 3rd party library and my own model. This would allow me to take advantage of the library now while providing me with the flexibility to replace it in the future with another 3rd party lib... | [
2,
1
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0003764851_oop_python.txt |
Q:
Python: What does the use of [] mean here?
What is the difference in these two statements in python?
var = foo.bar
and
var = [foo.bar]
I think it is making var into a list containing foo.bar but I am unsure. Also if this is the behavior and foo.bar is already a list what do you get in each case?
For example: if... | Python: What does the use of [] mean here? | What is the difference in these two statements in python?
var = foo.bar
and
var = [foo.bar]
I think it is making var into a list containing foo.bar but I am unsure. Also if this is the behavior and foo.bar is already a list what do you get in each case?
For example: if foo.bar = [1, 2] would I get this?
var = foo.ba... | [
"[] is an empty list. \n[foo.bar] is creating a new list ([]) with foo.bar as the first item in the list, which can then be referenced by its index:\nvar = [foo.bar]\nvar[0] == foo.bar # returns True \n\nSo your guess that your assignment of foo.bar = [1,2] is exactly right.\nIf you haven't already, I recommend pla... | [
14,
3,
1,
0
] | [] | [] | [
"brackets",
"list",
"python",
"syntax",
"variable_assignment"
] | stackoverflow_0003764858_brackets_list_python_syntax_variable_assignment.txt |
Q:
python 2.6.x theading / signals /atexit fail on some versions?
I've seen a lot of questions related to this... but my code works on python 2.6.2 and fails to work on python 2.6.5. Am I wrong in thinking that the whole atexit "functions registered via this module are not called when the program is killed by a signa... | python 2.6.x theading / signals /atexit fail on some versions? | I've seen a lot of questions related to this... but my code works on python 2.6.2 and fails to work on python 2.6.5. Am I wrong in thinking that the whole atexit "functions registered via this module are not called when the program is killed by a signal" thing shouldn't count here because I'm catching the signal and th... | [
"The root difference here is actually unrelated to both signals and atexit, but rather a change in the behavior of sys.exit.\nBefore around 2.6.5, sys.exit (more accurately, SystemExit being caught at the top level) would cause the interpreter to exit; if threads were still running, they'd be terminated, just as wi... | [
8,
3,
0
] | [] | [] | [
"atexit",
"multithreading",
"python",
"signals"
] | stackoverflow_0003713360_atexit_multithreading_python_signals.txt |
Q:
Is there a way to tell if I'm using recursion in Python?
I'm writing a function to traverse the user's file system and create a tree representing that directory (the tree is really a TreeView widget in Tkinter, but that's functionally a tree).
The best way I can think of doing this is recursion. However, one of my... | Is there a way to tell if I'm using recursion in Python? | I'm writing a function to traverse the user's file system and create a tree representing that directory (the tree is really a TreeView widget in Tkinter, but that's functionally a tree).
The best way I can think of doing this is recursion. However, one of my cases in the function requires me to know if it is the "origi... | [
"Pretty much the same as in every other language - in your case, you pass a reference to the parent and check if it is None. If so, you create a proper parent node.\n",
"\none of my cases in the function requires me to know if it is the \"original\" function call, in which case the files have no parent node\n\nTh... | [
7,
4,
1,
1,
1
] | [] | [] | [
"functional_programming",
"python",
"recursion",
"traversal",
"tree"
] | stackoverflow_0003764879_functional_programming_python_recursion_traversal_tree.txt |
Q:
How to use subqueries in SQLAlchemy to produce a moving average?
My problem is that I want to retrieve both a list of measurements along with a moving average of those measurements. I can do that with this SQL statement (postgresql interval syntax):
SELECT time, value,
(
SELECT AVG(t2.va... | How to use subqueries in SQLAlchemy to produce a moving average? | My problem is that I want to retrieve both a list of measurements along with a moving average of those measurements. I can do that with this SQL statement (postgresql interval syntax):
SELECT time, value,
(
SELECT AVG(t2.value)
FROM measurements t2
WHERE t2.time BETWEEN t1.time ... | [
"Right, apparently what I needed was the use of a so-called scalar select. With the use of those I get this python code, which actually works as I want it to (generates the equivalent SQL to that of the first in my question which was my goal):\nmoving_average_days = # configurable value, defaulting to 5\nndays = # ... | [
5
] | [] | [] | [
"postgresql",
"python",
"sqlalchemy",
"subquery"
] | stackoverflow_0003764358_postgresql_python_sqlalchemy_subquery.txt |
Q:
Python Array with String Indices
Is it possible to use strings as indices in an array in python?
For example:
myArray = []
myArray["john"] = "johns value"
myArray["jeff"] = "jeffs value"
print myArray["john"]
A:
What you want is called an associative array. In python these are called dictionaries.
Dictionaries ... | Python Array with String Indices | Is it possible to use strings as indices in an array in python?
For example:
myArray = []
myArray["john"] = "johns value"
myArray["jeff"] = "jeffs value"
print myArray["john"]
| [
"What you want is called an associative array. In python these are called dictionaries.\n\nDictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable ty... | [
176,
5
] | [] | [] | [
"arrays",
"dictionary",
"list",
"python"
] | stackoverflow_0003765533_arrays_dictionary_list_python.txt |
Q:
Running python on a Windows machine vs Linux
I am interested in learning python but my Linux skills suck. I would like to develop a medium to large scale web application using python and django but afraid the software may not work well on a windows box. Is there a performance difference in running python on Linux ... | Running python on a Windows machine vs Linux | I am interested in learning python but my Linux skills suck. I would like to develop a medium to large scale web application using python and django but afraid the software may not work well on a windows box. Is there a performance difference in running python on Linux vs Windows? Is there anything that I should watch ... | [
"Don't tell anybody this, but I've run python/django on windows. It works all right and the performance hit isn't any worse than you would expect from windows. I used MySQL and it installed without a problem. I had to grope around to find out how to manage it (no good ol' sudo /etc/init.d/mysql restart but i eventu... | [
16,
14,
9,
1,
1,
1
] | [] | [] | [
"python",
"windows"
] | stackoverflow_0003765178_python_windows.txt |
Q:
Use of cycle in django
I have a webpage where I am looping,and using cycle inside the loop.
{% for o in something %}
{% for c in o %}
<div class="{% cycle 'white' 'black'%}"></div>
{% endfor %}
Now, this means everytime inside the loop, first div tag gets white.But,what I want is to alternate between white and b... | Use of cycle in django | I have a webpage where I am looping,and using cycle inside the loop.
{% for o in something %}
{% for c in o %}
<div class="{% cycle 'white' 'black'%}"></div>
{% endfor %}
Now, this means everytime inside the loop, first div tag gets white.But,what I want is to alternate between white and black i.e. start with white, ... | [
"There is an accept bug open about this issue. You may want to try the proposed change to see if it works for you.\nIf you do not want to try it, or it does not work, give this a shot:\n{% cycle 'white' 'black' as divcolors %}\n{% for o in something %}\n {% for c in o %}\n <div class=\"{% cycle divcolors ... | [
4,
0
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0000861855_django_django_templates_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.