content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
python - faster downloading of ~500 webpages (loop)
For starters I'm new to python so my code below may not be the cleanest. For a program I need to download about 500 webpages. The url's are stored in an array which is populated by a previous function. The downloading part goes something like this:
def downloadpa... | python - faster downloading of ~500 webpages (loop) | For starters I'm new to python so my code below may not be the cleanest. For a program I need to download about 500 webpages. The url's are stored in an array which is populated by a previous function. The downloading part goes something like this:
def downloadpages(num):
import urllib
for i in range(0,numPlan... | [
"But you're not downloading a single file, here. You're downloading 500 separate pages, each connection involves overhead (for the initial connection), plus whatever else the server is doing (is it serving other people?).\nEither way, downloading 500 x 20kb is not the same as downloading a single file of that size... | [
4,
3,
2,
0
] | [] | [] | [
"download",
"python",
"urllib"
] | stackoverflow_0006909741_download_python_urllib.txt |
Q:
Use user provided python code during runtime
I'm developing a system that operates on (arbitrary) data from databases. The data may need some preprocessing before the system can work with it. To allow the user the specify possibly complex rules I though of giving the user the possibility to input Python code which... | Use user provided python code during runtime | I'm developing a system that operates on (arbitrary) data from databases. The data may need some preprocessing before the system can work with it. To allow the user the specify possibly complex rules I though of giving the user the possibility to input Python code which is used to do this task. The system is pure Pytho... | [
"Python provides an exec() statement which should do what you want. You will want to pass in the variables that you want available as the second and/or third arguments to the function (globals and locals respectively) as those control the environment that the exec is run in.\nFor example:\nenv = {'somevar': 'someva... | [
4,
2,
1,
0,
0
] | [
"well, you're describing compile()\nBut... I think I'd still implement this using regular python source files. Add a special location to the path, say '~/.myapp/plugins', and just __import__ everything there. Probably you'll want to provide some convenient base classes that expose the interface you're trying to o... | [
-1
] | [
"eval",
"exec",
"python"
] | stackoverflow_0006916753_eval_exec_python.txt |
Q:
django simplejson throwing keys must be a string error
the error sounds very straight forward but am unable to fix it. I tried changing in my dictionary but am not going anywhere and I thought maybe someone in here can help me point out what I need to do to solve it. Below is my code
blog_calendar = BlogI18n.obje... | django simplejson throwing keys must be a string error | the error sounds very straight forward but am unable to fix it. I tried changing in my dictionary but am not going anywhere and I thought maybe someone in here can help me point out what I need to do to solve it. Below is my code
blog_calendar = BlogI18n.objects.filter(language=request.LANGUAGE_CODE,
... | [
"You have to convert all your keys to strings.\nIn this line:\ncalendar_response['events'].append(dict((i.blog.published_at.date(), (i.blog.slug, i.title)) for i in blog_calendar))\n\nThe culprit is the i.blog.published_at.date() expression. Substitute it with something which returns a string, as for example:\nstr(... | [
3,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006916849_django_python.txt |
Q:
Django - Accessing object fields and names from class-based view
I'm trying to write a class-based view for Django which will utilise the same template each time, regardless of model. The intention is that I can then add a urls.py entry for each model, and not have to bother about a view or a template.
This will b... | Django - Accessing object fields and names from class-based view | I'm trying to write a class-based view for Django which will utilise the same template each time, regardless of model. The intention is that I can then add a urls.py entry for each model, and not have to bother about a view or a template.
This will be used to display a form, and as the form field names are dependant on... | [
"If you're using django 1.3, class based views are included... Just use them and set the 'template_name' attribute to be your \"common\" name. \nhttps://docs.djangoproject.com/en/1.3/topics/class-based-views/\n",
"I think you're going about this the wrong way. Django already knows how to create a form from a mode... | [
0,
0
] | [] | [] | [
"django",
"model",
"python"
] | stackoverflow_0006915469_django_model_python.txt |
Q:
python RSA implemention with PKCS1
I got the following code in javascript for RSA implementionhttp://www-cs-students.stanford.edu/~tjw/jsbn/:
// Return the PKCS#1 RSA encryption of "text" as an even-length hex string
function RSAEncrypt(text) {
var m = pkcs1pad2(text,(this.n.bitLength()+7)>>3);
if(m == nu... | python RSA implemention with PKCS1 | I got the following code in javascript for RSA implementionhttp://www-cs-students.stanford.edu/~tjw/jsbn/:
// Return the PKCS#1 RSA encryption of "text" as an even-length hex string
function RSAEncrypt(text) {
var m = pkcs1pad2(text,(this.n.bitLength()+7)>>3);
if(m == null) return null;
var c = this.doPubl... | [
"I know it's a bit late, but in a few days I'll release a new version of my Python-RSA package. That version will include PKCS#1 v1.5 padding, so it should be compatible with your JavaScript code ;-)\n"
] | [
0
] | [] | [] | [
"jsbn",
"python",
"rsa"
] | stackoverflow_0002565096_jsbn_python_rsa.txt |
Q:
In South, can I copy the value of an old column to a new one?
One of my Django models is a subclass and I want to change its superclass to one that is very similar to the original one. In particular, the new superclass describes the same object and has the same primary key. How can I make South create the new OneT... | In South, can I copy the value of an old column to a new one? | One of my Django models is a subclass and I want to change its superclass to one that is very similar to the original one. In particular, the new superclass describes the same object and has the same primary key. How can I make South create the new OneToOne field and copy the values from the old one to the new one?
| [
"In south, there are two kinds of migrations: schema migrations and data migrations. \nAfter you've created the schemamigration, create a corresponding data migration:\n./manage.py datamigration <app> <migration_name>\nDo not run the migration (yet). Instead, open up the migration file you just created.\nYou'll f... | [
11
] | [] | [] | [
"django",
"django_models",
"django_south",
"python"
] | stackoverflow_0006917670_django_django_models_django_south_python.txt |
Q:
Sort by hierarchy algorithm
How can I make this sorting algorithm?
modules = {
2:[4], # element 2 must be after element 4
1:[],
3:[2,4], # element 3 must be after 2 and 3 elements
4:[1] # element 4 must be after element 1
}
Result [1, 4, 2, 3] by conditions.
A:
That's called a topological s... | Sort by hierarchy algorithm | How can I make this sorting algorithm?
modules = {
2:[4], # element 2 must be after element 4
1:[],
3:[2,4], # element 3 must be after 2 and 3 elements
4:[1] # element 4 must be after element 1
}
Result [1, 4, 2, 3] by conditions.
| [
"That's called a topological sort. Makefiles do it, and there's a standard UNIX utility called tsort that will do it.\n"
] | [
4
] | [] | [] | [
"python",
"sorting"
] | stackoverflow_0006917947_python_sorting.txt |
Q:
wildcard subdomains in a django project
has anyone ever used wildcard subdomains in their application? I need to come up with a way to 'localise' my application. When i say localise i mean anyone who goes to ny.foo.com/items/new/ will be sent to a view which looks through a database and search for new items in ny.... | wildcard subdomains in a django project | has anyone ever used wildcard subdomains in their application? I need to come up with a way to 'localise' my application. When i say localise i mean anyone who goes to ny.foo.com/items/new/ will be sent to a view which looks through a database and search for new items in ny. Obviously we could replace NY with any state... | [
"I would do it using a middleware, eg.:\nclass StateCodeMiddleware(object):\n\n def process_request(self, request):\n bits = request.META['HTTP_HOST'].split('.')\n if len(bits) == 3 and len(bits[0]) == 2:\n request.state_code = bits[0]\n else:\n request.state_code = None... | [
5
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006917931_django_python.txt |
Q:
In Dulwich, how do I commit to a branch instead of to HEAD?
Apparently repo.do_commit(message='test commit', committer='Name ') only commits to refs/heads/master.
Is there a way to set the current commit ref to another one than refs/heads/master?
Or is the only way to commit to a branch by creating a Commit object... | In Dulwich, how do I commit to a branch instead of to HEAD? | Apparently repo.do_commit(message='test commit', committer='Name ') only commits to refs/heads/master.
Is there a way to set the current commit ref to another one than refs/heads/master?
Or is the only way to commit to a branch by creating a Commit object (as shown in the tutorial in the documentation) and setting it's... | [
"Creating a Commit object manually and then setting the tag is indeed the only way to commit to a non-HEAD branch in the last release.\ndo_commit() in trunk supports a \"ref\" argument that you can use to commit to other branches.\nhttp://www.samba.org/~jelmer/dulwich/apidocs/dulwich.repo.BaseRepo.html#do_commit\n"... | [
1
] | [] | [] | [
"dulwich",
"git",
"python"
] | stackoverflow_0006904734_dulwich_git_python.txt |
Q:
Modify Windows unicode shortcuts using Python
Following this question, I've settled on the following Python code to modify Windows shortcuts. It works for English based shortcuts but it doesn't for unicode based shortcuts.
How could this (or any other) snippet be modified to support unicode?
import re, os, pythonc... | Modify Windows unicode shortcuts using Python | Following this question, I've settled on the following Python code to modify Windows shortcuts. It works for English based shortcuts but it doesn't for unicode based shortcuts.
How could this (or any other) snippet be modified to support unicode?
import re, os, pythoncom
from win32com.shell import shell, shellcon
shor... | [
"Perhaps looking here may help: Python Unicode HOWTO\nI'm guessing you'd need to be sure that each of those strings was properly encoded as Unicode and any changes need to preserve that encoding. That article should provide all the information you'll need.\n"
] | [
0
] | [] | [] | [
"python",
"shortcut",
"unicode",
"windows"
] | stackoverflow_0006916069_python_shortcut_unicode_windows.txt |
Q:
What's the main difference between simplejson and the module in the standard library of python?
Possible Duplicate:
json and simplejson module differences in Python
On this page about json, I read about json and the python modules available for json. The mention those four libraries:
Json in the Python Standard... | What's the main difference between simplejson and the module in the standard library of python? |
Possible Duplicate:
json and simplejson module differences in Python
On this page about json, I read about json and the python modules available for json. The mention those four libraries:
Json in the Python Standard Library.
simplejson.
pyson.
Yajl-Py
Which one is recommended? What is the main difference between ... | [
"json in the standard library is simplejson, only bit older version, maintained more slowly. As for which to use, stdlib json unless you have a good reason not to.\n"
] | [
3
] | [] | [] | [
"json",
"python",
"simplejson"
] | stackoverflow_0006918192_json_python_simplejson.txt |
Q:
Microsecond part lost when converting a date string to a datetime object in python
I have the following date string:
dtstr = '2010-12-19 03:44:34.778000'
I wanted to convert it to a datetime object, so i proceeded as follows:
import time
from datetime import datetime
dtstr = '2010-12-19 03:44:34.778000'
format =... | Microsecond part lost when converting a date string to a datetime object in python | I have the following date string:
dtstr = '2010-12-19 03:44:34.778000'
I wanted to convert it to a datetime object, so i proceeded as follows:
import time
from datetime import datetime
dtstr = '2010-12-19 03:44:34.778000'
format = "%Y-%m-%d %H:%M:%S.%f"
datetime.fromtimestamp(time.mktime(time.strptime(dtstr,format)))... | [
"from datetime import datetime\n\ndtstr = '2010-12-19 03:44:34.778000'\nformat = \"%Y-%m-%d %H:%M:%S.%f\"\na = datetime.strptime(dtstr,format)\nprint a.microsecond\n\ntime handles seconds since the Unix epoch, so using time loses the microseconds. Use datetime.strptime directly.\n",
"The time.struct_time object r... | [
7,
2
] | [] | [] | [
"datetime",
"python",
"time"
] | stackoverflow_0006918443_datetime_python_time.txt |
Q:
Finding an Insertion in a String
What's the best way of checking if StringA = StringB with an another StringC inserted at some arbitrary point?
For example, given abcdef and abcXYZdef, I want to find that abcXYZdef is abcdef with XYZ inserted at position 4.
On the other hand, given abcdef and abRSTcdXYZef, I wan... | Finding an Insertion in a String | What's the best way of checking if StringA = StringB with an another StringC inserted at some arbitrary point?
For example, given abcdef and abcXYZdef, I want to find that abcXYZdef is abcdef with XYZ inserted at position 4.
On the other hand, given abcdef and abRSTcdXYZef, I want to find that the first string cannot... | [
"A very underappreciated gem in the standard lib is difflib...\n>>> import difflib\n>>> s = difflib.SequenceMatcher(None, \"GHSKWITNIFSI\", \"GHSKWAGDITNIFSI\")\n>>> s.get_matching_blocks()[:-1]\n[(0, 0, 5), (5, 8, 7)]\n>>> s = difflib.SequenceMatcher(None, \"GHSKWITNIFSI\", \"GHSKWITNIFSI\")\n>>> s.get_matching_bl... | [
6,
2,
0,
0,
0
] | [
"strA='foor'\nstrB='foobar'\nstrC='ba'\n\nif strB.replace(strC,'') == strA:\n print strC,' at index ',len(strB.split(strC)[0])\n\nPossibly? Testing right now...\n"
] | [
-2
] | [
"algorithm",
"python",
"regex",
"string"
] | stackoverflow_0006918414_algorithm_python_regex_string.txt |
Q:
Writing to file with sys.stdout in python
ascii85.encode(file('/work/file1'), sys.write('/work/file2')
I am trying to write to a file with this code using sys.stdout, but it is not writing.
How do I fix the code to write to a file?
A:
Try
ascii85.encode(file('/work/file1'), open('/work/file2', 'w'))
I don't ... | Writing to file with sys.stdout in python | ascii85.encode(file('/work/file1'), sys.write('/work/file2')
I am trying to write to a file with this code using sys.stdout, but it is not writing.
How do I fix the code to write to a file?
| [
"Try\nascii85.encode(file('/work/file1'), open('/work/file2', 'w'))\n\nI don't know what exactly you're trying to do but that's how you open a file for writing in Python.\nIf this isn't what you want please clarify your question.\n"
] | [
2
] | [] | [] | [
"python",
"sys"
] | stackoverflow_0006918821_python_sys.txt |
Q:
Python sqlite3 create table syntax error
Whenever I try to create a table using python and sqlite3, it gives me the following error:
Traceback (most recent call last)
File "directory.py", line 14, in <module>
'Children' TEXT, 'Other' TEXT, 'Masul' TEXT);''')
sqlite3.OperationalError: near ")": syntax error
The wa... | Python sqlite3 create table syntax error | Whenever I try to create a table using python and sqlite3, it gives me the following error:
Traceback (most recent call last)
File "directory.py", line 14, in <module>
'Children' TEXT, 'Other' TEXT, 'Masul' TEXT);''')
sqlite3.OperationalError: near ")": syntax error
The way I'm trying to create the table is:
conn.exec... | [
"Often when you get this kind of error it is because you are using keywords as column (or table) names.\nI see that you have a column called primary.\nYou will want to put backticks around it or rename it because it is a keyword in SQLite; e.g.:\n...\n`Primary` TEXT,\n...\n\n",
"You have a trailing \",\" before t... | [
7,
1,
1
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0006918719_python_sqlite.txt |
Q:
Make CherryPy exit immediately upon receiving a keyboard interrupt?
Is there an easy way of making CherryPy perform an os._exit(0) once it gets a ^C interrupt?
It would normally wait for all the threads to terminate which is not useful for debugging as I expect it to shut down immediately.
A:
See https://cherry... | Make CherryPy exit immediately upon receiving a keyboard interrupt? | Is there an easy way of making CherryPy perform an os._exit(0) once it gets a ^C interrupt?
It would normally wait for all the threads to terminate which is not useful for debugging as I expect it to shut down immediately.
| [
"See https://cherrypy.readthedocs.org/en/3.3.0/refman/process/plugins/signalhandler.html.\nhandlers = {'SIGTERM': self.bus.exit,\n 'SIGHUP': self.handle_SIGHUP,\n 'SIGUSR1': self.bus.graceful,\n }\n\nare the default handlers; SIGINT from Ctrl-C isn't there (so I don't know if it's going the same... | [
5
] | [] | [] | [
"cherrypy",
"multithreading",
"python"
] | stackoverflow_0006918990_cherrypy_multithreading_python.txt |
Q:
How to convert a list of IP addresses to a list of address ranges?
There are multiple ways to convert a list of IP address to a list of CIDR (netaddr, ipaddr-py). Is there a way to convert a list of IP address ranges to a merged IP range?
The following examples return a list of tuples of the following format: [(... | How to convert a list of IP addresses to a list of address ranges? | There are multiple ways to convert a list of IP address to a list of CIDR (netaddr, ipaddr-py). Is there a way to convert a list of IP address ranges to a merged IP range?
The following examples return a list of tuples of the following format: [(start, end)].
Example 1:
>>> list_of_ips = ['192.168.0.1', '192.168.0.2'... | [
"IMHO a good point to start is to make converters from dotted string into int and back. Integer representation is more convenient to compare.\nI thought about using reduce but it seems too difficult for me. So I've just implemented it using traditional loop and without recursion.\ndef int2dot( intip ):\n return ... | [
3
] | [] | [] | [
"ip_address",
"python"
] | stackoverflow_0006917904_ip_address_python.txt |
Q:
Calling Python functions passed by weakref
Using Boost.Python, is there a way to call a Python function that's been passed through a weakref? The following code doesn't work:
import weakref
def foo():
print 'it works'
def func():
return weakref.ref(foo)
The following is the C++:
object module = import("... | Calling Python functions passed by weakref | Using Boost.Python, is there a way to call a Python function that's been passed through a weakref? The following code doesn't work:
import weakref
def foo():
print 'it works'
def func():
return weakref.ref(foo)
The following is the C++:
object module = import("test");
object func(module.attr("func"));
object... | [
"From weakref documentation:\n\nReturn a weak reference to object. The original object can be retrieved by calling the reference object if the referent is still alive...\n\nSo, given your snippet:\nimport weakref\n\ndef foo():\n print \"It Works!\"\n\ndef func():\n return weakref.ref(foo)\n\nref = func() # fu... | [
6,
4
] | [] | [] | [
"boost",
"c++",
"python"
] | stackoverflow_0006919134_boost_c++_python.txt |
Q:
How do reimplement this Python XML-parsing function in Haskell?
I recently wrote the following Python function which will take a Google Picasa contacts.xml file and output a dictionary with ID and Name.
def read_contacts_file(fn):
import xml.etree.ElementTree
x = xml.etree.ElementTree.ElementTree(file=fn)
... | How do reimplement this Python XML-parsing function in Haskell? | I recently wrote the following Python function which will take a Google Picasa contacts.xml file and output a dictionary with ID and Name.
def read_contacts_file(fn):
import xml.etree.ElementTree
x = xml.etree.ElementTree.ElementTree(file=fn)
q = [(u.attrib["id"], u.attrib["name"]) for u in x.iter("contact"... | [
"Here's a minimal example doing the same thing with tagsoup:\nimport Text.HTML.TagSoup\n\nassocLookup k dict = [v | (k', v) <- dict, k == k']\nreadContactsFile fn = fmap parse (readFile fn)\n\nparse contents = do\n TagOpen \"contact\" attrs <- parseTags contents\n id <- assocLookup \"id\" attrs\n name <- a... | [
7,
6,
1
] | [] | [] | [
"haskell",
"python",
"xml"
] | stackoverflow_0006918069_haskell_python_xml.txt |
Q:
checking and fixing values appended to a node with lxml.objectify in python
I'm trying to modify PyKML, which uses lxml.objectify. With a track node append, this gets turned into a string with the default str() behavior. I'd like to catch appends of lists or tuples and convert them to proper place separated line... | checking and fixing values appended to a node with lxml.objectify in python | I'm trying to modify PyKML, which uses lxml.objectify. With a track node append, this gets turned into a string with the default str() behavior. I'd like to catch appends of lists or tuples and convert them to proper place separated lines rather than '(xx.xxxx, yy.yyyy)'
from pykml.factory import GX_ElementMaker as ... | [
"Create a clean ElementMaker class with the namespace info. Then create a subclass with the node name as a method. In that method, handle all the odd cases. Then craft the string that would go in that node names place and return an instance of the clean ElementMaker class with that node name.\nhttp://code.google... | [
0
] | [] | [] | [
"kml",
"lxml",
"objectify",
"pykml",
"python"
] | stackoverflow_0006785264_kml_lxml_objectify_pykml_python.txt |
Q:
AttributeError: 'NoneType' object has no attribute 'strip' with Python WebCrawler
I'm writing a python program to crawl twitter using a combination of urllib2, the python twitter wrapper for the api, and BeautifulSoup. However, when I run my program, I get an error of the following type:
ray_krueger
RafaelNadal
T... | AttributeError: 'NoneType' object has no attribute 'strip' with Python WebCrawler | I'm writing a python program to crawl twitter using a combination of urllib2, the python twitter wrapper for the api, and BeautifulSoup. However, when I run my program, I get an error of the following type:
ray_krueger
RafaelNadal
Traceback (most recent call last):
File "C:\Users\Public\Documents\Columbia Job\Python... | [
"\nAttributeError: 'NoneType' object has no attribute 'strip'\n\nIt means exactly what it says: url.strip() requires first figuring out what url.strip is, i.e. looking up the strip attribute of url. This failed because url is a 'NoneType' object, i.e. an object whose type is NoneType, i.e. the special object None.\... | [
1,
0,
0,
0
] | [] | [] | [
"html",
"python",
"twitter",
"web_crawler"
] | stackoverflow_0006919098_html_python_twitter_web_crawler.txt |
Q:
Display files on HTML page as it is
I am using webpy framework for my project. I want to pass a file from my webpy program and display it on html page as it is(files may be any text files/program files). I passed a text file using following function from my webpy program.
class display_files:
def GET(self):
... | Display files on HTML page as it is | I am using webpy framework for my project. I want to pass a file from my webpy program and display it on html page as it is(files may be any text files/program files). I passed a text file using following function from my webpy program.
class display_files:
def GET(self):
wp=web.input()
file_name=wp... | [
"looks like you may need to globally replace any < or > with < or > respectively:\nhttp://jsfiddle.net/BaULp/\n",
"HTML treats amount of whitespace characters as a single whitespace. If the file that you are displaying contains this text:\nline one\n line two with indent\n\nthe rendered file_display.html w... | [
0,
0
] | [] | [] | [
"html",
"python",
"web.py"
] | stackoverflow_0006913994_html_python_web.py.txt |
Q:
Run function when task queue is empty on appengine
I have a cron job everyday to make a call to an API and fetch some data. For each row of the data I kick off a task queue to process the data (which involves looking up data via further APIs). Once all this has finished my data doesn't change for the next 24 hours... | Run function when task queue is empty on appengine | I have a cron job everyday to make a call to an API and fetch some data. For each row of the data I kick off a task queue to process the data (which involves looking up data via further APIs). Once all this has finished my data doesn't change for the next 24 hours so I memcache it.
Is there a way of knowing when all th... | [
"There's not currently any way to determine when your tasks have finished executing. Your best option would be to insert marker records in the datastore, and have each task delete its record when it's done. Each task can then check if it's the last task, and perform your cleanup / caching if it is.\n",
"i found t... | [
6,
2
] | [] | [] | [
"cron",
"google_app_engine",
"python",
"task_queue"
] | stackoverflow_0005546487_cron_google_app_engine_python_task_queue.txt |
Q:
Unicode problem with text in images in Python
I need to create in python an image with unicode chars like △ ▽ ◆ ◇ ◎ ◯ but I don't find the way.. I wonder how firefox or other programs print them well with the same font I use even.. this is my code
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
import Image, Imag... | Unicode problem with text in images in Python | I need to create in python an image with unicode chars like △ ▽ ◆ ◇ ◎ ◯ but I don't find the way.. I wonder how firefox or other programs print them well with the same font I use even.. this is my code
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
import Image, ImageDraw, ImageFont
chars = u'△ 0x25b3, ▽ 0x25bd, ◅ 0... | [
"You need to pick a font which contains those glyph's. Most likely the font face you are using, cour.ttf, does not contain the glyphs you are trying to write. You could try cyberbit.ttf.\n"
] | [
2
] | [] | [] | [
"firefox",
"image",
"python",
"unicode"
] | stackoverflow_0006920599_firefox_image_python_unicode.txt |
Q:
Why is there a date class in python
Doesn't datetime cover all that date can do? I haven't read all the documentation, but so far I always find myself using datetime.
Even in Django - datetime model fields are always more useful (at least for me). You don't have to use the hours if you don't want to, but if you d... | Why is there a date class in python | Doesn't datetime cover all that date can do? I haven't read all the documentation, but so far I always find myself using datetime.
Even in Django - datetime model fields are always more useful (at least for me). You don't have to use the hours if you don't want to, but if you decide that you do, you can.
Javascript s... | [
"When you only need the date component and can do without the time.\ndatetime is a composition of the date and time types, so, yes, datetime does all what date does (and does also all what time does).\nChoosing one instead of the other is thus pretty simple: if you want to record only a date, use date; if you need ... | [
4,
4
] | [
"datetime is a the same as the types date and time. The only thing better is that it takes less space than date does.\n"
] | [
-1
] | [
"date",
"datetime",
"python"
] | stackoverflow_0006920403_date_datetime_python.txt |
Q:
Help me make my Python 2 code work in Python 3
import math,sys,time;i=0
while 1: sys.stdout.write("\r"+':(__)'[:3+int(round(math.sin(i)))]+'n'+':(__)'[3+int(round(math.sin(i))):]);sys.stdout.flush();time.sleep(.15);i+=0.5*math.pi
I wrote that simple program in Python 2 a long time ago and it worked fine but ... | Help me make my Python 2 code work in Python 3 | import math,sys,time;i=0
while 1: sys.stdout.write("\r"+':(__)'[:3+int(round(math.sin(i)))]+'n'+':(__)'[3+int(round(math.sin(i))):]);sys.stdout.flush();time.sleep(.15);i+=0.5*math.pi
I wrote that simple program in Python 2 a long time ago and it worked fine but it has syntax errors in Python 3. I would greatly ap... | [
"I pasted your code in a file, saved it, then opened it in a Python shell:\nIn [10]: f=open('test2.py')\n\nIn [11]: content=f.read()\n\nIn [12]: content\nOut[12]: '#!/usr/bin/env python\\n# coding: utf-8\\n\\nimport math,sys,time;i=0\\nwhile 1: sys.stdout.write(\"\\\\r\"+\\':(_\\xe2\\x80\\x8b_)\\'[:3+int(round(math... | [
4,
1,
1,
0
] | [] | [] | [
"python",
"python_2.x",
"python_3.x"
] | stackoverflow_0006920547_python_python_2.x_python_3.x.txt |
Q:
Python for loop skipping every other value
I have run into an odd problem in my django application where a for loop is skipping every other item. I have take a returned queryset and list()ed to iterate over. The point of doing this is to remove items that are inside another list that is getting passed to the view ... | Python for loop skipping every other value | I have run into an odd problem in my django application where a for loop is skipping every other item. I have take a returned queryset and list()ed to iterate over. The point of doing this is to remove items that are inside another list that is getting passed to the view via a POST variable. This view is an ajax reques... | [
"temp and items refer to the same object, so when you do items.remove() you're also modifying temp. You probably want to do temp = items[:] to copy the values of the items list.\n",
"You should not be modifying a data structure while iterating over it.\nAnyways, this is a more concise and performant code to do y... | [
6,
2
] | [] | [] | [
"django",
"for_loop",
"python"
] | stackoverflow_0006920668_django_for_loop_python.txt |
Q:
QtSql convert MySql queries to SQLite
I am trying to convert some MySql queries to SQLite using Python PyQt, but I cannot seem to get it working. When I run the following code, nothing prints out, no errors or results. What is wrong with the code?
db = QSqlDatabase.addDatabase("QSQLITE")
db.setDatabaseName("TEST")... | QtSql convert MySql queries to SQLite | I am trying to convert some MySql queries to SQLite using Python PyQt, but I cannot seem to get it working. When I run the following code, nothing prints out, no errors or results. What is wrong with the code?
db = QSqlDatabase.addDatabase("QSQLITE")
db.setDatabaseName("TEST")
if not db.open():
QMessageBox.warning(... | [
"I don't know PyQT, but when you're using the native sqlite bindings, you have to issue\nconn.commit()\n\nwhen you actually want to commit your changes to the database. So you'd need the PyQT version of that after your insert and before your select.\nA quick glance at the docs makes it look like the PyQT version is... | [
1,
0
] | [] | [] | [
"database",
"mysql",
"python",
"sql",
"sqlite"
] | stackoverflow_0006846740_database_mysql_python_sql_sqlite.txt |
Q:
Python: Summing class instances inside a list
I am familiar with the built-in sum() function for lists and have used it before, eg:
sum(list1[0:41])
when the list contains integers, but I'm in a situation where I have instances from a Class and I need them summed.
I have this Class:
class DataPoint:
def __ini... | Python: Summing class instances inside a list | I am familiar with the built-in sum() function for lists and have used it before, eg:
sum(list1[0:41])
when the list contains integers, but I'm in a situation where I have instances from a Class and I need them summed.
I have this Class:
class DataPoint:
def __init__(self, low, high, freq):
self.low = low
... | [
"Have you tried:\nsum(i.freq for i in items[0:41])\n\nIf you need the cumulative sum of the last \"i\" elements, the following is the most efficient approach:\nsums = [items[0].freq]\nfor i in items[1:]:\n sums.append(sums[-1] + i.freq)\n\nAs other posters already have anticipated, it is a bad programming style ... | [
7,
1,
0,
0
] | [] | [] | [
"class",
"instances",
"list",
"python",
"sum"
] | stackoverflow_0006920653_class_instances_list_python_sum.txt |
Q:
Advice on frameworks for creating web front-ends and reports of MySQL database
I am using a commercial PHP web application that stores information in a mysql database, and find myself needing to create some custom reports on that database information, ideally presented via the web with the ability of exporting the... | Advice on frameworks for creating web front-ends and reports of MySQL database | I am using a commercial PHP web application that stores information in a mysql database, and find myself needing to create some custom reports on that database information, ideally presented via the web with the ability of exporting the reports to PDF or some external format as well.
I could just slap together some PH... | [
"I would recommend Django, it has a management command that can help automatically generate models from an existing database, inspectdb. You could leverage that to quickly get going and start using Django's powerful ORM to build your reports.\n"
] | [
0
] | [] | [] | [
"mysql",
"php",
"python",
"reporting",
"ruby"
] | stackoverflow_0006921100_mysql_php_python_reporting_ruby.txt |
Q:
Why does using Python's '-i' or '-c' options cause readline history from previous sessions to be unavailable?
I'm using a .pythonsetup file to enable readline history in the manner described in the readline module docs. Normally, history from previous interactive interpreter sessions is available when I start up a... | Why does using Python's '-i' or '-c' options cause readline history from previous sessions to be unavailable? | I'm using a .pythonsetup file to enable readline history in the manner described in the readline module docs. Normally, history from previous interactive interpreter sessions is available when I start up a new session.
% python
>>> # history available...
However, when using -i or -c, past history is not available. It'... | [
"The man page for my python2.6 says\n\n-i ... It does not read the $PYTHONSTARTUP file.\n\nSince this is how you customized the readline behavior ( http://docs.python.org/py3k/library/readline.html#example ), it doesn't take effect when you use that option.\n",
"You can get this behavior if you use IPython:\nipyt... | [
3,
1
] | [] | [] | [
"python",
"readline"
] | stackoverflow_0006921365_python_readline.txt |
Q:
Indexing python array with a python array with redundant elements
I'm experiencing a problem with array indexing. Suppose you have an array a and another array b you want to use to use as index for a in order to assign some values to the position pointed by b elements.
a=numpy.zeros(5)
print a
[ 0. 0. 0. 0. 0... | Indexing python array with a python array with redundant elements | I'm experiencing a problem with array indexing. Suppose you have an array a and another array b you want to use to use as index for a in order to assign some values to the position pointed by b elements.
a=numpy.zeros(5)
print a
[ 0. 0. 0. 0. 0.]
Now I would like to increase the second element twice
b=numpy.arra... | [
"When you use an integer array for indexing another array, NumPy cannot create an adequate view, since the resulting array may not be representable with strides. Therefore, it will return a copy:\n>>> a = np.zeros(5)\n>>> b = np.array([1, 1])\n>>> c = a[b]\n>>> c\narray([ 0., 0.])\n>>> c.base is a\nFalse\n\nWhen ... | [
7,
2,
1
] | [] | [] | [
"arrays",
"indexing",
"numpy",
"python",
"scipy"
] | stackoverflow_0006913997_arrays_indexing_numpy_python_scipy.txt |
Q:
Regex replace with correct spacing
I need help on some regex problem with chinese characters in python.
"拉柏多公园" is the correct form of the word, but in a text i found "拉柏 多公 园", what regex should i use to replace the characters.
import re
name = "拉柏多公园"
line = "whatever whatever it is then there comes a 拉柏 多公 园 s... | Regex replace with correct spacing | I need help on some regex problem with chinese characters in python.
"拉柏多公园" is the correct form of the word, but in a text i found "拉柏 多公 园", what regex should i use to replace the characters.
import re
name = "拉柏多公园"
line = "whatever whatever it is then there comes a 拉柏 多公 园 sort of thing"
line2 = "whatever whatever... | [
"(I assume you're using python 3, since you're using unicode characters in regular strings. For python 2, add u before each string literal.)\nPython 3\nimport re\n\nname = \"拉柏多公园\"\n# the string of Chinese characters, with any number of spaces interspersed.\n# The regex will match any surrounding spaces.\nregex = ... | [
4
] | [] | [] | [
"cjk",
"python",
"regex",
"replace",
"str_replace"
] | stackoverflow_0006921363_cjk_python_regex_replace_str_replace.txt |
Q:
Django upload image - From a form to Rackspace/S3 with no manipulation
I simply want to upload an image (JPG) using a form, then send that image to Rackspace 'Cloud Files' or Amazon 'S3'.
No manipulating the file.
No saving to disk, everything to memory (am hosted on a cloud server)
Image size won't exceed 75kb
... | Django upload image - From a form to Rackspace/S3 with no manipulation | I simply want to upload an image (JPG) using a form, then send that image to Rackspace 'Cloud Files' or Amazon 'S3'.
No manipulating the file.
No saving to disk, everything to memory (am hosted on a cloud server)
Image size won't exceed 75kb
Update (Two Caveats):
One: It also needs to work when data is posted from... | [
"How about ignoring python all together and just uploading directly to s3?\nYou can configure your s3 bucket to disallow uploading any files larger than $X bytes.\nHere's a simple example to illustrate uploading directly to s3 (and ignoring your image width/height conditions)\nhttp://sente.cc/upload_to_s3.html\ncod... | [
3,
2
] | [] | [] | [
"django",
"python",
"rackspace",
"rackspace_cloud"
] | stackoverflow_0006911567_django_python_rackspace_rackspace_cloud.txt |
Q:
In javascript, how would I do this rfind?
www.mydomain.com/invite/abc123
I want the function to return "abc123". The logic goes like this:
If there is a forward slash, then take all characters after the last forward slash.
In python, I write it like this:
if s.find('/') >= 0:
return s[s.rfind('/')+1:]
But ... | In javascript, how would I do this rfind? | www.mydomain.com/invite/abc123
I want the function to return "abc123". The logic goes like this:
If there is a forward slash, then take all characters after the last forward slash.
In python, I write it like this:
if s.find('/') >= 0:
return s[s.rfind('/')+1:]
But how do I do this in javascript?
| [
"You can just say\ns.substring(s.lastIndexOf(\"/\"))\n\nReturns the whole string if s has no slashes!\n",
"You don't need regexp to do this.\nvar s = \"www.mydomain.com/invite/abc123\";\n\nif(s.indexOf(\"/\")>=0)\n alert(s.split(\"/\").pop());\n\n"
] | [
9,
7
] | [] | [] | [
"javascript",
"python"
] | stackoverflow_0006921560_javascript_python.txt |
Q:
Querying GAE Datastore returns property types instead of values
I have stored data in the gae datastore, but when I query the data and reference the properties I seem to be getting a reference to the object rather than the value of the attribute.
class ClassDefinitions(db.Model):
class_name = db.StringProperty... | Querying GAE Datastore returns property types instead of values | I have stored data in the gae datastore, but when I query the data and reference the properties I seem to be getting a reference to the object rather than the value of the attribute.
class ClassDefinitions(db.Model):
class_name = db.StringProperty
class_definition = db.TextProperty
class FlexEntityAdminHandler... | [
"When creating the model, you need to create actual instances of the property type classes:\nclass ClassDefinitions(db.Model):\n class_name = db.StringProperty()\n class_definition = db.TextProperty()\n\n(Note the ().)\n"
] | [
4
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0006921583_google_app_engine_google_cloud_datastore_python.txt |
Q:
Beginner oop question: modifying a variable and using it in another method
I am writing some unit tests which I have simplified to the following:
class BuyTicket(TestCase):
ipn = {
"payer_email": "bishan_1233269544_per@gmail.com",
"quantity": "1",
}
def setUp(self):
self.atten... | Beginner oop question: modifying a variable and using it in another method | I am writing some unit tests which I have simplified to the following:
class BuyTicket(TestCase):
ipn = {
"payer_email": "bishan_1233269544_per@gmail.com",
"quantity": "1",
}
def setUp(self):
self.attendee = create_user(username='attendee', \
ema... | [
"I don't think you want to do that: \n I think Unittest creates a new instance of BuyTicket for each test function, and calls setUp before each test. \nIf one test depends on another like you describe, you should factor out the dependency into separate code or call from the setup() function. If you really need to ... | [
0,
0
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0006921544_oop_python.txt |
Q:
Python: how to have dynamicly generated function arguments without using an eval
I am trying to setup a system where users can submit an equation to be solved. I have a class, DP, which represents the full parameterization of the problem. A different class, dpsolver, takes a dp object, constructs the matrices, and... | Python: how to have dynamicly generated function arguments without using an eval | I am trying to setup a system where users can submit an equation to be solved. I have a class, DP, which represents the full parameterization of the problem. A different class, dpsolver, takes a dp object, constructs the matrices, and will solve the problem.
When creating the DP object, one of the attributes is a funct... | [
"From your question:\n\nalternatively using lists and then using eval to unpack the list\n within equation1\n\nYou may very well already be aware of this, but in case you're not, calling:\nequation1(*list_of_parameters)\n\nDoes just this.\nSimilarly, doing \nequation1(**dict_of_parameters)\n\nWill expand a dict to... | [
3
] | [] | [] | [
"python"
] | stackoverflow_0006921651_python.txt |
Q:
Boolean fields in MySQL Django Models?
At Django, a boolean field in MySQL is stored as a TINYINT. When I retrieve it, I get 0 or 1. Shouldn't I get False or True? Is there a way to achieve this behaviour?
A:
You could create your own method for your model that evaluates this for you:
class User(models.Model):
... | Boolean fields in MySQL Django Models? | At Django, a boolean field in MySQL is stored as a TINYINT. When I retrieve it, I get 0 or 1. Shouldn't I get False or True? Is there a way to achieve this behaviour?
| [
"You could create your own method for your model that evaluates this for you:\nclass User(models.Model):\n active_status = models.BooleanField(default=1)\n\n def is_active(self):\n return bool(self.active_status)\n\nThen any tests you perform against this field could just reference the method instead:\... | [
7,
1,
1,
0
] | [] | [] | [
"boolean",
"django",
"mysql",
"python"
] | stackoverflow_0001778948_boolean_django_mysql_python.txt |
Q:
How can I package my python application with external python libraries?
I hope my title was clear. I'm using wxpython for making a GUI and I want it to be able to be opened, extracted, and have it work on all operating systems. I was able to include twill by finding a folder called twill inside the twill archive, ... | How can I package my python application with external python libraries? | I hope my title was clear. I'm using wxpython for making a GUI and I want it to be able to be opened, extracted, and have it work on all operating systems. I was able to include twill by finding a folder called twill inside the twill archive, which worked fine. However, I'm unable to figure out how to correctly package... | [
"Unfortunately, there's just no one stop solution so that a single installable executable will work across all operating systems. The right solution is really to provide a different installer or executable for each OS; For windows, use py2exe, for mac, py2app is a good choice, and for linux you should just provid... | [
2,
1,
0
] | [] | [] | [
"packaging",
"python",
"wxpython"
] | stackoverflow_0006917456_packaging_python_wxpython.txt |
Q:
Looking for a more complete explanation of how to upload video to youtube
Possible Duplicate:
Problem accessing user uploaded video in temporary memory
So I've tried this question here and here but I might have been being too specific or misguided in my question.
Essentially I am trying to take a video submitted... | Looking for a more complete explanation of how to upload video to youtube |
Possible Duplicate:
Problem accessing user uploaded video in temporary memory
So I've tried this question here and here but I might have been being too specific or misguided in my question.
Essentially I am trying to take a video submitted via <form> <input type='file'/> </form> and submit it to youtube.
I've look... | [
"Your current problem is that your file hasn't been saved to disk, so how could it have a path?\nThere are two obvious solutions. First, you can change your FILE_UPLOAD_HANDLERS setting to have only one handler, like so:\n(\"django.core.files.uploadhandler.TemporaryFileUploadHandler\",)\n\nso it will automatically ... | [
0
] | [] | [] | [
"django",
"file_upload",
"html",
"python",
"youtube"
] | stackoverflow_0006921178_django_file_upload_html_python_youtube.txt |
Q:
It's possible to integrate Python with Java?
I have a main application that is coded with Java, but I want to use Python because the NLTK lib.
I want to know if it's possible do some integration with these two languages. Thinks like passing parameters from Java to Python and retrieving processed data from Python ... | It's possible to integrate Python with Java? | I have a main application that is coded with Java, but I want to use Python because the NLTK lib.
I want to know if it's possible do some integration with these two languages. Thinks like passing parameters from Java to Python and retrieving processed data from Python to Java.
| [
"Try Jython\nFrom their FAQ site:\n\nWhat is Jython?\nJython is the successor to JPython. The Jython project was created in\n accordance with the CNRI JPython 1.1.x license, in order to ensure the\n continued existence and development of this important piece of Python\n software. The intent is to manage this pro... | [
6
] | [] | [] | [
"integration",
"java",
"nltk",
"python"
] | stackoverflow_0006922076_integration_java_nltk_python.txt |
Q:
Django and Python + uWSGI
Using instruction I try to connect Python + uWSGI.
I made default project in a folder /home/sanya/django/pasteurl.
However, have opened it in a browser I get
uWSGI Error
wsgi application not found
Logs contain the following:
binding on TCP port: 9001
your server socket listen backlog is ... | Django and Python + uWSGI | Using instruction I try to connect Python + uWSGI.
I made default project in a folder /home/sanya/django/pasteurl.
However, have opened it in a browser I get
uWSGI Error
wsgi application not found
Logs contain the following:
binding on TCP port: 9001
your server socket listen backlog is limited to 64 connections
added... | [
"FWIW, looking at the source code, starting at line 1997, we see that uWSGI emits the exact sequence of error messages that you are receiving if it cannot find an applications dictionary.\nLooking at your django.wsgi file, we see that the line, \n`applications = {'/': 'application'} \n\nis commented out. I wonder w... | [
1,
1
] | [] | [] | [
"django",
"nginx",
"python",
"uwsgi",
"wsgi"
] | stackoverflow_0003775755_django_nginx_python_uwsgi_wsgi.txt |
Q:
Dollar notation in script languages - why?
Does anyone know, what is the actual reason behind "dollar variable notation" in some of the scripting languages, i.e. PHP or Perl? Python creators did not find $variable useful, neither do I. Why does PHP and Perl force me to press shift-4 so often?
(OK, in Perl you can ... | Dollar notation in script languages - why? | Does anyone know, what is the actual reason behind "dollar variable notation" in some of the scripting languages, i.e. PHP or Perl? Python creators did not find $variable useful, neither do I. Why does PHP and Perl force me to press shift-4 so often?
(OK, in Perl you can somehow explain it with distinguishing $scalar, ... | [
"I don't know if this is the main reason, but if PHP did not have variables with an identifying marker, the following would not be possible.\necho \"Welcome back $name, we last saw you on $date\";\n\nUpdate:\nIt also creates something called a variable variable possible. The usefulness of a variable variable is deb... | [
8,
7,
6,
2
] | [] | [] | [
"javascript",
"perl",
"php",
"python"
] | stackoverflow_0006922245_javascript_perl_php_python.txt |
Q:
How to generate checksum from hex byte using python
I am creating a hex file using python and at the end I need to add a checksum that consists of sum of all hex values so that checksum = Byte 0x000000 + Byte 0x000001 + … + Byte 0x27DAFF (not including this 4 bytes). This checksum shall then be written to buffer a... | How to generate checksum from hex byte using python | I am creating a hex file using python and at the end I need to add a checksum that consists of sum of all hex values so that checksum = Byte 0x000000 + Byte 0x000001 + … + Byte 0x27DAFF (not including this 4 bytes). This checksum shall then be written to buffer at position 0x27DB00-0x27DB03 as unsigned long.
Any good i... | [
"the following two solutions worked:\nchecksum = sum(map(ord, b))\n\nor:\nchecksum = sum(bytearray(b))\n\n"
] | [
4
] | [] | [] | [
"byte",
"checksum",
"crc",
"hex",
"python"
] | stackoverflow_0006917330_byte_checksum_crc_hex_python.txt |
Q:
Writing and listening to the same serial port in python
Is there anyway to do this without getting a "COM PORT IN USE" error? I have a a service that listens to gps GPRMC sentences on a com port. But I don't have this device on my testing computer. So I wanted to write a python script to simulate GPRMC sentences o... | Writing and listening to the same serial port in python | Is there anyway to do this without getting a "COM PORT IN USE" error? I have a a service that listens to gps GPRMC sentences on a com port. But I don't have this device on my testing computer. So I wanted to write a python script to simulate GPRMC sentences on the port while my other python script listens to the same p... | [
"Writing to a serial port does not leave a message on the serial port to be read by the same device. This just isn't how a serial port works and is not how most OSes are written to allow as a buffer behavior. What you really need is a virtual serial port.\nCheck out this section of a wikipedia article on COM port r... | [
3
] | [] | [] | [
"pyserial",
"python",
"serial_port"
] | stackoverflow_0006921687_pyserial_python_serial_port.txt |
Q:
How can I pass arguments to Tkinter button's callback command?
I got 2 buttons, respectively named 'ButtonA', 'ButtonB'.
I want the program to print 'hello, ButtonA' and 'hello, ButtonB' if any button is clicked.
My code is as follows:
def sayHi(name):
print 'hello,', name
root = Tk()
btna = Button(root, text... | How can I pass arguments to Tkinter button's callback command? | I got 2 buttons, respectively named 'ButtonA', 'ButtonB'.
I want the program to print 'hello, ButtonA' and 'hello, ButtonB' if any button is clicked.
My code is as follows:
def sayHi(name):
print 'hello,', name
root = Tk()
btna = Button(root, text = 'ButtonA', command = lambda: text)
btna.pack()
When I click Butt... | [
"This should work:\n...\nbtnaText='ButtonA'\nbtna = Button(root, text = btnaText, command = lambda: sayHi(btnaText))\nbtna.pack()\n\nFor more information take a look at Tkinter Callbacks\n",
"text is not a function in your case. Just have it as:\nvalue = 'ButtonA'\nbtna = Button(root, text = value, command = lamb... | [
28,
3
] | [] | [] | [
"arguments",
"callback",
"python",
"tkinter"
] | stackoverflow_0006922621_arguments_callback_python_tkinter.txt |
Q:
python base64 string decoding
I've got what's supposed to be a UCS-2 encoded xml document that I've managed to build a DOM based on minidom after some tweaking.
The issue is that I'm supposed to have some data encoded on base64. I know for a fact that:
AME= (or \x00A\x00M\x00E\x00=) is base64 code for Á
How would... | python base64 string decoding | I've got what's supposed to be a UCS-2 encoded xml document that I've managed to build a DOM based on minidom after some tweaking.
The issue is that I'm supposed to have some data encoded on base64. I know for a fact that:
AME= (or \x00A\x00M\x00E\x00=) is base64 code for Á
How would I decode that?
http://www.fileform... | [
"Check this out\n>>> import base64\n>>> base64.b64decode('AME=').decode('UTF-16')\nu'\\uc100'\n>>> base64.b64decode('AME=').decode('UTF-16LE') \nu'\\uc100'\n>>> base64.b64decode('AME=').decode('UTF-16BE')\nu'\\xc1'\n\nPerhaps you are looking for big endian decoding?\n"
] | [
17
] | [] | [] | [
"encoding",
"python",
"ucs2"
] | stackoverflow_0006923159_encoding_python_ucs2.txt |
Q:
Twisted Python IRC bot set channel modes
How can I use Twisted Python to automatically voice users in my channel and do other channel operator commands (and even network oper commands? like handling vhost requests, etc.)?
A:
You can use the mode function of the IRCClient to set channel and user modes:
http://tw... | Twisted Python IRC bot set channel modes | How can I use Twisted Python to automatically voice users in my channel and do other channel operator commands (and even network oper commands? like handling vhost requests, etc.)?
| [
"You can use the mode function of the IRCClient to set channel and user modes:\nhttp://twistedmatrix.com/documents/11.0.0/api/twisted.words.protocols.irc.IRCClient.html#mode\nIf you follow the guide at http://www.eflorenzano.com/blog/post/writing-markov-chain-irc-bot-twisted-and-python/ then you could create a priv... | [
0
] | [] | [] | [
"bots",
"irc",
"python",
"twisted"
] | stackoverflow_0006688258_bots_irc_python_twisted.txt |
Q:
How to deserialize and serialize AMF Packets in Python?
I am rewriting the following Perl code in Python:
my $data = Data::AMF::Packet->new->deserialize($packet);
$data->messages->[0]->{value}->[1] = $data->messages->[1]->{value}->[1] = $mid;
$data = $data->serialize;
I would like to know how to write this ... | How to deserialize and serialize AMF Packets in Python? | I am rewriting the following Perl code in Python:
my $data = Data::AMF::Packet->new->deserialize($packet);
$data->messages->[0]->{value}->[1] = $data->messages->[1]->{value}->[1] = $mid;
$data = $data->serialize;
I would like to know how to write this in Python? I am new to PyAMF and the examples I googled wont ... | [
"Something along the lines of:\nfrom pyamf import remoting\n\npacket = remoting.decode(bytes)\npacket['/1'][1] = packet['/2'][1]\n\nstream = remoting.encode(packet)\n\nbytes = stream.getvalue()\n\n"
] | [
1
] | [] | [] | [
"adobe",
"amf",
"perl",
"pyamf",
"python"
] | stackoverflow_0006920799_adobe_amf_perl_pyamf_python.txt |
Q:
Avoid Circular Model Imports in Django Apps
I have a django project with 2 apps like this:
## tags app, models.py
class Tag(models.Model):
title = models.CharField(max_length=50)
## items app, models.py
from application.tags.models import Tag
class Item(models.Model):
title = models.CharField(max_length=... | Avoid Circular Model Imports in Django Apps | I have a django project with 2 apps like this:
## tags app, models.py
class Tag(models.Model):
title = models.CharField(max_length=50)
## items app, models.py
from application.tags.models import Tag
class Item(models.Model):
title = models.CharField(max_length=300)
tags = models.ManyToManyField(Tag, rela... | [
"When you define models with foreign keys, you can use the format:\ntags = models.ManyToManyField('tags.Tag', ...)\n\nThis means you don't need to have imported the Tag class, just installed the tags app.\nThen you can store a function in a different location, that might import both Tag and Item, and not have to wo... | [
27
] | [] | [] | [
"circular_reference",
"contenttype",
"django",
"organization",
"python"
] | stackoverflow_0006923042_circular_reference_contenttype_django_organization_python.txt |
Q:
Executing Python script from Java in Tomcat project
I want to execute a Python script (including Scipy and Numpy) from Java which should be bundled with the tomcat project by eclipse. Calling Python from Java is trivial:
Runtime.getRuntime().exec("python ...");
How can I achieve bundling the script to call it at ... | Executing Python script from Java in Tomcat project | I want to execute a Python script (including Scipy and Numpy) from Java which should be bundled with the tomcat project by eclipse. Calling Python from Java is trivial:
Runtime.getRuntime().exec("python ...");
How can I achieve bundling the script to call it at the corresponding path? Is this even possible?
| [
"You mention tomcat, so I guess your project is in a jar-file. The file may not be available to the system as a file, but only bundled in your jar, so the python interpreter can't access it. You could get the contents as a InputStream. You can find an example here:\nHow to get path of executed jar file\nAfter that,... | [
1,
1
] | [] | [] | [
"eclipse",
"java",
"python",
"tomcat"
] | stackoverflow_0006530627_eclipse_java_python_tomcat.txt |
Q:
Mapping dictionary with rows values
My problem is how to map dictionary values to row indices. I have a dictionary like:
ordered_dict = OrderedDict(1:"id", 2:"name", 3:"address", 4:"salary")
And I got rows from a select query like:
row = ["David", 4500, "France", 121]
With the following code, where i get id as f... | Mapping dictionary with rows values | My problem is how to map dictionary values to row indices. I have a dictionary like:
ordered_dict = OrderedDict(1:"id", 2:"name", 3:"address", 4:"salary")
And I got rows from a select query like:
row = ["David", 4500, "France", 121]
With the following code, where i get id as first index in dictionary, which is fourth... | [
"This should do the work:\nresults = cursor.fetchall()\ncol_names = [column[0] for column in cursor.description]\nrows_dict = map(lambda row: dict(zip(col_names, row)), results)\n\nIt's working for PostgreSQL and SQLite3, but I haven't tested it with MySQL. If for postgres IndexError or something like this occurs, ... | [
3
] | [] | [] | [
"mapping",
"ordereddictionary",
"python"
] | stackoverflow_0006923930_mapping_ordereddictionary_python.txt |
Q:
Python: Need to attach extra header, after hidden defaults added by urllib2, before the request is sent
I know how to get at the response headers of a urllib2 request and also how to access those sent and print them out and the request is made, as detailed in the responses to this question.
However, I need to inte... | Python: Need to attach extra header, after hidden defaults added by urllib2, before the request is sent | I know how to get at the response headers of a urllib2 request and also how to access those sent and print them out and the request is made, as detailed in the responses to this question.
However, I need to intercept the request after the default headers, such as 'Content-Type' are added by the OpenerDirector, but befo... | [
"Just some ideas:\nThe implementation in urllib2.py:\ndef _open(self, req, data=None):\n result = self._call_chain(self.handle_open, 'default',\n 'default_open', req)\n if result:\n return result\n\n protocol = req.get_type()\n result = self._call_chain(self.handle_op... | [
1,
0,
0
] | [] | [] | [
"header",
"http",
"httplib",
"python",
"urllib2"
] | stackoverflow_0006912867_header_http_httplib_python_urllib2.txt |
Q:
How to inherit the properties of a member variable into the host class?
Imagine the following code:
class X(object):
def geta(self):
return self.__a
def seta(self, v):
self.__a = v
def __init__(self, a=0):
self.__a = a
a = property(geta, seta)
class Y(object):
def __... | How to inherit the properties of a member variable into the host class? | Imagine the following code:
class X(object):
def geta(self):
return self.__a
def seta(self, v):
self.__a = v
def __init__(self, a=0):
self.__a = a
a = property(geta, seta)
class Y(object):
def __init__(self, v):
self.X = X(v)
# !!! Here, not sure how to do it... | [
"Add this to Y:\ndef __getattr__(self, attr):\n return getattr(self.X, attr)\n\nNow all unresolved attribute references to a Y instance will forward to its contained X.\n",
"Properties are inherited like any other attribute... if you actually inherit from the class. What's wrong with that?\nclass Y(X): pass\n\... | [
2,
1
] | [] | [] | [
"attributes",
"class",
"inheritance",
"python"
] | stackoverflow_0006924521_attributes_class_inheritance_python.txt |
Q:
How to print number with commas as thousands separator and decimal places in Python/Django
I'm trying to display numbers in my Django templates with
commas as thousand sepaerator and
specifying the decimal places to round to.
e.g. 76384.8739439 -> 76,384.87
Django has template tags to achieve both these.
intco... | How to print number with commas as thousands separator and decimal places in Python/Django | I'm trying to display numbers in my Django templates with
commas as thousand sepaerator and
specifying the decimal places to round to.
e.g. 76384.8739439 -> 76,384.87
Django has template tags to achieve both these.
intcomma - for thousand separator and
floatformat - for decimal places
I can't seem to find a way to... | [
"{{ value|floatformat:2|intcomma }}\n\n"
] | [
18
] | [] | [] | [
"django",
"number_formatting",
"python"
] | stackoverflow_0006924706_django_number_formatting_python.txt |
Q:
How to convert int to 24bit string?
for read I use:
def UI24(t):
result = 0
for i in xrange(3):
result = (result << 8);
byte = unpack('>b',t[i-1])
result += byte;
return result
and for write ?
A:
Simpler to just pad them and treat as longs
>>> from struct import pack, unpack
... | How to convert int to 24bit string? | for read I use:
def UI24(t):
result = 0
for i in xrange(3):
result = (result << 8);
byte = unpack('>b',t[i-1])
result += byte;
return result
and for write ?
| [
"Simpler to just pad them and treat as longs\n>>> from struct import pack, unpack\n>>> def unpack24(s):\n... return unpack(\">L\",\"\\0\"+s)[0]\n... \n>>> def pack24(i):\n... return pack(\">L\",i)[1:]\n... \n\n",
"This is not tested !\ndef UI24back(value):\n result = \"\"\n for i in xrange(3):\n ... | [
5,
0
] | [] | [] | [
"python"
] | stackoverflow_0006924098_python.txt |
Q:
Trouble installing NumPy and Matplotlib on Mac (snow leopard)
Having installed Python 2.7 from the python website I have since tried to install both NumPy and Matplotlib, but when I do so a box comes up telling me it requires system python 2.6. Do I need to be running an older version!?
A:
Sourceforge version t... | Trouble installing NumPy and Matplotlib on Mac (snow leopard) | Having installed Python 2.7 from the python website I have since tried to install both NumPy and Matplotlib, but when I do so a box comes up telling me it requires system python 2.6. Do I need to be running an older version!?
| [
"Sourceforge version trees of those modules are tricky for OS X users. :P I was having problems installing them because I did't realize there were dmgs exactly built for Snow Leopard...\nThere are different version of .egg and .dmg files, you should pay attention to download. If have SL, you should installi these v... | [
5
] | [] | [] | [
"macos",
"matplotlib",
"numpy",
"osx_snow_leopard",
"python"
] | stackoverflow_0006904435_macos_matplotlib_numpy_osx_snow_leopard_python.txt |
Q:
Document python using Eclipse/Pydev
I am new to python development and use Eclipse/Pydev. Is there a nice way to integrate tools for generating documentations (e.g. Sphinx, pydoc) into the IDE to have a nice workflow, maybe showing the documentation in a separate tab?
A:
Maybe the Eclipse ReST editor can help y... | Document python using Eclipse/Pydev | I am new to python development and use Eclipse/Pydev. Is there a nice way to integrate tools for generating documentations (e.g. Sphinx, pydoc) into the IDE to have a nice workflow, maybe showing the documentation in a separate tab?
| [
"Maybe the Eclipse ReST editor can help you (I heard about it in the last Eclipse demo camp held in Grenoble/France):\nhttp://www.slideshare.net/tcalmant/rest-editor-eclipse-demo-camp-grenoble-2011\nhttp://marketplace.eclipse.org/content/rest-editor\n"
] | [
5
] | [] | [] | [
"eclipse",
"pydev",
"pydoc",
"python",
"python_sphinx"
] | stackoverflow_0006923974_eclipse_pydev_pydoc_python_python_sphinx.txt |
Q:
How to search through a JSON feed
I'm using the code below and make a call to the Google Maps API and parse some JSON data.
def getLocalityFromPostCode(postcode):
import urllib, json
import pprint
url = "http://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=false" % postcode
googleResp... | How to search through a JSON feed | I'm using the code below and make a call to the Google Maps API and parse some JSON data.
def getLocalityFromPostCode(postcode):
import urllib, json
import pprint
url = "http://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=false" % postcode
googleResponse = urllib.urlopen(url)
jsonResp... | [
"This looks like what you want :)\nresults = json.load(googleResponse)['results']\n\nfor result in results:\n for address_component in result['address_components']:\n if address_component['types'] == ['locality', 'political']\n # address_component['long_name'] and\n # address_compone... | [
7
] | [
"Create an object from the json and access the values by the keys\nimport json\nobj = json.loads(jsonString)\n\n"
] | [
-2
] | [
"google_maps",
"json",
"python"
] | stackoverflow_0006919789_google_maps_json_python.txt |
Q:
The most pythonic way for acessing "private" variables from another class instance
Imagine the following class that displays some sort of hierarchy:
class BaseList2D(object):
def __init__(self):
self._superobject = None
self._subobjects = []
def InsertUnder(self, other):
if se... | The most pythonic way for acessing "private" variables from another class instance | Imagine the following class that displays some sort of hierarchy:
class BaseList2D(object):
def __init__(self):
self._superobject = None
self._subobjects = []
def InsertUnder(self, other):
if self not in other._subobjects:
other._subobjects.append(self)
self... | [
"_foo is just a naming convention. Usually, there would be a property or something that sets the 'private' variable for you. If not, the convention is being (slightly) misused.\n"
] | [
1
] | [] | [] | [
"private_members",
"python"
] | stackoverflow_0006925063_private_members_python.txt |
Q:
How to create a new variable from the contents of another variable in python?
May it's very simple question, but I'm stuck here.
I have variable val as val="mandy", now i want to create a list whose name is the content of val. i.e. "mandy". so how to define mandy=[] in python.
It's like "$$" equivalent of PHP.
A:... | How to create a new variable from the contents of another variable in python? | May it's very simple question, but I'm stuck here.
I have variable val as val="mandy", now i want to create a list whose name is the content of val. i.e. "mandy". so how to define mandy=[] in python.
It's like "$$" equivalent of PHP.
| [
"You can do something like this in Python, but it's very un-Pythonic to do so (whereas it's a common PHP idiom as I gather). Don't use the language in a way it's not intended to be used.\nWhat you're trying to do is much better done by using a dictionary, a maximally optimized datatype in Python:\n>>> val = \"mandy... | [
2,
1,
0,
0
] | [
"Try this:\n>>> val = 'mandy'\n>>> vars()[val] = []\n>>> mandy\n[]\n\nSee more details about vars() builtin \n"
] | [
-3
] | [
"python"
] | stackoverflow_0006925079_python.txt |
Q:
django template boolean variable shows as 0 but is considred True. Why?
I have template variables that correctly can be displayed with {{ myclass.myvariable }} as either 1 or 0.
But when I use them in the if statement {% if myclass.myvariable %} they always are considered to be True, even when the value is 0.
Th... | django template boolean variable shows as 0 but is considred True. Why? | I have template variables that correctly can be displayed with {{ myclass.myvariable }} as either 1 or 0.
But when I use them in the if statement {% if myclass.myvariable %} they always are considered to be True, even when the value is 0.
The variables are 1-character charfield choices in my model, stored as 0 or 1, ... | [
"Because '0' (string) is not 0 (integer). '0' is non-zero-length string, which means it's True in a boolean context. If you store integers, you should be using IntegerField or PositiveIntegerField, not CharField.\n",
"If you are getting your values from a CharField then it is '0', not 0\n>>> True if 0 else False\... | [
6,
1,
0
] | [] | [] | [
"django",
"python",
"templates",
"variables"
] | stackoverflow_0006925150_django_python_templates_variables.txt |
Q:
How to know if my server is using SSL or not (with Twisted)
I've wrote a simple client and a server.
They both can configured to use SSL or not. You can set it up in the client and in the server.
My problem is, if I try to connect without SSL to a server setup with SSL, the connection is made but stuck. (of course... | How to know if my server is using SSL or not (with Twisted) | I've wrote a simple client and a server.
They both can configured to use SSL or not. You can set it up in the client and in the server.
My problem is, if I try to connect without SSL to a server setup with SSL, the connection is made but stuck. (of course... it is normal).
How my client can know that he is trying to co... | [
"Use a different port number for SSL connections. This is how HTTP / HTTPS are used.\nOr\nDefine a command in your protocol to transform the connection into SSL e.g. STARTTLS, based on a capability negotiation. This is one way the same thing is achieved in SMTP.\n",
"\nThe best solution will be that my client aut... | [
5,
0
] | [] | [] | [
"python",
"ssl",
"tcp",
"twisted"
] | stackoverflow_0006925122_python_ssl_tcp_twisted.txt |
Q:
Best way to automate the updating of google app engine datastore from external source?
I read "Best option for Google App Engine Datastore and external database", and I had already considered the SDC(we already use it for some things). However, I need to be able to automate the update of the datastore every 15 mi... | Best way to automate the updating of google app engine datastore from external source? | I read "Best option for Google App Engine Datastore and external database", and I had already considered the SDC(we already use it for some things). However, I need to be able to automate the update of the datastore every 15 minutes or so. When using a cronjob in AppEngine there is no user attached to the actions, th... | [
"I know it's kinda silly to answer your own question, but figured I may as well post my solution since there is no answer here.\nWhat Nick left a comment about is definitely one option for solving the the problem, but what I found to be easier, and will work in the current situation is to push the data out rather t... | [
1
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0006815939_google_app_engine_google_cloud_datastore_python.txt |
Q:
What library to use to extract text from images (OCR)?
I need to recognize text in images (OCR). What library can I use in Python to extract text from the images?
A:
Check out google tesseract-oct, which has it's own python module.
| What library to use to extract text from images (OCR)? | I need to recognize text in images (OCR). What library can I use in Python to extract text from the images?
| [
"Check out google tesseract-oct, which has it's own python module.\n"
] | [
8
] | [] | [] | [
"ocr",
"python"
] | stackoverflow_0006925442_ocr_python.txt |
Q:
How to prevent a process from terminating on a KeyboardInterrupt?
I've been messing around with a Django project.
What I want to achieve is the Django project starting up in another process while the parent process initiates a load of arbitary code I have written (the backend of my project). Obviously, the Django ... | How to prevent a process from terminating on a KeyboardInterrupt? | I've been messing around with a Django project.
What I want to achieve is the Django project starting up in another process while the parent process initiates a load of arbitary code I have written (the backend of my project). Obviously, the Django process and parent processes communicate. I'd like a dictionary to be r... | [] | [] | [
"Ok, as far I see no possibility to simply ignore exception. When you rise one, you always go straight into a \"except\" block if there is one. What I'm proposing here is something what will restart your django application on each ^C, but note, that there should be added some back door for leaving.\nIn theory, you ... | [
-1
] | [
"django",
"multiprocessing",
"python"
] | stackoverflow_0006926200_django_multiprocessing_python.txt |
Q:
read a multi tier csv file in python
I need to read the following data out of a text file;
[L02]
g,g,g,g,g,g,g,g,g,g,w,w,w,w,g,g
g,g,g,g,g,g,g,g,g,w,w,w,w,w,g,g
g,g,g,g,g,g,g,g,w,w,w,w,w,g,g,g
g,g,g,g,g,g,g,g,w,w,w,w,g,g,g,g
g,g,g,g,g,g,g,g,g,w,w,w,w,g,g,g
g,g,g,g,g,g,g,g,g,g,w,w,w,w,g,g
g,g,g,g,g,g,g,g,g,g,g,w,w,... | read a multi tier csv file in python | I need to read the following data out of a text file;
[L02]
g,g,g,g,g,g,g,g,g,g,w,w,w,w,g,g
g,g,g,g,g,g,g,g,g,w,w,w,w,w,g,g
g,g,g,g,g,g,g,g,w,w,w,w,w,g,g,g
g,g,g,g,g,g,g,g,w,w,w,w,g,g,g,g
g,g,g,g,g,g,g,g,g,w,w,w,w,g,g,g
g,g,g,g,g,g,g,g,g,g,w,w,w,w,g,g
g,g,g,g,g,g,g,g,g,g,g,w,w,w,g,g
g,g,g,g,g,g,g,g,g,g,g,w,w,g,g,g
g,g,... | [
"Here's a script that demonstrates how to break down the problem into reusable steps (functions) and performs the transformation your need.\nimport itertools\nimport operator\nimport re\nimport csv\nimport pprint\n\nclass TaggedLine(str):\n \"\"\"\n Override str to allow a tag to be added.\n \"\"\"\n de... | [
3,
1
] | [] | [] | [
"file_io",
"list",
"python"
] | stackoverflow_0006925551_file_io_list_python.txt |
Q:
Programmatically analyze CSS layout
I would like to spider a few blogs and programmatically analyze their html and css-based layouts to see e.g. if the sidebar is to the left or right of the main content, how many columns and how wide they are.
How would I do this the best way? Are there any tools or libraries I c... | Programmatically analyze CSS layout | I would like to spider a few blogs and programmatically analyze their html and css-based layouts to see e.g. if the sidebar is to the left or right of the main content, how many columns and how wide they are.
How would I do this the best way? Are there any tools or libraries I can use?
(I would prefer a solution in Pyt... | [
"This sounds like an extremely hard task to do using pure server-side CSS and HTML parsing - you would effectively have to recreate the browser's rendering engine to get reliable results.\nDepending on what you need this for, I could think of a way somewhere along these lines:\n\nFetch pages and style sheets using ... | [
2,
0,
0
] | [] | [] | [
"css",
"php",
"python",
"statistics"
] | stackoverflow_0005015532_css_php_python_statistics.txt |
Q:
Taking a fullpage screenshot using Selenium server in python
I am trying to take a full page screenshot of a url using selenium using python
I have found plenty of examples for webdriver but I am more interested in using it through
the server. Is it possible if yes, can anyone point me in the right direction? The ... | Taking a fullpage screenshot using Selenium server in python | I am trying to take a full page screenshot of a url using selenium using python
I have found plenty of examples for webdriver but I am more interested in using it through
the server. Is it possible if yes, can anyone point me in the right direction? The reason I am interested in the server version is to reduce load, do... | [
"The captureEntirePageScreenshot command through Selenium IDE is exported like this into Python 2 (Remote Control)\nsel.capture_entire_page_screenshot(\"entirePageScreenshot.png\", \"\")\n\n"
] | [
1
] | [] | [] | [
"python",
"screenshot",
"selenium"
] | stackoverflow_0006740467_python_screenshot_selenium.txt |
Q:
how do i make links clickable in QtWebView?
I'm in the process of writing a web browser with QtWebView, i tested it using an html page but it turns out the links are not working. What do i do?
A:
You should set a "link delegation policy" for WebView's page, because it defaults to "DontDelegateLinks".
Try:
webVie... | how do i make links clickable in QtWebView? | I'm in the process of writing a web browser with QtWebView, i tested it using an html page but it turns out the links are not working. What do i do?
| [
"You should set a \"link delegation policy\" for WebView's page, because it defaults to \"DontDelegateLinks\".\nTry:\nwebView.page().setLinkDelegationPolicy(QWebPage.DelegateAllLinks)\n\nAnd connect page's link_clicked() signal to appropriate slot.\nLook at:\nhttp://doc.qt.nokia.com/4.7-snapshot/qwebview.html#page\... | [
2
] | [] | [] | [
"pyqt4",
"python"
] | stackoverflow_0006926590_pyqt4_python.txt |
Q:
How to dynamically add options to optparser?
I have a system, where you can modify, which modules will be loaded (and run; "module" is not necessarily python module, it can combine several modules). The program can run module A and B. Now, I want to have an option that every module can define (add) its own paramet... | How to dynamically add options to optparser? | I have a system, where you can modify, which modules will be loaded (and run; "module" is not necessarily python module, it can combine several modules). The program can run module A and B. Now, I want to have an option that every module can define (add) its own parameters. Let's say A wants to have -n and B wants to h... | [
"You should consider moving to a library that supports the concept of sub-parsers, such as argparse (which deprecates optparse anyway), so that each library can create its own parser rules, and the main program can just combine them.\n",
"When I had this problem I ended up using a class derived from ArgumentParse... | [
2,
1
] | [] | [] | [
"code_organization",
"configuration",
"module",
"python"
] | stackoverflow_0006899997_code_organization_configuration_module_python.txt |
Q:
Can anyone perhaps teach me how to further optimize this 'print up to the nth prime number' script?
I'm a 17 year old getting started with programming with the help of the Python programming language.
I've been seeking to optimize this algorithm, perhaps by eliminating one of the loops, or with a better test to ch... | Can anyone perhaps teach me how to further optimize this 'print up to the nth prime number' script? | I'm a 17 year old getting started with programming with the help of the Python programming language.
I've been seeking to optimize this algorithm, perhaps by eliminating one of the loops, or with a better test to check for prime numbers.
Trying to calculate and display 100000 prime numbers has the script pausing for ab... | [
"You could use prime sieve, and with a simple twist:\n\nDefine the first prime 2 as you do, set the largest number reached (max) to 2;\nGenerate a list of n consecutive numbers from max+1 to max+n;\nUse sieve with the primes on this list. When sieving, set the beginning number for each prime to the smallest number ... | [
2,
1,
0,
0
] | [
"Any number that ends in 5, other than 5, is not a prime. So you can put a statement that skips any number ending in 5 that is greater than 5.\n"
] | [
-1
] | [
"algorithm",
"numbers",
"optimization",
"performance",
"python"
] | stackoverflow_0006921348_algorithm_numbers_optimization_performance_python.txt |
Q:
Python - Sphinx adding image gives error
In chapter1.rst, I have the following:
TEST
****
* Test1
.. image:: ../images/snap.png
When I run sphinx-build (Sphinx 1.0.7), I get this error:
Exception occurred: File "/usr/lib/python2.6/posixpath.py", line 70, in join path += '/' + b
UnicodeDecodeError: 'ascii' c... | Python - Sphinx adding image gives error | In chapter1.rst, I have the following:
TEST
****
* Test1
.. image:: ../images/snap.png
When I run sphinx-build (Sphinx 1.0.7), I get this error:
Exception occurred: File "/usr/lib/python2.6/posixpath.py", line 70, in join path += '/' + b
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 15: or... | [
"Maybe the full path of ../images/snap.png contain no ASCII char.\nChange you project path to an English only path and try again.\n"
] | [
1
] | [] | [] | [
"python",
"python_sphinx"
] | stackoverflow_0006924758_python_python_sphinx.txt |
Q:
Split in py. write in django
asd = "qweasdzxc";
qwen = asd.split("")
self.response.out.write(qwen[0]) # write q
i can split the sentence with this way but i want to do this with using django template in my html doc.
How can i do this
Thanks for helping
A:
You might want to write a custom filter for django fo... | Split in py. write in django | asd = "qweasdzxc";
qwen = asd.split("")
self.response.out.write(qwen[0]) # write q
i can split the sentence with this way but i want to do this with using django template in my html doc.
How can i do this
Thanks for helping
| [
"You might want to write a custom filter for django for this. Here is a snippet for splitting.\nThere is also make_list and slice (look on the same page as the last link) to accomplish the same goal. \nGiven the example slice is probably what you want.\n"
] | [
0
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0006927054_django_django_templates_python.txt |
Q:
Proxing Python class to Objective-C
I try to proxy existing Python class to Objective-C. I started from simple sample of Python class:
Test.py
class Test:
def __init__(self):
self.text = ""
def addText(self, _text):
self.text = self.text + _text
def addSomeText(self):
self.ad... | Proxing Python class to Objective-C | I try to proxy existing Python class to Objective-C. I started from simple sample of Python class:
Test.py
class Test:
def __init__(self):
self.text = ""
def addText(self, _text):
self.text = self.text + _text
def addSomeText(self):
self.addText("SomeText")
Then I wrote Objectiv... | [
"I just want to make sure that you wrote newText method without return type intentionally..\nobjective-c methods have its return type most likely, and if you don't want to a specific type to be return use keyword \"id\".\n"
] | [
0
] | [] | [] | [
"objective_c",
"pyobjc",
"python"
] | stackoverflow_0006484266_objective_c_pyobjc_python.txt |
Q:
writing multiple data calculated from a function in the same file
I am trying to write a data calculated from this function in a file. But the function is called number of times. Say there are 9 numbers in another file and this function will calculate the root for each of those 9 numbers. These 9 roots from this f... | writing multiple data calculated from a function in the same file | I am trying to write a data calculated from this function in a file. But the function is called number of times. Say there are 9 numbers in another file and this function will calculate the root for each of those 9 numbers. These 9 roots from this function should be written in the same file. But the way I have done it ... | [
"Your function does two things: It calculates the roots of a polynomial, and it writes the result to an output file. Functions should ideally do one thing. \nSo, try breaking this up into a function that receives a polynomial and returns a list containing the roots, and then just write that list to a file in one st... | [
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0006923820_python.txt |
Q:
How can i put number in the list in python
I have numbers like this :
-1
1
2
3
-1
1
3
2
and i would like to put this number in list like [-1,1,2,3,-1,1,3,2] and delete -1 from the list.
A:
Like this?
>>> a = [-1, 1, 2, 3, -1, 1, 3, 2]
>>> a = [x for x in a if x != -1]
>>> a
[1, 2, 3, 1, 3, 2]
A:
In [5]: l = ... | How can i put number in the list in python | I have numbers like this :
-1
1
2
3
-1
1
3
2
and i would like to put this number in list like [-1,1,2,3,-1,1,3,2] and delete -1 from the list.
| [
"Like this?\n>>> a = [-1, 1, 2, 3, -1, 1, 3, 2]\n>>> a = [x for x in a if x != -1]\n>>> a\n[1, 2, 3, 1, 3, 2]\n\n",
"In [5]: l = [-1,1,2,3,-1,1,3,2]\n\nIn [6]: l = [item for item in l if item != -1]\n\nIn [7]: l\nOut[7]: [1, 2, 3, 1, 3, 2]\n\n",
"here is the code:\nIn [1]: [int(x) for x in \"-1 1 2 3 -1 1 3 2\"... | [
1,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0006926909_python.txt |
Q:
Python How to list all methods/classes that have been imported into a class
How to list all methods/classes that have been imported into a class. Take an example
from module1 import method1
from module2 import method2
class foo(object):
def say_foo(self):
method1()
def talk(self):
method2()
is ... | Python How to list all methods/classes that have been imported into a class | How to list all methods/classes that have been imported into a class. Take an example
from module1 import method1
from module2 import method2
class foo(object):
def say_foo(self):
method1()
def talk(self):
method2()
is it possible to list all methods used in the foo class? i know inspect.getmembers... | [
"To be brutally honest, your question doesn't make a whole lot of sense, and here is why:\nAt the point when foo is defined, no connection is made between the two globals called by say_foo and talk and the two functions imported at the top of your code.\nFor example, the interpreter will not complain about the foll... | [
3,
2,
1
] | [] | [] | [
"function",
"python"
] | stackoverflow_0006927234_function_python.txt |
Q:
Scientific computing in Python for MATLAB programmers
I was wondering if anybody knows of a good tutorial or introductory text on scientific computing on Python/SciPy for MATLAB programmers.
I was thinking of something along the lines of David Hiebeler's text on R for MATLAB programmers, which provides a side-by-s... | Scientific computing in Python for MATLAB programmers | I was wondering if anybody knows of a good tutorial or introductory text on scientific computing on Python/SciPy for MATLAB programmers.
I was thinking of something along the lines of David Hiebeler's text on R for MATLAB programmers, which provides a side-by-side reference between both languages.
To clarify, my curren... | [
"Take a look at http://www.scipy.org/NumPy_for_Matlab_Users\nYou didn't ask for tools, but I thought I'd mention Sage.\n",
"Rosetta Code is a great resource for translating between languages. Most problems have a python example, and there are several hundred MATLAB equivalents.\n",
"Might be a little outdated ... | [
11,
3,
2
] | [] | [] | [
"matlab",
"python",
"scipy"
] | stackoverflow_0006916268_matlab_python_scipy.txt |
Q:
Is there a way to capture the collection of shell commands that fabric outputs?
I've got a collection of fab files that I use to manage servers, install applications on them etc for clients. Some of them are not very happy when I deliver install documentation as a fabfile and readme. There are usually experienced ... | Is there a way to capture the collection of shell commands that fabric outputs? | I've got a collection of fab files that I use to manage servers, install applications on them etc for clients. Some of them are not very happy when I deliver install documentation as a fabfile and readme. There are usually experienced sysadmins, just not python programmers. If I could give them a bash script that is a ... | [
"You wrote:\n\nIf I could give them a bash script that is a record of what the various fabfiles did then that would be great.\n\nand later\n\nI don't need help to manually translate fab commands into bash. I'm looking for a programatic way to capture the stream of commands, either from paramiko or fabric or on the ... | [
1
] | [] | [] | [
"bash",
"fabric",
"paramiko",
"python"
] | stackoverflow_0006911977_bash_fabric_paramiko_python.txt |
Q:
How to Refresh Python Script Once in Awhile?
So I've created a class, which contains GUI using wxPython.
How do you make it so that it refreshes itself say every minute?
A:
For things that happen on intervals, use a Timer. From WxPyWiki:
def on_timer(event):
pass # do whatever
TIMER_ID = 100 # pick a num... | How to Refresh Python Script Once in Awhile? | So I've created a class, which contains GUI using wxPython.
How do you make it so that it refreshes itself say every minute?
| [
"For things that happen on intervals, use a Timer. From WxPyWiki:\ndef on_timer(event):\n pass # do whatever\n\nTIMER_ID = 100 # pick a number\ntimer = wx.Timer(panel, TIMER_ID) # message will be sent to the panel\ntimer.Start(100) # x100 milliseconds\nwx.EVT_TIMER(panel, TIMER_ID, on_timer) # call the on_t... | [
2,
0,
0
] | [] | [] | [
"python",
"refresh",
"reload",
"user_interface",
"wxpython"
] | stackoverflow_0006923875_python_refresh_reload_user_interface_wxpython.txt |
Q:
Yielding from sorted iterators in sorted order in Python?
Is there a better way to merge/collate a bunch of sorted iterators into one so that it yields the items in sorted order? I think the code below works but I feel like there is a cleaner, more concise way of doing it that I'm missing.
def sortIters(*iterables... | Yielding from sorted iterators in sorted order in Python? | Is there a better way to merge/collate a bunch of sorted iterators into one so that it yields the items in sorted order? I think the code below works but I feel like there is a cleaner, more concise way of doing it that I'm missing.
def sortIters(*iterables, **kwargs):
key = kwargs.get('key', lambda x : x)
next... | [
"yes, you want heapq.merge() which does exactly one thing; iterate over sorted iterators in order\ndef sortkey(row):\n return (row[5], row)\n\ndef unwrap(key):\n sortkey, row = key\n return row\n\nfrom itertools import imap\nFILE_LIST = map(file, ['foo.csv', 'bar.csv'])\ninput_iters = imap(sortkey, map(csv... | [
29
] | [] | [] | [
"iterator",
"python",
"sorting"
] | stackoverflow_0006928421_iterator_python_sorting.txt |
Q:
Detect an invalid keyword argument
I have the following function:
def foo(**kwargs):
if not kwargs:
# No keyword arguments? It's all right. Set defaults here...
elif ('start_index' or 'end_index') in kwargs:
# Do something here...
else:
# Catch unexpected keyword arguments
raise TypeError("%r... | Detect an invalid keyword argument | I have the following function:
def foo(**kwargs):
if not kwargs:
# No keyword arguments? It's all right. Set defaults here...
elif ('start_index' or 'end_index') in kwargs:
# Do something here...
else:
# Catch unexpected keyword arguments
raise TypeError("%r are invalid keyword arguments" % (kwarg... | [
"Why do you need **kwargs here? Just\ndef foo(start_index=None, end_index=None):\n\nand Python will perform all validation for you.\n",
"For the sake of completeness, Here's an alternative that still uses **kwargs.\ndef foo(**kwargs):\n start_index = kwargs.pop('start_index', STARTINDEX_DEFAULT)\n end_index = k... | [
13,
5,
1,
0
] | [] | [] | [
"arguments",
"keyword",
"python"
] | stackoverflow_0006928068_arguments_keyword_python.txt |
Q:
tkinter radio buttons does not work inside function
I am trying to write a GUI (in fact a PyMOL plugin) with radio buttons. I need the radio buttons to be inside a function. I have two problems (if the radio buttons are outside a function I don´t have any problem):
1) the last two radio button looks gray and che... | tkinter radio buttons does not work inside function | I am trying to write a GUI (in fact a PyMOL plugin) with radio buttons. I need the radio buttons to be inside a function. I have two problems (if the radio buttons are outside a function I don´t have any problem):
1) the last two radio button looks gray and checked. (I think the correct behavior should be only one ch... | [
"I should set the master explicitly, otherwise it will use the PyMOL GUI as master.\nv = StringVar(master=master)\n\nPS: thanks Thomas Holder for the answer.\n",
"It works for me (I copied your code and added the lines from Tkinter import * and if __name__ == \"__main__\": draw_gui() which I assume you have too).... | [
2,
0
] | [] | [] | [
"function",
"python",
"radio_button",
"tkinter"
] | stackoverflow_0006919596_function_python_radio_button_tkinter.txt |
Q:
How to import large number of global variables without listing each one? (Python)
DEFINE1 = 1
DEFINE2 = 2
DEFINE3 = 3
...
DEFINE10 = 10
Let's say one file has 10 global constants that I want to import into another file.
Instead of doing the following, is there any simpler way to import all the global constants wi... | How to import large number of global variables without listing each one? (Python) | DEFINE1 = 1
DEFINE2 = 2
DEFINE3 = 3
...
DEFINE10 = 10
Let's say one file has 10 global constants that I want to import into another file.
Instead of doing the following, is there any simpler way to import all the global constants without doing something like: from file_one.py import *. I don't want it to import the en... | [
"Assuming that all upper-case names are global constants:\nimport file_one\ng = globals()\nfor key in dir(file_one):\n if key.isupper():\n g[key] = getattr(file_one, key)\n\nOr shorter:\nimport file_one\nglobals().update((key, getattr(file_one, key)) for key in dir(file_one)\n ... | [
4,
4,
0,
0,
0
] | [] | [] | [
"import",
"python"
] | stackoverflow_0006928629_import_python.txt |
Q:
stopping a python thread using __del__
I have a threaded program in Python that works fine except that __del__ does not get called once the thread is running:
class tt(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.stop_event = threading.Event()
def __del__(sel... | stopping a python thread using __del__ | I have a threaded program in Python that works fine except that __del__ does not get called once the thread is running:
class tt(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.stop_event = threading.Event()
def __del__(self):
print "Deleting"
self.st... | [
"The __del__() method is executed when an instance is garbage collected, not when you call del on a name that happens to point to the instance. The latter will only delete the name (which might in some cases result in the instance pointed to by the name being gc'ed).\nA threading.Thread instance will never be garb... | [
8,
3
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0006928872_multithreading_python.txt |
Q:
Modules with Classes and Imports
If I were to use a class in a module how would I make it "top level" in it's instance?
Structure:
/package
__init__.py
/subPackage
__init__.py
module.py
subModule.py
/theScript.py
python theScript.py
Source of theScript:
import package.subPackag... | Modules with Classes and Imports | If I were to use a class in a module how would I make it "top level" in it's instance?
Structure:
/package
__init__.py
/subPackage
__init__.py
module.py
subModule.py
/theScript.py
python theScript.py
Source of theScript:
import package.subPackage.module
package.subPackage.module.met... | [
"Here is how the random module in the standard lib solved this problem:\n_inst = Random()\nseed = _inst.seed\nrandom = _inst.random\nuniform = _inst.uniform\ntriangular = _inst.triangular\n...\n\nSeems a reasonable solution to me. Of course there is the drawback that you have to manually keep the method lists in s... | [
6
] | [] | [] | [
"python",
"python_module"
] | stackoverflow_0006929056_python_python_module.txt |
Q:
clipping text in python/tkinter
I want to draw text on a tkinter canvas, within a previously drawn rectangle. I want to clip the text to be drawn entirely within the rectangle, hopefully by just specifying a maximum allowed width. Is there a straightforward way to do this in tkinter? If not, could I be using somet... | clipping text in python/tkinter | I want to draw text on a tkinter canvas, within a previously drawn rectangle. I want to clip the text to be drawn entirely within the rectangle, hopefully by just specifying a maximum allowed width. Is there a straightforward way to do this in tkinter? If not, could I be using something else that would make it easier? ... | [
"something along the lines of:\nfrom Tkinter import *\nroot = Tk()\nc = Canvas(root, width=200, height=200)\nc.pack()\nc.create_rectangle(50,50,91,67, outline='blue')\nt = Label(c, text=\"Hello John, Michael, Eric, ...\", anchor='w')\nc.create_window(51, 51, width=40, height=15, window=t, anchor='nw')\nroot.mainloo... | [
3,
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0001123463_python_tkinter.txt |
Q:
Issue with 'StringVar' in Python Program
I am trying to write a VERY simple UI in Python using Tkinter. I have run into a small problem with the StringVar class. The thing is, when I run the python script, I get an error on the line that initializes the StringVar variable. I have written a sample program with t... | Issue with 'StringVar' in Python Program | I am trying to write a VERY simple UI in Python using Tkinter. I have run into a small problem with the StringVar class. The thing is, when I run the python script, I get an error on the line that initializes the StringVar variable. I have written a sample program with this issue that I would like to get working:
fr... | [
"I think you might need to call Tk() explicitly before invoking StringVar. \nJust do this:\nfrom Tkinter import *\nTk() # Add this\nvar = StringVar()\nvar.set('test');\n\n",
"I've never done anything with Tkinter myself, but here it looks like this StringVar class inherits from a base Variable class, as you can s... | [
12,
1
] | [] | [] | [
"python",
"string",
"tkinter",
"user_interface",
"widget"
] | stackoverflow_0006928937_python_string_tkinter_user_interface_widget.txt |
Q:
Removing default file names in Django-Storages S3
I'm using django-storages with amazon S3, and uploading image files with:
models.ImageField(upload_to="img=%Y-%m-%d", max_length=256, blank=True, null=True)
When the files are uploaded to S3 however, it has the original file name attached at the end. How do I get ... | Removing default file names in Django-Storages S3 | I'm using django-storages with amazon S3, and uploading image files with:
models.ImageField(upload_to="img=%Y-%m-%d", max_length=256, blank=True, null=True)
When the files are uploaded to S3 however, it has the original file name attached at the end. How do I get rid of that and replace it, with say some random hash i... | [
"Supply a callable instead of a string to upload_to. The callable will be passed the instance being saved, and the filename, and will have to return the full path, including the filename -- so you can choose not to use the original filename. (You'll have to call strftime yourself with datetime.date.today(), however... | [
3
] | [] | [] | [
"django",
"django_storage",
"filefield",
"python"
] | stackoverflow_0006928737_django_django_storage_filefield_python.txt |
Q:
Shared object between requests in Django
I am using a Python module (PyCLIPS) and Django 1.3.
I want develop a thread-safety class which realizes the Object Pool and the Singleton patterns and also that have to be shared between requests in Django.
For example, I want to do the following:
A request gets the objec... | Shared object between requests in Django | I am using a Python module (PyCLIPS) and Django 1.3.
I want develop a thread-safety class which realizes the Object Pool and the Singleton patterns and also that have to be shared between requests in Django.
For example, I want to do the following:
A request gets the object with some ID from the pool, do
something wit... | [
"Well, I think a different angle is necessary here. Django is not like Java, the solution should be tailored for a multi-process environment, not a multi-threaded one.\nDjango has no immediate equivalent of a singleton session bean.\nThat said, I see no reason your description does not fit a classic database model.... | [
7,
2,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006927589_django_python.txt |
Q:
Adding a widget with a button - wxPython
I'm trying to create something like the categories panel in Wordpress, with wxPython.
What I'm trying to figure out, is how to add a widget when the user clicks a button (like "Add New Category")
Here is my code:
import wx
class MainWindow(wx.Frame):
def __init__(self,... | Adding a widget with a button - wxPython | I'm trying to create something like the categories panel in Wordpress, with wxPython.
What I'm trying to figure out, is how to add a widget when the user clicks a button (like "Add New Category")
Here is my code:
import wx
class MainWindow(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__... | [
"Call self.panel.Layout() after adding the button. This function is called automatically when you resize a window with children (try it with your current code), but not when you add widgets to it.\n"
] | [
0
] | [] | [] | [
"python",
"user_interface",
"wxpython"
] | stackoverflow_0006919318_python_user_interface_wxpython.txt |
Q:
Use variables from iPython in a script
I'd like to pass variables I've defined in iPython into a python script.
For example:
In [1]: import demo
In [2]: x = [1, 2, 3]
In [3]: y = [1, 2, 3]
In [4]: rtp x y
Where the script is:
import IPython.ipapi
ip = IPython.ipapi.get()
def run_this_plot(*args):
""" Run
... | Use variables from iPython in a script | I'd like to pass variables I've defined in iPython into a python script.
For example:
In [1]: import demo
In [2]: x = [1, 2, 3]
In [3]: y = [1, 2, 3]
In [4]: rtp x y
Where the script is:
import IPython.ipapi
ip = IPython.ipapi.get()
def run_this_plot(*args):
""" Run
Examples
In [1]: import demo
In [2]... | [
"You might find it useful to browse the source of the IPython.Magic module for clues. It would appear you can only get one string argument into a custom magic method. But I can't seem to find a doc reference to confirm. \nWhile I imagine there's a better way to accomplish this, the following should work for your sp... | [
1,
0
] | [] | [] | [
"ipython",
"python"
] | stackoverflow_0006928102_ipython_python.txt |
Q:
Upload data to BlobStore using remote api
Is it possible to upload blob to blobstore using remote API (not the standard upload scheme)?
I want to write backup/restore script for my application and blobstore is the only thing that doesn't work.
A:
Blobstore access over Remote API was added three days ago:
Remote... | Upload data to BlobStore using remote api | Is it possible to upload blob to blobstore using remote API (not the standard upload scheme)?
I want to write backup/restore script for my application and blobstore is the only thing that doesn't work.
| [
"Blobstore access over Remote API was added three days ago:\n\n\nRemote API now supports the Blobstore API. (Changelog)\n\n\n\n\nremote_api works at the lowest level\n of the datastore, so once you've set\n up the stub, you don't have to worry\n about the fact that you're operating\n on a remote datastore: With... | [
1,
1,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003530990_google_app_engine_python.txt |
Q:
from python, how to write an integer into a (hex) bytea field
issue is this: in (pl)python code, we've calculated an integer = 26663.
Can easily convert this to hex using hex(myint) = 0x6827
So far so good!
Now, how to write this value -into a concatenation of strings- into a PostgreSQL (v9) bytea field? The DB is... | from python, how to write an integer into a (hex) bytea field | issue is this: in (pl)python code, we've calculated an integer = 26663.
Can easily convert this to hex using hex(myint) = 0x6827
So far so good!
Now, how to write this value -into a concatenation of strings- into a PostgreSQL (v9) bytea field? The DB is UTF8-encoded, if this matters.
EG, neither of these examples will ... | [
"I'm not familiar with Postgres, but the hex(n) function returns a string representation of the numeric value of n in hexadecimal. The nicest way in my opinion to concatenate this with a string is to use format strings. For example:\nrv = plpy.execute(plan, [ ( 'foo %s bar' % hex(6827) ) ] )\n\nIf the string is rea... | [
2
] | [] | [] | [
"plpython",
"postgresql",
"python"
] | stackoverflow_0006929512_plpython_postgresql_python.txt |
Q:
python - obfuscating distributed text/image/sound files
In distributing my app, I'd like to prevent casual users from viewing my png files, playing my mp3s or reading/modifying the plain text files I use to load and store data. The text I guess could be binary pickled? What about the images/sounds? What do you do ... | python - obfuscating distributed text/image/sound files | In distributing my app, I'd like to prevent casual users from viewing my png files, playing my mp3s or reading/modifying the plain text files I use to load and store data. The text I guess could be binary pickled? What about the images/sounds? What do you do when distributing your app?
Assuming py2exe or py2app.
| [
"You could archive those files and at runtime unarchive, use, then delete them:\nHere is an article regarding Work with ZIP archives\nNot a very strong protection method, but it will discourage hobby hackers\n",
"You can use zip files, but they'll be visible while the program is running; you could extract them to... | [
0,
0
] | [] | [] | [
"obfuscation",
"python"
] | stackoverflow_0006674167_obfuscation_python.txt |
Q:
improve read spead simple db boto
I have a script that reads simpledb domains and writes them to s3. the performance is mediocre at best. Is there a way to increase the read speed?
import boto
import datetime
from xml.dom.minidom import Document
from boto.s3.key import Key
awsa = "myawsaccesskey"
awss = "myawsse... | improve read spead simple db boto | I have a script that reads simpledb domains and writes them to s3. the performance is mediocre at best. Is there a way to increase the read speed?
import boto
import datetime
from xml.dom.minidom import Document
from boto.s3.key import Key
awsa = "myawsaccesskey"
awss = "myawssecretkey"
conn = boto.connect_sdb(awsa,... | [
"Run 5 or 10 threads in parallel and have each copy one domain.\nThis is actually pretty simple if you use a queue for domains to copy and have the threads wait for elements in the queue.\nhttp://www.ibm.com/developerworks/aix/library/au-threadingpython/\n",
"I agree with the accepted answer but if you're just lo... | [
3,
0
] | [] | [] | [
"amazon_simpledb",
"boto",
"python"
] | stackoverflow_0006666809_amazon_simpledb_boto_python.txt |
Q:
Regex to join numbers when they have spaces between them
I'm trying to build a regex that joins numbers in a string when they have spaces between them, ex:
$string = "I want to go home 8890 7463 and then go to 58639 6312 the cinema"
The regex should output:
"I want to go home 88907463 and then go to 586396312 the... | Regex to join numbers when they have spaces between them | I'm trying to build a regex that joins numbers in a string when they have spaces between them, ex:
$string = "I want to go home 8890 7463 and then go to 58639 6312 the cinema"
The regex should output:
"I want to go home 88907463 and then go to 586396312 the cinema"
The regex can be either in python or php language.
T... | [
"Use a look-ahead to see if the next block is a set of numbers and remove the trailing space. That way, it works for any number of sets (which I suspected you might want):\n$string = \"I want to go home 8890 7463 41234 and then go to 58639 6312 the cinema\";\n\n$newstring = preg_replace(\"/\\b(\\d+)\\s+(?=\\d+\\b)... | [
10,
3
] | [] | [] | [
"php",
"preg_replace",
"python",
"regex",
"replace"
] | stackoverflow_0006929981_php_preg_replace_python_regex_replace.txt |
Q:
Accessing a CSV File outside python folder
So my files are the exact same size, with a row header and a column header. I need to add the values thare are in the rest of the cells besides the row and column header. This is the function I am using to do it:
def readStructured (filename):
# Open the file
fd ... | Accessing a CSV File outside python folder | So my files are the exact same size, with a row header and a column header. I need to add the values thare are in the rest of the cells besides the row and column header. This is the function I am using to do it:
def readStructured (filename):
# Open the file
fd = open (filename, 'rb')
# CSV reader
re... | [
"\nThe files are the exact same. I opened the files in their C location and used save as to save them into my python folder.\n\nIt sounds to me like this might be the source of some invisible conversion. Adding an end-of-file character, or removing a trailing newline or something like that. I wouldn't trust that t... | [
0
] | [] | [] | [
"csv",
"directory",
"file",
"forcing",
"python"
] | stackoverflow_0006929355_csv_directory_file_forcing_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.