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:
Pagination of Date-Based Generic Views in Django
I have a pretty simple question. I want to make some date-based generic views on a Django site, but I also want to paginate them. According to the documentation the object_list view has page and paginate_by arguments, but the archive_month view does not. What's the "right" way to do it?
A:
I created a template tag to do template-based pagination on collections passed to the templates that aren't already paginated. Copy the following code to an app/templatetags/pagify.py file.
from django.template import Library, Node, Variable
from django.core.paginator import Paginator
import settings
register = Library()
class PagifyNode(Node):
def __init__(self, items, page_size, varname):
self.items = Variable(items)
self.page_size = int(page_size)
self.varname = varname
def render(self, context):
pages = Paginator(self.items.resolve(context), self.page_size)
request = context['request']
page_num = int(request.GET.get('page', 1))
context[self.varname] = pages.page(page_num)
return ''
@register.tag
def pagify(parser, token):
"""
Usage:
{% pagify items by page_size as varname %}
"""
bits = token.contents.split()
if len(bits) != 6:
raise TemplateSyntaxError, 'pagify tag takes exactly 5 arguments'
if bits[2] != 'by':
raise TemplateSyntaxError, 'second argument to pagify tag must be "by"'
if bits[4] != 'as':
raise TemplateSyntaxError, 'fourth argument to pagify tag must be "as"'
return PagifyNode(bits[1], bits[3], bits[5])
To use it in the templates (assume we've passed in an un-paginated list called items):
{% load pagify %}
{% pagify items by 20 as page %}
{% for item in page %}
{{ item }}
{% endfor %}
The page_size argument (the 20) can be a variable as well. The tag automatically detects page=5 variables in the querystring. And if you ever need to get at the paginator that belong to the page (for a page count, for example), you can simply call:
{{ page.paginator.num_pages }}
A:
Date based generic views don't have pagination. It seems you can't add pagination via wrapping them as well since they return rendered result.
I would simply write my own view in this case. You can check out generic views' code as well, but most of it will probably be unneeded in your case.
Since your question is a valid one, and looking at the code; I wonder why they didn't decouple queryset generation as separate functions. You could just use them and render as you wish then.
A:
I was working on a problem similar to this yesterday, and I found the best solution for me personally was to use the object_list generic view for all date-based pages, but pass a filtered queryset, as follows:
import datetime, time
def post_archive_month(request, year, month, page=0, template_name='post_archive_month.html', **kwargs):
# Convert date to numeric format
date = datetime.date(*time.strptime('%s-%s' % (year, month), '%Y-%b')[:3])
return list_detail.object_list(
request,
queryset = Post.objects.filter(publish__year=date.year, publish__date.month).order_by('-publish',),
paginate_by = 5,
page = page,
template_name = template_name,
**kwargs)
Where the urls.py reads something like:
url(r'^blog/(?P<year>\d{4})/(?P<month>\w{3})/$',
view=path.to.generic_view,
name='archive_month'),
I found this the easiest way around the problem without resorting to hacking the other generic views or writing a custom view.
A:
There is also excellent django-pagination add-on, which is completely independent of underlying view.
A:
Django date-based generic views do not support pagination. There is an open ticket from 2006 on this. If you want, you can try out the code patches supplied to implement this feature. I am not sure why the patches have not been applied to the codebase yet.
| Pagination of Date-Based Generic Views in Django | I have a pretty simple question. I want to make some date-based generic views on a Django site, but I also want to paginate them. According to the documentation the object_list view has page and paginate_by arguments, but the archive_month view does not. What's the "right" way to do it?
| [
"I created a template tag to do template-based pagination on collections passed to the templates that aren't already paginated. Copy the following code to an app/templatetags/pagify.py file.\nfrom django.template import Library, Node, Variable\nfrom django.core.paginator import Paginator\nimport settings\n\nregister = Library()\n\nclass PagifyNode(Node):\n def __init__(self, items, page_size, varname):\n self.items = Variable(items)\n self.page_size = int(page_size)\n self.varname = varname\n\n def render(self, context):\n pages = Paginator(self.items.resolve(context), self.page_size)\n request = context['request']\n page_num = int(request.GET.get('page', 1))\n\n context[self.varname] = pages.page(page_num)\n return ''\n\n@register.tag\ndef pagify(parser, token):\n \"\"\"\n Usage:\n\n {% pagify items by page_size as varname %}\n \"\"\"\n\n bits = token.contents.split()\n if len(bits) != 6:\n raise TemplateSyntaxError, 'pagify tag takes exactly 5 arguments'\n if bits[2] != 'by':\n raise TemplateSyntaxError, 'second argument to pagify tag must be \"by\"'\n if bits[4] != 'as':\n raise TemplateSyntaxError, 'fourth argument to pagify tag must be \"as\"'\n return PagifyNode(bits[1], bits[3], bits[5])\n\nTo use it in the templates (assume we've passed in an un-paginated list called items):\n{% load pagify %}\n\n{% pagify items by 20 as page %}\n{% for item in page %}\n {{ item }}\n{% endfor %}\n\nThe page_size argument (the 20) can be a variable as well. The tag automatically detects page=5 variables in the querystring. And if you ever need to get at the paginator that belong to the page (for a page count, for example), you can simply call:\n{{ page.paginator.num_pages }}\n\n",
"Date based generic views don't have pagination. It seems you can't add pagination via wrapping them as well since they return rendered result.\nI would simply write my own view in this case. You can check out generic views' code as well, but most of it will probably be unneeded in your case.\nSince your question is a valid one, and looking at the code; I wonder why they didn't decouple queryset generation as separate functions. You could just use them and render as you wish then.\n",
"I was working on a problem similar to this yesterday, and I found the best solution for me personally was to use the object_list generic view for all date-based pages, but pass a filtered queryset, as follows:\nimport datetime, time\n\ndef post_archive_month(request, year, month, page=0, template_name='post_archive_month.html', **kwargs):\n # Convert date to numeric format\n date = datetime.date(*time.strptime('%s-%s' % (year, month), '%Y-%b')[:3])\n return list_detail.object_list(\n request,\n queryset = Post.objects.filter(publish__year=date.year, publish__date.month).order_by('-publish',),\n paginate_by = 5,\n page = page,\n template_name = template_name,\n **kwargs)\n\nWhere the urls.py reads something like:\nurl(r'^blog/(?P<year>\\d{4})/(?P<month>\\w{3})/$',\n view=path.to.generic_view,\n name='archive_month'),\n\nI found this the easiest way around the problem without resorting to hacking the other generic views or writing a custom view.\n",
"There is also excellent django-pagination add-on, which is completely independent of underlying view.\n",
"Django date-based generic views do not support pagination. There is an open ticket from 2006 on this. If you want, you can try out the code patches supplied to implement this feature. I am not sure why the patches have not been applied to the codebase yet.\n"
] | [
3,
2,
1,
1,
0
] | [] | [] | [
"django",
"pagination",
"python"
] | stackoverflow_0000669903_django_pagination_python.txt |
Q:
R or Python for file manipulation
I have 4 reasonably complex r scripts that are used to manipulate csv and xml files. These were created by another department where they work exclusively in r.
My understanding is that while r is very fast when dealing with data, it's not really optimised for file manipulation. Can I expect to get significant speed increases by converting these scripts to python? Or is this something of a waste of time?
A:
I write in both R and Python regularly. I find Python modules for writing, reading and parsing information easier to use, maintain and update. Little niceties like the way python lets you deal with lists of items over R's indexing make things much easier to read.
I highly doubt you will gain any significant speed-up by switching the language. If you are becoming the new "maintainer" of these scripts and you find Python easier to understand and extend, then I'd say go for it.
Computer time is cheap ... programmer time is expensive. If you have other things to do then I'd just limp along with what you've got until you have a free day to putz with them.
Hope that helps.
A:
Few weeks ago, I wrote a Python script to extract some rows from a large (280 MB) CSV file. More precisely, I wanted to extract all available information on companies in the dbpedia that have an ISIN field. Later I tried the same in R, but as hard as I tried, the R script took 10x more than the python script (10min vs 1min on my rather old laptop). Maybe this is due to my knowledge of R, in which case I would appreciate any hint on how to make the script faster. Here is the python code
from time import clock
clock()
infile = "infobox_de.csv"
outfile = "companies.csv"
reader = open(infile, "rb")
writer = open(outfile, "w")
oldthing = ""
isCompany = False
hasISIN = False
matches = 0
for line in reader:
row = line.strip().split("\t")
if len(row)>0: thing = row[0]
if len(row)>1: key = row[1]
if len(row)>2: value = row[2]
if (len(row)>0) and (oldthing != thing):
if isCompany and hasISIN:
matches += 1
for tup in buf:
writer.write(tup)
buf = []
isCompany = False
hasISIN = False
isCompany = isCompany or ((key.lower()=="wikipageusestemplate") and (value.lower()=="template:infobox_unternehmen"))
hasISIN = hasISIN or ((key.lower()=="isin") and (value!=""))
oldthing = thing
buf.append(line)
writer.close()
print "finished after ", clock(), " seconds; ", matches, " matches."
and here is the R script (I do not have the equivalent version anymore, but a very similar which returns a dataframe instead of writing a csv file and does not check for ISIN):
infile <- "infobox_de.csv"
maxLines=65000
reader <- file(infile, "r")
writer <- textConnection("queryRes", open = "w", local = TRUE)
writeLines("thing\tkey\tvalue\tetc\n", writer)
oldthing <- ""
hasInfobox <- FALSE
lineNumber <- 0
matches <- 0
key <- ""
thing <- ""
repeat {
lines <- readLines(reader, maxLines)
if (length(lines)==0) break
for (line in lines) {
lineNumber <- lineNumber + 1
row = unlist(strsplit(line, "\t"))
if (length(row)>0) thing <- row[1]
if (length(row)>1) key <- row[2]
if (length(row)>2) value <- row[3]
if ((length(row)>0) && (oldthing != thing)) {
if (hasInfobox) {
matches <- matches + 1
writeLines(buf, writer)
}
buf <- c()
hasInfobox <- FALSE
}
hasInfobox <- hasInfobox || ((tolower(key)=="wikipageusestemplate") && (tolower(value)==tolower("template:infobox_unternehmen")))
oldthing <- thing
buf <- c(buf, line)
}
}
close(reader)
close(writer)
readRes <- textConnection(queryRes, "r")
result <- read.csv(readRes, sep="\t", stringsAsFactors=FALSE)
close(readRes)
result
What I did explicitly, was to restrict readLines to 65000 lines maximum. I did this because I thought my 500MB RAM machine would be run out of memory otherwise. I did not try without this restriction.
A:
Know where the time is being spent. If your R scripts are bottlenecked on disk IO (and that is very possible in this case), then you could rewrite them in hand-optimized assembly and be no faster. As always with optimization, if you don't measure first, you're just pissing into the wind. If they're not bottlenecked on disk IO, you would likely see more benefit from improving the algorithm than changing the language.
A:
what do you mean by "file manipulation?" are you talking about moving files around, deleting, copying, etc., in which case i would use a shell, e.g., bash, etc. if you're talking about reading in the data, performing calculations, perhaps writing out a new file, etc., then you could probably use Python or R. unless maintenance is an issue, i would just leave it as R and find other fish to fry as you're not going to see enough of a speedup to justify your time and effort in porting that code.
A:
My guess is that you probably won't see much of a speed-up in time. When comparing high-level languages, overhead in the language is typically not to blame for performance problems. Typically, the problem is your algorithm.
I'm not very familiar with R, but you may find speed-ups by reading larger chunks of data into memory at once vs smaller chunks (less system calls). If R doesn't have the ability to change something like this, you will probably find that python can be much faster simply because of this ability.
A:
R data manipulation has rules for it to be fast. The basics are:
vectorize
use data.frames as little as possible (for example, in the end)
Search for R time optimization and profiling and you will find many resources to help you.
| R or Python for file manipulation | I have 4 reasonably complex r scripts that are used to manipulate csv and xml files. These were created by another department where they work exclusively in r.
My understanding is that while r is very fast when dealing with data, it's not really optimised for file manipulation. Can I expect to get significant speed increases by converting these scripts to python? Or is this something of a waste of time?
| [
"I write in both R and Python regularly. I find Python modules for writing, reading and parsing information easier to use, maintain and update. Little niceties like the way python lets you deal with lists of items over R's indexing make things much easier to read.\nI highly doubt you will gain any significant speed-up by switching the language. If you are becoming the new \"maintainer\" of these scripts and you find Python easier to understand and extend, then I'd say go for it.\nComputer time is cheap ... programmer time is expensive. If you have other things to do then I'd just limp along with what you've got until you have a free day to putz with them.\nHope that helps.\n",
"Few weeks ago, I wrote a Python script to extract some rows from a large (280 MB) CSV file. More precisely, I wanted to extract all available information on companies in the dbpedia that have an ISIN field. Later I tried the same in R, but as hard as I tried, the R script took 10x more than the python script (10min vs 1min on my rather old laptop). Maybe this is due to my knowledge of R, in which case I would appreciate any hint on how to make the script faster. Here is the python code\nfrom time import clock\n\nclock()\ninfile = \"infobox_de.csv\"\noutfile = \"companies.csv\"\n\nreader = open(infile, \"rb\")\nwriter = open(outfile, \"w\")\n\noldthing = \"\"\nisCompany = False\nhasISIN = False\nmatches = 0\n\nfor line in reader:\n row = line.strip().split(\"\\t\")\n if len(row)>0: thing = row[0]\n if len(row)>1: key = row[1]\n if len(row)>2: value = row[2]\n if (len(row)>0) and (oldthing != thing):\n if isCompany and hasISIN:\n matches += 1\n for tup in buf:\n writer.write(tup)\n buf = []\n isCompany = False\n hasISIN = False\n isCompany = isCompany or ((key.lower()==\"wikipageusestemplate\") and (value.lower()==\"template:infobox_unternehmen\"))\n hasISIN = hasISIN or ((key.lower()==\"isin\") and (value!=\"\"))\n oldthing = thing\n buf.append(line)\n\nwriter.close()\nprint \"finished after \", clock(), \" seconds; \", matches, \" matches.\"\n\nand here is the R script (I do not have the equivalent version anymore, but a very similar which returns a dataframe instead of writing a csv file and does not check for ISIN):\ninfile <- \"infobox_de.csv\"\nmaxLines=65000\n\nreader <- file(infile, \"r\")\nwriter <- textConnection(\"queryRes\", open = \"w\", local = TRUE)\nwriteLines(\"thing\\tkey\\tvalue\\tetc\\n\", writer)\n\noldthing <- \"\"\nhasInfobox <- FALSE\nlineNumber <- 0\nmatches <- 0\nkey <- \"\"\nthing <- \"\"\n\nrepeat {\n lines <- readLines(reader, maxLines)\n if (length(lines)==0) break\n for (line in lines) {\n lineNumber <- lineNumber + 1\n row = unlist(strsplit(line, \"\\t\"))\n if (length(row)>0) thing <- row[1]\n if (length(row)>1) key <- row[2]\n if (length(row)>2) value <- row[3]\n if ((length(row)>0) && (oldthing != thing)) {\n if (hasInfobox) {\n matches <- matches + 1\n writeLines(buf, writer)\n }\n buf <- c()\n hasInfobox <- FALSE\n }\n hasInfobox <- hasInfobox || ((tolower(key)==\"wikipageusestemplate\") && (tolower(value)==tolower(\"template:infobox_unternehmen\")))\n oldthing <- thing\n buf <- c(buf, line)\n }\n}\nclose(reader)\nclose(writer)\nreadRes <- textConnection(queryRes, \"r\")\nresult <- read.csv(readRes, sep=\"\\t\", stringsAsFactors=FALSE)\nclose(readRes)\nresult\n\nWhat I did explicitly, was to restrict readLines to 65000 lines maximum. I did this because I thought my 500MB RAM machine would be run out of memory otherwise. I did not try without this restriction.\n",
"Know where the time is being spent. If your R scripts are bottlenecked on disk IO (and that is very possible in this case), then you could rewrite them in hand-optimized assembly and be no faster. As always with optimization, if you don't measure first, you're just pissing into the wind. If they're not bottlenecked on disk IO, you would likely see more benefit from improving the algorithm than changing the language.\n",
"what do you mean by \"file manipulation?\" are you talking about moving files around, deleting, copying, etc., in which case i would use a shell, e.g., bash, etc. if you're talking about reading in the data, performing calculations, perhaps writing out a new file, etc., then you could probably use Python or R. unless maintenance is an issue, i would just leave it as R and find other fish to fry as you're not going to see enough of a speedup to justify your time and effort in porting that code.\n",
"My guess is that you probably won't see much of a speed-up in time. When comparing high-level languages, overhead in the language is typically not to blame for performance problems. Typically, the problem is your algorithm.\nI'm not very familiar with R, but you may find speed-ups by reading larger chunks of data into memory at once vs smaller chunks (less system calls). If R doesn't have the ability to change something like this, you will probably find that python can be much faster simply because of this ability.\n",
"R data manipulation has rules for it to be fast. The basics are: \n\nvectorize\nuse data.frames as little as possible (for example, in the end)\n\nSearch for R time optimization and profiling and you will find many resources to help you.\n"
] | [
11,
2,
1,
1,
0,
0
] | [] | [] | [
"file",
"performance",
"python",
"r"
] | stackoverflow_0002770030_file_performance_python_r.txt |
Q:
Python: Why do some packages get installed as eggs and some as "egg folders"?
I maintain a few Python packages. I have a very similar setup.py file for each of them. However, when doing setup.py install, one of my packages gets installed as an egg, while the others get installed as "egg folders", i.e. folders with an extension of "egg".
What is the difference between them that causes this different behavior?
A:
The Internal Structure of Python Eggs, Zip Support Metadata :
If zip-safe exists, it means that the project will work properly when installed as an .egg zipfile, and conversely the existence of not-zip-safe means the project should not be installed as an .egg file [ie. as an .egg directory]. The zip_safe option to setuptools' setup() determines which file will be written. If the option isn't provided, setuptools attempts to make its own assessment of whether the package can work, based on code and content analysis.
A:
A single egg file is in fact a zip archive with a particular directory structure inside. Per the zipimport documentation, only .py, .pyc, and .pyo files can be imported from zip files. So, if the package needs to import other kinds of module resources (like compiled c code; .so files, .pyd files) it won't work as a zip file.
I don't know if this is the only reason that some eggs won't work as zip archives, but I think it is the main reason.
| Python: Why do some packages get installed as eggs and some as "egg folders"? | I maintain a few Python packages. I have a very similar setup.py file for each of them. However, when doing setup.py install, one of my packages gets installed as an egg, while the others get installed as "egg folders", i.e. folders with an extension of "egg".
What is the difference between them that causes this different behavior?
| [
"The Internal Structure of Python Eggs, Zip Support Metadata :\n\nIf zip-safe exists, it means that the project will work properly when installed as an .egg zipfile, and conversely the existence of not-zip-safe means the project should not be installed as an .egg file [ie. as an .egg directory]. The zip_safe option to setuptools' setup() determines which file will be written. If the option isn't provided, setuptools attempts to make its own assessment of whether the package can work, based on code and content analysis.\n\n",
"A single egg file is in fact a zip archive with a particular directory structure inside. Per the zipimport documentation, only .py, .pyc, and .pyo files can be imported from zip files. So, if the package needs to import other kinds of module resources (like compiled c code; .so files, .pyd files) it won't work as a zip file.\nI don't know if this is the only reason that some eggs won't work as zip archives, but I think it is the main reason.\n"
] | [
28,
5
] | [] | [] | [
"egg",
"packaging",
"python",
"setuptools"
] | stackoverflow_0002798451_egg_packaging_python_setuptools.txt |
Q:
How do I pass a Python Variable to Bash?
How would I pass a Python variable to the Bash shell? It should work like this:
foo="./RetVar.py 42"
Replace the double-quotes with `s
I have tried printing and sys.exiting the result, but to no avail. How would I accomplish my goal?
A:
foo="$(scriptthatprintssomething)"
That's it. print. Or sys.stdout.write(). Or the like. If the script isn't executable then you'll need to specify the interpreter explicitly.
foo="$(python scriptthatprintssomething.py)"
A:
In bash both ``cmd\ and $(cmd) will be replaced by the output of the command. This allows you to assign the output of a program to a variable like
foo=`some command`
or
foo=$(some command)
Normally you wrap this in double quotes so you can have spaces in your output. It must be double quotes as stuff inside single quotes will not be executed.
A:
Your desired form works just fine:
$ cat >Retvar.py
#!/usr/bin/python
import sys
print sys.argv[1]
$ chmod +x RetVar.py
$ foo=`./RetVar.py 42`
$ echo $foo
42
$
so presumably the ways in which you had tried printing were incorrect. (This is quite independent from using the older-style backquotes, or newer-style constructs such as $()). If you still have this problem, can you show us the minimal example of Python code that reproduces it, to help us help you?
| How do I pass a Python Variable to Bash? | How would I pass a Python variable to the Bash shell? It should work like this:
foo="./RetVar.py 42"
Replace the double-quotes with `s
I have tried printing and sys.exiting the result, but to no avail. How would I accomplish my goal?
| [
"foo=\"$(scriptthatprintssomething)\"\n\nThat's it. print. Or sys.stdout.write(). Or the like. If the script isn't executable then you'll need to specify the interpreter explicitly.\nfoo=\"$(python scriptthatprintssomething.py)\"\n\n",
"In bash both ``cmd\\ and $(cmd) will be replaced by the output of the command. This allows you to assign the output of a program to a variable like \nfoo=`some command`\n\nor \nfoo=$(some command)\n\nNormally you wrap this in double quotes so you can have spaces in your output. It must be double quotes as stuff inside single quotes will not be executed. \n",
"Your desired form works just fine:\n$ cat >Retvar.py\n#!/usr/bin/python\nimport sys\nprint sys.argv[1]\n$ chmod +x RetVar.py \n$ foo=`./RetVar.py 42`\n$ echo $foo\n42\n$ \n\nso presumably the ways in which you had tried printing were incorrect. (This is quite independent from using the older-style backquotes, or newer-style constructs such as $()). If you still have this problem, can you show us the minimal example of Python code that reproduces it, to help us help you?\n"
] | [
9,
1,
0
] | [] | [] | [
"bash",
"linux",
"python",
"unix"
] | stackoverflow_0002796932_bash_linux_python_unix.txt |
Q:
Starting an http request, but dropping out if no response after a certain time
I'm trying to write a python script that does the following from within a minutely cronjob:
tries to execute a url
after 10 seconds if there is no response yet, abandon the response and immediately issue a command via os.system to restart the webserver.
The problem is that when my server crashes, it doesn't return a response at all. If I were to just have my script time the response, the script will go on for 10 minutes or more. I want it to issue the restart immediately once it detects a slow response. I know such a script could be written in probably less than 5 mines of code, but I have no idea how to go about it.
A:
From Python 2.6 on you can use the following, provide the timeout in seconds in the call to urlopen:
urllib2.urlopen(url[, data][, timeout])
This sets the timeout only for this request, not globally like with socket.settimeout. But for older versions of Python that is probably your only option.
A:
Use settimeout()
I believe this will throw an exception, so just do:
try:
//all the magic you want
except socket.timeout:
os.system(...)
A:
Here's a non-Python answer, suitable for a minute-ly cronjob:
curl > /dev/null --silent --max-time 10 http://myserver.com || sudo /usr/sbin/apache2ctl graceful
If the curl fetch takes more than ten seconds, it'll exit with an error. The bash "||" command will then fire, running the command to restart Apache gracefully. That is, it'll restart, but leave current connections running. You'll need to visudo to enable that command to run passwordless from cron.
| Starting an http request, but dropping out if no response after a certain time | I'm trying to write a python script that does the following from within a minutely cronjob:
tries to execute a url
after 10 seconds if there is no response yet, abandon the response and immediately issue a command via os.system to restart the webserver.
The problem is that when my server crashes, it doesn't return a response at all. If I were to just have my script time the response, the script will go on for 10 minutes or more. I want it to issue the restart immediately once it detects a slow response. I know such a script could be written in probably less than 5 mines of code, but I have no idea how to go about it.
| [
"From Python 2.6 on you can use the following, provide the timeout in seconds in the call to urlopen:\nurllib2.urlopen(url[, data][, timeout])\n\nThis sets the timeout only for this request, not globally like with socket.settimeout. But for older versions of Python that is probably your only option.\n",
"Use settimeout()\nI believe this will throw an exception, so just do:\ntry:\n //all the magic you want\nexcept socket.timeout:\n os.system(...)\n\n",
"Here's a non-Python answer, suitable for a minute-ly cronjob:\ncurl > /dev/null --silent --max-time 10 http://myserver.com || sudo /usr/sbin/apache2ctl graceful\n\nIf the curl fetch takes more than ten seconds, it'll exit with an error. The bash \"||\" command will then fire, running the command to restart Apache gracefully. That is, it'll restart, but leave current connections running. You'll need to visudo to enable that command to run passwordless from cron.\n"
] | [
3,
2,
2
] | [] | [] | [
"benchmarking",
"python"
] | stackoverflow_0002798264_benchmarking_python.txt |
Q:
How to enable i18n from within setup_app in websetup.py ? (formatted resend)
From within the setup_app function (websetup.py) of a pylons i18n application, which is making use of a db, I was trying to initiate multilingual content to be inserted into the db.
To do so the idea was something like:
#necessary imports here
def setup_app(command, conf, vars):
....
for lang in langs:
set_lang(lang)
content=model.Content()
content.content=_('content')
Session.add(content)
Session.commit()
Unfortunately it seems that it doesn't work. the set_lang code line is firing an exception as follows:
File ".. i18n/translation.py", line 179, in set_lang
translator = _get_translator(lang, **kwargs)
File ".. i18n/translation.py", line 160, in _get_translator
localedir = os.path.join(rootdir, 'i18n')
File ".. /posixpath.py", line 67, in join
elif path == '' or path.endswith('/'):
AttributeError: 'NoneType' object has no attribute 'endswith'
Actually I'm even not sure it could be possible launching i18n mechanisms from within this setup_app function without an active request object.
Anyone has tried some trick on a similar story ?
A:
Apologies, I'm not familiar with i18n together with Pylons...
That said, you need to track down what 'path' is, and what its relative to. The error is because path is expected to be a string, but instead is set to None... causing the exception because the code is attempting a string operation 'path.endswith()' but path is None.
| How to enable i18n from within setup_app in websetup.py ? (formatted resend) | From within the setup_app function (websetup.py) of a pylons i18n application, which is making use of a db, I was trying to initiate multilingual content to be inserted into the db.
To do so the idea was something like:
#necessary imports here
def setup_app(command, conf, vars):
....
for lang in langs:
set_lang(lang)
content=model.Content()
content.content=_('content')
Session.add(content)
Session.commit()
Unfortunately it seems that it doesn't work. the set_lang code line is firing an exception as follows:
File ".. i18n/translation.py", line 179, in set_lang
translator = _get_translator(lang, **kwargs)
File ".. i18n/translation.py", line 160, in _get_translator
localedir = os.path.join(rootdir, 'i18n')
File ".. /posixpath.py", line 67, in join
elif path == '' or path.endswith('/'):
AttributeError: 'NoneType' object has no attribute 'endswith'
Actually I'm even not sure it could be possible launching i18n mechanisms from within this setup_app function without an active request object.
Anyone has tried some trick on a similar story ?
| [
"Apologies, I'm not familiar with i18n together with Pylons... \nThat said, you need to track down what 'path' is, and what its relative to. The error is because path is expected to be a string, but instead is set to None... causing the exception because the code is attempting a string operation 'path.endswith()' but path is None.\n"
] | [
1
] | [] | [] | [
"internationalization",
"pylons",
"python"
] | stackoverflow_0002798517_internationalization_pylons_python.txt |
Q:
cd Terminal at a given directory after running a Python script?
I'm working on a simple Python script that can use subprocess and/or os to execute some commands, which is working fine.
However, when the script exits I'd like to cd the actual Terminal (in this case OS X) so on exit, the new files are ready to use in the directory where the have been created. All the following (subprocess.Popen, os.system, os.chdir) can do what I want from within the script (i.e. they execute stuff in the target directory) but on exit leave the Terminal at the script's own directory, not the target directory.
I'd like to avoid writing a shell script to temporary file just to achieve this, if this is at all possible anyway?
A:
Sadly, no. Processes are not allowed to change the environment of their parent process, and in this case your Python script is a child process of the shell. You could "fake" it by having your Python process set up a new shell - call subprocess to open a shell process and present it to the user, inheriting the modified environment from itself - but that has the downside of forcing the Python process to run continually.
This is really what shell scripts are for.. :-) Someone clearly needs to write a more traditional shell (e.g. closer to Bash than IPython) which can use python as its scripting language.
A:
Forgetting Python for the moment, no subprocess can change the state of its invoking shell. Thus you need a construct which alters the state of the calling shell which is what Paul Creasey was hinting at.
alias mycd="cd `echo $1`"
where echo could be replaced with script_which_outputs_a_directory_name_on_stdout.py It's kind of a hack, but at least it's an old hack.
A:
Have you tried simply running the program in the current shell?
i.e
$. script.py
instead of
$script.py
| cd Terminal at a given directory after running a Python script? | I'm working on a simple Python script that can use subprocess and/or os to execute some commands, which is working fine.
However, when the script exits I'd like to cd the actual Terminal (in this case OS X) so on exit, the new files are ready to use in the directory where the have been created. All the following (subprocess.Popen, os.system, os.chdir) can do what I want from within the script (i.e. they execute stuff in the target directory) but on exit leave the Terminal at the script's own directory, not the target directory.
I'd like to avoid writing a shell script to temporary file just to achieve this, if this is at all possible anyway?
| [
"Sadly, no. Processes are not allowed to change the environment of their parent process, and in this case your Python script is a child process of the shell. You could \"fake\" it by having your Python process set up a new shell - call subprocess to open a shell process and present it to the user, inheriting the modified environment from itself - but that has the downside of forcing the Python process to run continually.\nThis is really what shell scripts are for.. :-) Someone clearly needs to write a more traditional shell (e.g. closer to Bash than IPython) which can use python as its scripting language.\n",
"Forgetting Python for the moment, no subprocess can change the state of its invoking shell. Thus you need a construct which alters the state of the calling shell which is what Paul Creasey was hinting at.\nalias mycd=\"cd `echo $1`\"\n\nwhere echo could be replaced with script_which_outputs_a_directory_name_on_stdout.py It's kind of a hack, but at least it's an old hack.\n",
"Have you tried simply running the program in the current shell?\ni.e \n$. script.py\ninstead of\n$script.py\n"
] | [
10,
4,
1
] | [] | [] | [
"bash",
"directory",
"python",
"shell",
"terminal"
] | stackoverflow_0002799256_bash_directory_python_shell_terminal.txt |
Q:
Why does py2exe remove `help` and `license`?
I packaged my Python app with py2exe. My app is a wxPython GUI, in which there is an interactive Python shell.
I noticed that I can't do help(whatever) in the shell. I investigated a bit and discovered that after the py2exe process, 3 items were missing from __builtin__. These are help, license, and another one I haven't discovered.
Why is this happening and how can I stop it? I want the users of my program to be able to use the help function of Python.
A:
Reason: These are added by the site module. I believe that py2exe doesn't package that.
Fix: Either explicitly import site or reimplement help (trivial).
See also: http://docs.python.org/library/constants.html#constants-added-by-the-site-module
| Why does py2exe remove `help` and `license`? | I packaged my Python app with py2exe. My app is a wxPython GUI, in which there is an interactive Python shell.
I noticed that I can't do help(whatever) in the shell. I investigated a bit and discovered that after the py2exe process, 3 items were missing from __builtin__. These are help, license, and another one I haven't discovered.
Why is this happening and how can I stop it? I want the users of my program to be able to use the help function of Python.
| [
"Reason: These are added by the site module. I believe that py2exe doesn't package that.\nFix: Either explicitly import site or reimplement help (trivial).\nSee also: http://docs.python.org/library/constants.html#constants-added-by-the-site-module\n"
] | [
2
] | [] | [] | [
"packaging",
"py2exe",
"python"
] | stackoverflow_0002799473_packaging_py2exe_python.txt |
Q:
How can I dispatch Firefox or Google Chrome with Python?
How can I do this with Firefox or Google Chrome?
ie = win32com.client.Dispatch('InternetExplorer.Application')
ie.visible = 1
ie.navigate('http://google.com')
Is there a way to do it?
ps: I need to use the ReadyState with it... for example while (ie.ReadyState != 4):, or in other words, I need some command that wait until the page loads completely until do the next command, that's why I need the dispatch, that currently work very good with IE
A:
Firefox does not expose a COM object; this is not possible. (AFAIK)
You can use the webbrowser module to open a URL in the user's default browser.
A:
Have a look at the webbrowser module in the Python standard library.
| How can I dispatch Firefox or Google Chrome with Python? | How can I do this with Firefox or Google Chrome?
ie = win32com.client.Dispatch('InternetExplorer.Application')
ie.visible = 1
ie.navigate('http://google.com')
Is there a way to do it?
ps: I need to use the ReadyState with it... for example while (ie.ReadyState != 4):, or in other words, I need some command that wait until the page loads completely until do the next command, that's why I need the dispatch, that currently work very good with IE
| [
"Firefox does not expose a COM object; this is not possible. (AFAIK)\nYou can use the webbrowser module to open a URL in the user's default browser.\n",
"Have a look at the webbrowser module in the Python standard library.\n"
] | [
3,
1
] | [] | [] | [
"firefox",
"python",
"windows"
] | stackoverflow_0002799535_firefox_python_windows.txt |
Q:
Difference in regex between Python and Rubular?
In Rubular, I have created a regular expression:
(Prerequisite|Recommended): (\w|-| )*
It matches the bolded:
Recommended: good comfort level with computers and some of the arts.
Summer. 2 credits. Prerequisite:
pre-freshman standing or permission of
instructor. Credit may not be applied
toward engineering degree. S-U
grades only.
Here is a use of the regex in Python:
note_re = re.compile(r'(Prerequisite|Recommended): (\w|-| )*', re.IGNORECASE)
def prereqs_of_note(note):
match = note_re.match(note)
if not match:
return None
return match.group(0)
Unfortunately, the code returns None instead of a match:
>>> import prereqs
>>> result = prereqs.prereqs_of_note("Summer. 2 credits. Prerequisite: pre-fres
hman standing or permission of instructor. Credit may not be applied toward engi
neering degree. S-U grades only.")
>>> print result
None
What am I doing wrong here?
UPDATE: Do I need re.search() instead of re.match()?
A:
You want to use re.search() because it scans the string. You don't want re.match() because it tries to apply the pattern at the start of the string.
>>> import re
>>> s = """Summer. 2 credits. Prerequisite: pre-freshman standing or permission of instructor. Credit may not be applied toward engineering degree. S-U grades only."""
>>> note_re = re.compile(r'(Prerequisite|Recommended): ([\w -]*)', re.IGNORECASE)
>>> note_re.search(s).groups()
('Prerequisite', 'pre-freshman standing or permission of instructor')
Also, if you want to match past the first period following the word "instructor" you're going to have to add a literal '.' into your pattern:
>>> re.search(r'(Prerequisite|Recommended): ([\w -\.]*)', s, re.IGNORECASE).groups()
('Prerequisite', 'pre-freshman standing or permission of instructor. Credit may not be applied toward engineering degree. S-U grades only.')
I would suggest you make your pattern greedier and match on the rest of the line, unless that's not really what you want, although it seems like you do.
>>> re.search(r'(Prerequisite|Recommended): (.*)', s, re.IGNORECASE).groups()
('Prerequisite', 'pre-freshman standing or permission of instructor. Credit may not be applied toward engineering degree. S-U grades only.')
The previous pattern with the addition of literal '.', returns the same as .* for this example.
| Difference in regex between Python and Rubular? | In Rubular, I have created a regular expression:
(Prerequisite|Recommended): (\w|-| )*
It matches the bolded:
Recommended: good comfort level with computers and some of the arts.
Summer. 2 credits. Prerequisite:
pre-freshman standing or permission of
instructor. Credit may not be applied
toward engineering degree. S-U
grades only.
Here is a use of the regex in Python:
note_re = re.compile(r'(Prerequisite|Recommended): (\w|-| )*', re.IGNORECASE)
def prereqs_of_note(note):
match = note_re.match(note)
if not match:
return None
return match.group(0)
Unfortunately, the code returns None instead of a match:
>>> import prereqs
>>> result = prereqs.prereqs_of_note("Summer. 2 credits. Prerequisite: pre-fres
hman standing or permission of instructor. Credit may not be applied toward engi
neering degree. S-U grades only.")
>>> print result
None
What am I doing wrong here?
UPDATE: Do I need re.search() instead of re.match()?
| [
"You want to use re.search() because it scans the string. You don't want re.match() because it tries to apply the pattern at the start of the string.\n>>> import re\n>>> s = \"\"\"Summer. 2 credits. Prerequisite: pre-freshman standing or permission of instructor. Credit may not be applied toward engineering degree. S-U grades only.\"\"\"\n>>> note_re = re.compile(r'(Prerequisite|Recommended): ([\\w -]*)', re.IGNORECASE)\n>>> note_re.search(s).groups()\n('Prerequisite', 'pre-freshman standing or permission of instructor')\n\nAlso, if you want to match past the first period following the word \"instructor\" you're going to have to add a literal '.' into your pattern:\n>>> re.search(r'(Prerequisite|Recommended): ([\\w -\\.]*)', s, re.IGNORECASE).groups()\n('Prerequisite', 'pre-freshman standing or permission of instructor. Credit may not be applied toward engineering degree. S-U grades only.')\n\nI would suggest you make your pattern greedier and match on the rest of the line, unless that's not really what you want, although it seems like you do. \n>>> re.search(r'(Prerequisite|Recommended): (.*)', s, re.IGNORECASE).groups()\n('Prerequisite', 'pre-freshman standing or permission of instructor. Credit may not be applied toward engineering degree. S-U grades only.')\n\nThe previous pattern with the addition of literal '.', returns the same as .* for this example.\n"
] | [
2
] | [] | [] | [
"python",
"regex",
"rubular"
] | stackoverflow_0002799418_python_regex_rubular.txt |
Q:
Django admin page dropdowns
I am building a high school team application using Django.
Here is my working models file:
class Directory(models.Model):
school = models.CharField(max_length=60)
website = models.URLField()
district = models.SmallIntegerField()
conference = models.ForeignKey(Conference)
class Conference(models.Model):
conference_name = models.CharField(max_length=50)
url = models.URLField()
class Meta:
ordering = ['conference_name']
When I open my admin pages and go to edit a school's conference the drop down looks like this:
<select>
<option value="1">Conference Object</option>
<option value="2">Conference Object</option>
<select>
How do I replace "Conference Object" with the conference_name?
A:
Try this:
class Conference(models.Model):
conference_name = models.CharField(max_length=50)
url = models.URLField()
def __unicode__(self):
return self.conference_name
class Meta:
ordering = ['conference_name']
This will say to the framework how to convert Conference instances to unicode strings.
| Django admin page dropdowns | I am building a high school team application using Django.
Here is my working models file:
class Directory(models.Model):
school = models.CharField(max_length=60)
website = models.URLField()
district = models.SmallIntegerField()
conference = models.ForeignKey(Conference)
class Conference(models.Model):
conference_name = models.CharField(max_length=50)
url = models.URLField()
class Meta:
ordering = ['conference_name']
When I open my admin pages and go to edit a school's conference the drop down looks like this:
<select>
<option value="1">Conference Object</option>
<option value="2">Conference Object</option>
<select>
How do I replace "Conference Object" with the conference_name?
| [
"Try this:\nclass Conference(models.Model):\n conference_name = models.CharField(max_length=50)\n url = models.URLField()\n\n def __unicode__(self):\n return self.conference_name\n\n class Meta:\n ordering = ['conference_name']\n\nThis will say to the framework how to convert Conference instances to unicode strings.\n"
] | [
0
] | [] | [] | [
"admin",
"django",
"drop_down_menu",
"python"
] | stackoverflow_0002799553_admin_django_drop_down_menu_python.txt |
Q:
Named semaphores in Python?
I have a script in python which uses a resource which can not be used by more than a certain amount of concurrent scripts running.
Classically, this would be solved by a named semaphores but I can not find those in the documentation of the multiprocessing module or threading .
Am I missing something or are named semaphores not implemented / exposed by Python? and more importantly, if the answer is no, what is the best way to emulate one?
Thanks,
Boaz
PS. For reasons which are not so relevant to this question, I can not aggregate the task to a continuously running process/daemon or work with spawned processes - both of which, it seems, would have worked with the python API.
A:
I suggest a third party extension like these, ideally the posix_ipc one -- see in particular the sempahore section in the docs.
These modules are mostly about exposing the "system V IPC" (including semaphores) in a unixy way, but at least one of them (posix_ipc specifically) is claimed to work with Cygwin on Windows (I haven't verified that claim). There are some documented limitations on FreeBSD 7.2 and Mac OSX 10.5, so take care if those platforms are important to you.
A:
You can emulate them by using the filesystem instead of a kernel path (named semaphores are implemented this way on some platforms anyhow). You'll have to implement sem_[open|wait|post|unlink] yourself, but it ought to be relatively trivial to do so. Your synchronization overhead might be significant (depending on how often you have to fiddle with the semaphore in your app), so you might want to initialize a ramdisk when you launch your process in which to store named semaphores.
Alternatively if you're not comfortable rolling your own, you could probably wrap boost::interprocess::named_semaphore (docs here) in a simple extension module.
| Named semaphores in Python? | I have a script in python which uses a resource which can not be used by more than a certain amount of concurrent scripts running.
Classically, this would be solved by a named semaphores but I can not find those in the documentation of the multiprocessing module or threading .
Am I missing something or are named semaphores not implemented / exposed by Python? and more importantly, if the answer is no, what is the best way to emulate one?
Thanks,
Boaz
PS. For reasons which are not so relevant to this question, I can not aggregate the task to a continuously running process/daemon or work with spawned processes - both of which, it seems, would have worked with the python API.
| [
"I suggest a third party extension like these, ideally the posix_ipc one -- see in particular the sempahore section in the docs.\nThese modules are mostly about exposing the \"system V IPC\" (including semaphores) in a unixy way, but at least one of them (posix_ipc specifically) is claimed to work with Cygwin on Windows (I haven't verified that claim). There are some documented limitations on FreeBSD 7.2 and Mac OSX 10.5, so take care if those platforms are important to you.\n",
"You can emulate them by using the filesystem instead of a kernel path (named semaphores are implemented this way on some platforms anyhow). You'll have to implement sem_[open|wait|post|unlink] yourself, but it ought to be relatively trivial to do so. Your synchronization overhead might be significant (depending on how often you have to fiddle with the semaphore in your app), so you might want to initialize a ramdisk when you launch your process in which to store named semaphores.\nAlternatively if you're not comfortable rolling your own, you could probably wrap boost::interprocess::named_semaphore (docs here) in a simple extension module.\n"
] | [
4,
0
] | [] | [] | [
"cross_process",
"multithreading",
"python",
"semaphore"
] | stackoverflow_0002798727_cross_process_multithreading_python_semaphore.txt |
Q:
Google Appengine: Java or Python
Possible Duplicate:
Choosing Java vs Python on Google App Engine
We are going to use Google Appengine platform for our next big web project.But we are not sure which flavour to use: Java or Python.
Could you please, advise on cons and pros of each approach? Which is the best way in order to build more scalable and efficient solution quicker.
Thanks in advance
A:
I gave the accepted answer to the question a comment claims is "very similar" -- but that was nearly a year ago. I'm still biased the same way (still expert on Python, rusty in Java), but in the intervening year I would say the Java runtime has just about caught up to the Python one -- or, if not quite that yet, it has made serious strides (as have both runtimes "in parallel", of course;-). Most of my general considerations in that answer remain roughly valid.
So the main consideration today is, I think, how familiar is the team with Python, and how familiar with Java -- if very familiar with one and not at all with the other, go with what you already know, as the time needed to "catch up" on the other is a cost that's probably larger than the advantages you could get one way or another (to a hobbyist wanting a "mind expanding" experience I'd recommend the reverse: take the opportunity to learn what you don't yet know -- but in terms of immediate productivity, staying with what you know increases it;-).
If there's some "killer library" that you've ascertained runs well with one of the runtimes and that you're really keen to use in your apps, that could be the decisive factor, if differences of familiarity with the two languages are not decisive in your case.
A:
It would be helpful to know what type of things this project needs to do, do you need to integrate with lots of other libraries, applications, etc?
This is just one anecdote, but I've recently tried out GAE on both platforms, and found the Python option way easier to get working than using Java with JDO. A part of this had to do with also tackling JDO at the same time, but I found I was able to implement the same exact functionality in Python in just a few days as I was in weeks on the Java side.
As someone relatively new to Python still, there are a lot of things I still need to tackle to feel more comfortable in it, such as:
the best way to unit test my controllers and model classes
best way to structure my controllers
determine if Django templates are satisfactory or if I should attempt to use a different template system
When I attempted the best way to write Java unit tests for my GAE classes I bounced between a half-dozen different blog articles and suggestions on how to best mock out the App Engine services. Some seemed to work, some seemed like hacks, but the lack of a good and supported solution left me feeling uncomfortable.
All things being equal, I would recommend the Python flavor for a greenfield project. Easier to get started, less moving pieces, no nasty JVM startup times in the production environment, no post-compile bytecode enhancement necessary, etc.
| Google Appengine: Java or Python |
Possible Duplicate:
Choosing Java vs Python on Google App Engine
We are going to use Google Appengine platform for our next big web project.But we are not sure which flavour to use: Java or Python.
Could you please, advise on cons and pros of each approach? Which is the best way in order to build more scalable and efficient solution quicker.
Thanks in advance
| [
"I gave the accepted answer to the question a comment claims is \"very similar\" -- but that was nearly a year ago. I'm still biased the same way (still expert on Python, rusty in Java), but in the intervening year I would say the Java runtime has just about caught up to the Python one -- or, if not quite that yet, it has made serious strides (as have both runtimes \"in parallel\", of course;-). Most of my general considerations in that answer remain roughly valid.\nSo the main consideration today is, I think, how familiar is the team with Python, and how familiar with Java -- if very familiar with one and not at all with the other, go with what you already know, as the time needed to \"catch up\" on the other is a cost that's probably larger than the advantages you could get one way or another (to a hobbyist wanting a \"mind expanding\" experience I'd recommend the reverse: take the opportunity to learn what you don't yet know -- but in terms of immediate productivity, staying with what you know increases it;-).\nIf there's some \"killer library\" that you've ascertained runs well with one of the runtimes and that you're really keen to use in your apps, that could be the decisive factor, if differences of familiarity with the two languages are not decisive in your case.\n",
"It would be helpful to know what type of things this project needs to do, do you need to integrate with lots of other libraries, applications, etc?\nThis is just one anecdote, but I've recently tried out GAE on both platforms, and found the Python option way easier to get working than using Java with JDO. A part of this had to do with also tackling JDO at the same time, but I found I was able to implement the same exact functionality in Python in just a few days as I was in weeks on the Java side.\nAs someone relatively new to Python still, there are a lot of things I still need to tackle to feel more comfortable in it, such as:\n\nthe best way to unit test my controllers and model classes\nbest way to structure my controllers\ndetermine if Django templates are satisfactory or if I should attempt to use a different template system\n\nWhen I attempted the best way to write Java unit tests for my GAE classes I bounced between a half-dozen different blog articles and suggestions on how to best mock out the App Engine services. Some seemed to work, some seemed like hacks, but the lack of a good and supported solution left me feeling uncomfortable.\nAll things being equal, I would recommend the Python flavor for a greenfield project. Easier to get started, less moving pieces, no nasty JVM startup times in the production environment, no post-compile bytecode enhancement necessary, etc.\n"
] | [
11,
5
] | [] | [] | [
"google_app_engine",
"java",
"python"
] | stackoverflow_0002799811_google_app_engine_java_python.txt |
Q:
Putting a thread to sleep until event X occurs
I'm writing to many files in a threaded app and I'm creating one handler per file. I have HandlerFactory class that manages the distribution of these handlers. What I'd like to do is that
thread A requests and gets foo.txt's file handle from the HandlerFactory class
thread B requests foo.txt's file handler
handler class recognizes that this file handle has been checked out
handler class puts thread A to sleep
thread B closes file handle using a wrapper method from HandlerFactory
HandlerFactory notifies sleeping threads
thread B wakes and successfully gets foo.txt's file handle
This is what I have so far,
def get_handler(self, file_path, type):
self.lock.acquire()
if file_path not in self.handlers:
self.handlers[file_path] = open(file_path, type)
elif not self.handlers[file_path].closed:
time.sleep(1)
self.lock.release()
return self.handlers[file_path][type]
I believe this covers the sleeping and handler retrieval successfully, but I am unsure how to wake up all threads, or even better wake up a specific thread.
A:
What you're looking for is known as a condition variable.
Condition Variables
Here is the Python 2 library reference.
For Python 3 it can be found here
A:
Looks like you want a threading.Semaphore associated with each handler (other synchronization objects like Events and Conditions are also possible, but a Semaphore seems simplest for your needs). (Specifically, use a BoundedSemaphore: for your use case, that will raise an exception immediately for programming errors that erroneously release the semaphone more times than they acquire it -- and that's exactly the reason for being of the bounded version of semaphones;-).
Initialize each semaphore to a value of 1 when you build it (so that means the handler is available). Each using-thread calls acquire on the semaphore to get the handler (that may block it), and release on it when it's done with the handler (that will unblock exactly one of the waiting threads). That's simpler than the acquire/wait/notify/release lifecycle of a Condition, and more future-proof too, since as the docs for Condition say:
The current implementation wakes up
exactly one thread, if any are
waiting. However, it’s not safe to
rely on this behavior. A future,
optimized implementation may
occasionally wake up more than one
thread.
while with a Semaphore you're playing it safe (the semantics whereof are safe to rely on: if a semaphore is initialized to N, there are at all times between 0 and N-1 [[included]] threads that have successfully acquired the semaphore and not yet released it).
A:
You do realize that Python has a giant lock, so that most of the benefits of multi-threading you do not get, right?
Unless there is some reason for the master thread to do something with the results of each worker, you may wish to consider just forking off another process for each request. You won't have to deal with locking issues then. Have the children do what they need to do, then die. If they do need to communicate back, do it over a pipe, with XMLRPC, or through a sqlite database (which is threadsafe).
| Putting a thread to sleep until event X occurs | I'm writing to many files in a threaded app and I'm creating one handler per file. I have HandlerFactory class that manages the distribution of these handlers. What I'd like to do is that
thread A requests and gets foo.txt's file handle from the HandlerFactory class
thread B requests foo.txt's file handler
handler class recognizes that this file handle has been checked out
handler class puts thread A to sleep
thread B closes file handle using a wrapper method from HandlerFactory
HandlerFactory notifies sleeping threads
thread B wakes and successfully gets foo.txt's file handle
This is what I have so far,
def get_handler(self, file_path, type):
self.lock.acquire()
if file_path not in self.handlers:
self.handlers[file_path] = open(file_path, type)
elif not self.handlers[file_path].closed:
time.sleep(1)
self.lock.release()
return self.handlers[file_path][type]
I believe this covers the sleeping and handler retrieval successfully, but I am unsure how to wake up all threads, or even better wake up a specific thread.
| [
"What you're looking for is known as a condition variable.\nCondition Variables\nHere is the Python 2 library reference.\nFor Python 3 it can be found here\n",
"Looks like you want a threading.Semaphore associated with each handler (other synchronization objects like Events and Conditions are also possible, but a Semaphore seems simplest for your needs). (Specifically, use a BoundedSemaphore: for your use case, that will raise an exception immediately for programming errors that erroneously release the semaphone more times than they acquire it -- and that's exactly the reason for being of the bounded version of semaphones;-).\nInitialize each semaphore to a value of 1 when you build it (so that means the handler is available). Each using-thread calls acquire on the semaphore to get the handler (that may block it), and release on it when it's done with the handler (that will unblock exactly one of the waiting threads). That's simpler than the acquire/wait/notify/release lifecycle of a Condition, and more future-proof too, since as the docs for Condition say:\n\nThe current implementation wakes up\n exactly one thread, if any are\n waiting. However, it’s not safe to\n rely on this behavior. A future,\n optimized implementation may\n occasionally wake up more than one\n thread.\n\nwhile with a Semaphore you're playing it safe (the semantics whereof are safe to rely on: if a semaphore is initialized to N, there are at all times between 0 and N-1 [[included]] threads that have successfully acquired the semaphore and not yet released it).\n",
"You do realize that Python has a giant lock, so that most of the benefits of multi-threading you do not get, right?\nUnless there is some reason for the master thread to do something with the results of each worker, you may wish to consider just forking off another process for each request. You won't have to deal with locking issues then. Have the children do what they need to do, then die. If they do need to communicate back, do it over a pipe, with XMLRPC, or through a sqlite database (which is threadsafe).\n"
] | [
6,
2,
0
] | [] | [] | [
"concurrency",
"locking",
"multithreading",
"python"
] | stackoverflow_0002800069_concurrency_locking_multithreading_python.txt |
Q:
In python, changing MySQL query based on function variables
I'd like to be able to add a restriction to the query if user_id != None ... for example:
"AND user_id = 5"
but I am not sure how to add this into the below function?
Thank you.
def get(id, user_id=None):
query = """SELECT *
FROM USERS
WHERE text LIKE %s AND
id = %s
"""
values = (search_text, id)
results = DB.get(query, values)
This way I can call:
get(5)
get(5,103524234) (contains user_id restriction)
A:
def get(id, user_id=None):
query = """SELECT *
FROM USERS
WHERE text LIKE %s AND
id = %s
"""
values = [search_text, id]
if user_id is not None:
query += ' AND user_id = %s'
values.append(user_id)
results = DB.get(query, values)
As you see, the main difference wrt your original code is the small if block in the middle, which enriches query string and values if needed. I also made values a list, rather than a tuple, so it can be enriched with the more natural append rather than with
values += (user_id,)
which is arguably less readable - however, you can use it if you want to keep values a tuple for some other reasons.
edit: the OP now clarifies in a comment (!) that his original query has an ending LIMIT clause. In this case I would suggest a different approach, such as:
query_pieces = ["""SELECT *
FROM USERS
WHERE text LIKE %s AND
id = %s
""", "LIMIT 5"]
values = [search_text, id]
if user_id is not None:
query_pieces.insert(1, ' AND user_id = %s')
values.append(user_id)
query = ' '.join(query_pieces)
results = DB.get(query, values)
You could do it in other ways, but keeping a list of query pieces in the proper order, enriching it as you go (e.g. by insert), and joining it with some whitespace at the end, is a pretty general and usable approach.
A:
What's wrong with something like:
def get(id, user_id=None):
query = "SELECT * FROM USERS WHERE text LIKE %s"
if user_id != None:
query = query + " AND id = %s"%(user_id)
:
:
That syntax may not be perfect, I haven't done Python for a while - I'm just trying to get the basic idea across. This defaults to the None case and only adds the extra restriction if you give a real user ID.
A:
You could build the SQL query using a list of conditions:
def get(id, user_id=None):
query = """SELECT *
FROM USERS
WHERE
"""
values = [search_text, id]
conditions=[
'text LIKE %s',
'id = %s']
if user_id is not None:
conditions.append('user_id = %s')
values.append(user_id)
query+=' AND '.join(conditions)+' LIMIT 1'
results = DB.get(query, values)
| In python, changing MySQL query based on function variables | I'd like to be able to add a restriction to the query if user_id != None ... for example:
"AND user_id = 5"
but I am not sure how to add this into the below function?
Thank you.
def get(id, user_id=None):
query = """SELECT *
FROM USERS
WHERE text LIKE %s AND
id = %s
"""
values = (search_text, id)
results = DB.get(query, values)
This way I can call:
get(5)
get(5,103524234) (contains user_id restriction)
| [
"def get(id, user_id=None):\n\n query = \"\"\"SELECT *\n FROM USERS\n WHERE text LIKE %s AND\n id = %s\n \"\"\"\n values = [search_text, id]\n\n if user_id is not None:\n query += ' AND user_id = %s'\n values.append(user_id)\n\n results = DB.get(query, values)\n\nAs you see, the main difference wrt your original code is the small if block in the middle, which enriches query string and values if needed. I also made values a list, rather than a tuple, so it can be enriched with the more natural append rather than with\n values += (user_id,)\n\nwhich is arguably less readable - however, you can use it if you want to keep values a tuple for some other reasons.\nedit: the OP now clarifies in a comment (!) that his original query has an ending LIMIT clause. In this case I would suggest a different approach, such as:\n query_pieces = [\"\"\"SELECT *\n FROM USERS\n WHERE text LIKE %s AND\n id = %s\n \"\"\", \"LIMIT 5\"]\n values = [search_text, id]\n\n if user_id is not None:\n query_pieces.insert(1, ' AND user_id = %s')\n values.append(user_id)\n\n query = ' '.join(query_pieces)\n results = DB.get(query, values)\n\nYou could do it in other ways, but keeping a list of query pieces in the proper order, enriching it as you go (e.g. by insert), and joining it with some whitespace at the end, is a pretty general and usable approach.\n",
"What's wrong with something like:\ndef get(id, user_id=None):\n query = \"SELECT * FROM USERS WHERE text LIKE %s\"\n if user_id != None:\n query = query + \" AND id = %s\"%(user_id)\n :\n :\n\nThat syntax may not be perfect, I haven't done Python for a while - I'm just trying to get the basic idea across. This defaults to the None case and only adds the extra restriction if you give a real user ID.\n",
"You could build the SQL query using a list of conditions:\ndef get(id, user_id=None):\n query = \"\"\"SELECT *\n FROM USERS\n WHERE \n \"\"\"\n values = [search_text, id]\n conditions=[\n 'text LIKE %s',\n 'id = %s']\n if user_id is not None:\n conditions.append('user_id = %s')\n values.append(user_id)\n query+=' AND '.join(conditions)+' LIMIT 1'\n results = DB.get(query, values)\n\n"
] | [
4,
2,
1
] | [] | [] | [
"function",
"mysql",
"python"
] | stackoverflow_0002800085_function_mysql_python.txt |
Q:
How can I do such a typical unittest?
This is a simple structure in my project:
MyAPP---
note---
__init__.py
views.py
urls.py
test.py
models.py
auth--
...
template---
auth---
login.html
register.html
note---
noteshow.html
media---
css---
...
js---
...
settings.py
urls.py
__init__.py
manage.py
I want to make a unittest which can test the noteshow page working propeyly or not.
The code:
from django.test import TestCase
class Note(TestCase):
def test_noteshow(self):
response = self.client.get('/note/')
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, '/note/noteshow.html')
The problem is that my project include an auth mod, it will force the unlogin user redirecting into the login.html page when they visit the noteshow.html.
So, when I run my unittest, in the bash it raise an failure that the response.status_code is always 302 instead of 200.
All right though through this result I can check the auth mod is running well, it is not like what I want it to be.
OK, the question is that how can I make another unittest to check my noteshow.template is used or not?
Thanks for all.
django version: 1.1.1
python version: 2.6.4
Use Eclipse for MAC OS
A:
Just login a user for each test. The best way to do this is to use a setUp() method that creates a client, creates a user, and then logs user in. Also use a tearDown() method that does the reverse (logs out user and deletes user).
The methods setUp() and tearDown() are run automatically for each test in the set of tests.
It would look something like this:
class Note(TestCase):
def setUp(self):
self.client = Client()
self.new_user = User.objects.create_user('blah', 'blah@blah.com', 'blah')
self.new_user.save()
self.client.login(username='blah', password='blah')
def tearDown(self):
self.client.logout()
self.new_user.delete()
def test_noteshow(self):
response = self.client.get('/note/')
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, '/note/noteshow.html')
| How can I do such a typical unittest? | This is a simple structure in my project:
MyAPP---
note---
__init__.py
views.py
urls.py
test.py
models.py
auth--
...
template---
auth---
login.html
register.html
note---
noteshow.html
media---
css---
...
js---
...
settings.py
urls.py
__init__.py
manage.py
I want to make a unittest which can test the noteshow page working propeyly or not.
The code:
from django.test import TestCase
class Note(TestCase):
def test_noteshow(self):
response = self.client.get('/note/')
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, '/note/noteshow.html')
The problem is that my project include an auth mod, it will force the unlogin user redirecting into the login.html page when they visit the noteshow.html.
So, when I run my unittest, in the bash it raise an failure that the response.status_code is always 302 instead of 200.
All right though through this result I can check the auth mod is running well, it is not like what I want it to be.
OK, the question is that how can I make another unittest to check my noteshow.template is used or not?
Thanks for all.
django version: 1.1.1
python version: 2.6.4
Use Eclipse for MAC OS
| [
"Just login a user for each test. The best way to do this is to use a setUp() method that creates a client, creates a user, and then logs user in. Also use a tearDown() method that does the reverse (logs out user and deletes user).\nThe methods setUp() and tearDown() are run automatically for each test in the set of tests.\nIt would look something like this:\nclass Note(TestCase):\n def setUp(self):\n self.client = Client()\n self.new_user = User.objects.create_user('blah', 'blah@blah.com', 'blah')\n self.new_user.save()\n self.client.login(username='blah', password='blah')\n\n def tearDown(self):\n self.client.logout()\n self.new_user.delete()\n \n def test_noteshow(self):\n response = self.client.get('/note/')\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, '/note/noteshow.html')\n\n"
] | [
6
] | [] | [] | [
"django",
"python",
"testcase"
] | stackoverflow_0002800179_django_python_testcase.txt |
Q:
use/run python's 2to3 as or like a unittest
I have used the 2to3 utility to convert code from the command line. What I would like to do is run it basically as a unittest. Even if it tests the file rather than parts(functions, methods...) as would be normal for a unittest.
It does not need to be a unittest and I don't what to automatically convert the files I just want to monitor the py3 compliance of files in a unittest like manor. I can't seem to find any documentation or examples for this.
An example and/or documentation would be great.
A:
Simply use the -3 option with python2.6+ to be informed of Python3 compliance.
A:
If you are trying to verify the code will work in Python 3.x, I would suggest a script that copies the source files to a new directory, runs 2to3 on them, then copies the unit tests to the directory and runs them.
This may seem slightly inelegant, but is consistent with the spirit of unit testing. You are making a series of assertions that you believe ought to be true about the external behavior of the code, regardless of implementation. If the converted code passes your unit tests, you can consider your code to support Python 3.
| use/run python's 2to3 as or like a unittest | I have used the 2to3 utility to convert code from the command line. What I would like to do is run it basically as a unittest. Even if it tests the file rather than parts(functions, methods...) as would be normal for a unittest.
It does not need to be a unittest and I don't what to automatically convert the files I just want to monitor the py3 compliance of files in a unittest like manor. I can't seem to find any documentation or examples for this.
An example and/or documentation would be great.
| [
"Simply use the -3 option with python2.6+ to be informed of Python3 compliance.\n",
"If you are trying to verify the code will work in Python 3.x, I would suggest a script that copies the source files to a new directory, runs 2to3 on them, then copies the unit tests to the directory and runs them.\nThis may seem slightly inelegant, but is consistent with the spirit of unit testing. You are making a series of assertions that you believe ought to be true about the external behavior of the code, regardless of implementation. If the converted code passes your unit tests, you can consider your code to support Python 3.\n"
] | [
2,
1
] | [] | [] | [
"python",
"python_2to3",
"unit_testing"
] | stackoverflow_0002800231_python_python_2to3_unit_testing.txt |
Q:
UnicodeEncodeError while writing data to an xml file
My aim is to write an XML file with few tags whose values are in the regional language. I'm using Python to do this and using IDLE (Pythong GUI) for programming.
While I try to write the words in an xmls file it gives the following error:
UnicodeEncodeError: 'ascii' codec
can't encode characters in position
0-4: ordinal not in range(128)
For now, I'm not using any xml writer library; instead, I'm opening a file "test.xml" and writing the data into it. This error is encountered by the line:
f.write(data)
If I replace the above write statement with print statement then it prints the data properly on the Python shell.
I'm reading the data from an Excel file which is not in the UTF-8, 16, or 32 encoding formats. It's in some other format. cp1252 is reading the data properly.
Any help in getting this data written to an XML file would be highly appreciated.
A:
You should .decode your incoming cp1252 to get Unicode strings, and .encode them in utf-8 (by far the preferred encoding for XML) at the time you write, i.e.
f.write(unicodedata.encode('utf-8'))
where unicodedata is obtained by .decode('cp1252') on the incoming bytestrings.
It's possible to put lipstick on it by using the codecs module of the standard Python library to open the input and output files each with their proper encodings in lieu of plain open, but what I show is the underlying mechanism (and it's often, though not invariably, clearer and more explicit to apply it directly, rather than indirectly via codecs -- a matter of style and taste).
What does matter is the general principle: translate your input strings to unicode as soon as you can right after you obtain them, use unicode throughout your processing, translate them back to byte strings at late as you can just before you output them. This gives you the simplest, most straightforward life!-)
| UnicodeEncodeError while writing data to an xml file | My aim is to write an XML file with few tags whose values are in the regional language. I'm using Python to do this and using IDLE (Pythong GUI) for programming.
While I try to write the words in an xmls file it gives the following error:
UnicodeEncodeError: 'ascii' codec
can't encode characters in position
0-4: ordinal not in range(128)
For now, I'm not using any xml writer library; instead, I'm opening a file "test.xml" and writing the data into it. This error is encountered by the line:
f.write(data)
If I replace the above write statement with print statement then it prints the data properly on the Python shell.
I'm reading the data from an Excel file which is not in the UTF-8, 16, or 32 encoding formats. It's in some other format. cp1252 is reading the data properly.
Any help in getting this data written to an XML file would be highly appreciated.
| [
"You should .decode your incoming cp1252 to get Unicode strings, and .encode them in utf-8 (by far the preferred encoding for XML) at the time you write, i.e.\nf.write(unicodedata.encode('utf-8'))\n\nwhere unicodedata is obtained by .decode('cp1252') on the incoming bytestrings.\nIt's possible to put lipstick on it by using the codecs module of the standard Python library to open the input and output files each with their proper encodings in lieu of plain open, but what I show is the underlying mechanism (and it's often, though not invariably, clearer and more explicit to apply it directly, rather than indirectly via codecs -- a matter of style and taste).\nWhat does matter is the general principle: translate your input strings to unicode as soon as you can right after you obtain them, use unicode throughout your processing, translate them back to byte strings at late as you can just before you output them. This gives you the simplest, most straightforward life!-)\n"
] | [
6
] | [] | [] | [
"encoding",
"python",
"xml"
] | stackoverflow_0002800383_encoding_python_xml.txt |
Q:
Multi-variate regression using NumPy in Python?
Is it possible to perform multi-variate regression in Python using NumPy?
The documentation here suggests that it is, but I cannot find any more details on the topic.
A:
Yes, download this ( http://www.scipy.org/Cookbook/OLS?action=AttachFile&do=get&target=ols.0.2.py ) from http://www.scipy.org/Cookbook/OLS
Or you can install R and a python-R link. R can do anything.
A:
The webpage that you linked to mentions numpy.linalg.lstsq to find the vector x
which minimizes |b - Ax|. Here is a little example of how it can be used:
First we setup some "random" data:
import numpy as np
c1,c2 = 5.0,2.0
x = np.arange(1,11)/10.0
y = c1*np.exp(-x)+c2*x
b = y + 0.01*max(y)*np.random.randn(len(y))
A = np.column_stack((np.exp(-x),x))
c,resid,rank,sigma = np.linalg.lstsq(A,b)
print(c)
# [ 4.96579654 2.03913202]
A:
You might want to look into the scipy.optimize.leastsq function. It's rather complicated but I seem to remember that being the thing I would look to when I wanted to do a multivariate regression. (It's been a while so I could be misremembering)
| Multi-variate regression using NumPy in Python? | Is it possible to perform multi-variate regression in Python using NumPy?
The documentation here suggests that it is, but I cannot find any more details on the topic.
| [
"Yes, download this ( http://www.scipy.org/Cookbook/OLS?action=AttachFile&do=get&target=ols.0.2.py ) from http://www.scipy.org/Cookbook/OLS\nOr you can install R and a python-R link. R can do anything.\n",
"The webpage that you linked to mentions numpy.linalg.lstsq to find the vector x\nwhich minimizes |b - Ax|. Here is a little example of how it can be used:\nFirst we setup some \"random\" data:\nimport numpy as np\nc1,c2 = 5.0,2.0\nx = np.arange(1,11)/10.0\ny = c1*np.exp(-x)+c2*x\nb = y + 0.01*max(y)*np.random.randn(len(y))\nA = np.column_stack((np.exp(-x),x))\nc,resid,rank,sigma = np.linalg.lstsq(A,b)\nprint(c)\n# [ 4.96579654 2.03913202]\n\n",
"You might want to look into the scipy.optimize.leastsq function. It's rather complicated but I seem to remember that being the thing I would look to when I wanted to do a multivariate regression. (It's been a while so I could be misremembering)\n"
] | [
3,
2,
1
] | [] | [] | [
"python",
"regression"
] | stackoverflow_0002799491_python_regression.txt |
Q:
It's possible make an OCR in Python to check words
in opened applications?
I want to automate firefox in some web page and I don't have a way to "know" if the page already load completely or if it still loading...
I was thinking about making an OCR to check the status bar... it's difficult ?
For example, when the word DONE appears at the status bar, the program continues to the next command...
A:
OCR is a terrible, terrible choice for something like this. Use OCR when you are encountering images with unknown text. If you are trying to automate Firefox, there's a billion better ways of doing so. Check out something like AutoIt or any one of a hundred automation tools for Windows. Or write a custom Firefox extension. Either one of those will be far easier to implement, more reliable, and more performant than OCR.
A:
Maybe http://groups.csail.mit.edu/uid/sikuli/ is what you want
| It's possible make an OCR in Python to check words | in opened applications?
I want to automate firefox in some web page and I don't have a way to "know" if the page already load completely or if it still loading...
I was thinking about making an OCR to check the status bar... it's difficult ?
For example, when the word DONE appears at the status bar, the program continues to the next command...
| [
"OCR is a terrible, terrible choice for something like this. Use OCR when you are encountering images with unknown text. If you are trying to automate Firefox, there's a billion better ways of doing so. Check out something like AutoIt or any one of a hundred automation tools for Windows. Or write a custom Firefox extension. Either one of those will be far easier to implement, more reliable, and more performant than OCR.\n",
"Maybe http://groups.csail.mit.edu/uid/sikuli/ is what you want\n"
] | [
4,
1
] | [] | [] | [
"firefox",
"ocr",
"python",
"windows"
] | stackoverflow_0002800119_firefox_ocr_python_windows.txt |
Q:
video player with qt phonon (using python)
I am working on Windows xp and am trying to get a simple video player running.
I am trying to use Phonon::VideoPlayer module for this. I am connecting the signal as
connect(self.player,SIGNAL("finished()"),self.player.deleteLater)
and then , when the Play button is pressed, it makes the following call:
self.player.play(Phonon.MediaSource("C:\\vid.mp4"))
But, this doesn't display the video in the video player widget. Neither can I hear audio. Can anyone help??
I tried using different video file formats but no luck.
A:
Try writing
self.player.play(Phonon.MediaSource("C:\\vid.mp4"))
to escape the \
A:
Phonon::MediaSource mediaSource= Phonon::MediaSource("C:\\vid.mp4");
Try creating media sources like this and also other Phonon objects..
| video player with qt phonon (using python) | I am working on Windows xp and am trying to get a simple video player running.
I am trying to use Phonon::VideoPlayer module for this. I am connecting the signal as
connect(self.player,SIGNAL("finished()"),self.player.deleteLater)
and then , when the Play button is pressed, it makes the following call:
self.player.play(Phonon.MediaSource("C:\\vid.mp4"))
But, this doesn't display the video in the video player widget. Neither can I hear audio. Can anyone help??
I tried using different video file formats but no luck.
| [
"Try writing\nself.player.play(Phonon.MediaSource(\"C:\\\\vid.mp4\"))\n\nto escape the \\\n",
"Phonon::MediaSource mediaSource= Phonon::MediaSource(\"C:\\\\vid.mp4\");\n\nTry creating media sources like this and also other Phonon objects..\n"
] | [
0,
0
] | [] | [] | [
"c++",
"phonon",
"pyqt",
"python",
"qt"
] | stackoverflow_0002454560_c++_phonon_pyqt_python_qt.txt |
Q:
PyQt: Get the position of QGraphicsWidgets in a QGraphicsGridLayout
I have a fairly simple PyQt application in which I'm placing instances of a QGraphicsWidget in a QGraphicsGridLayout and want to connect the widgets with lines drawn with a QGraphicsPath. Unfortunately, no matter what I try, I always get (0, 0) back as the position for both the start and end widgets.
I'm constructing the graph with a recursive function that adds widgets to the scene and layout. Once the recursive function is complete, the layout is added to a new widget, which is added to the scene to show everything. The edges are added to the scene as widgets are created.
How do I get a non-zero position of any of the widgets in the grid layout?
Update: I forgot to mention that I've tried both pos() and scenePos() on the widgets in the grid layout. Both always return (0, 0) as the position for every widget in the grid.
A:
If you use the QGraphicsItem::pos(), it gives you the position of the item in the parent coordinates. When using QGraphicsLayout, the parent is probably the cell containing the object thus the coordinate is equal to zero.
Since you want to connect widgets with path, you will need scene coordinate to define the control points: use QGraphicsItem::scenePos() to obtain the position of your QGraphicsWidget in the scene.
| PyQt: Get the position of QGraphicsWidgets in a QGraphicsGridLayout | I have a fairly simple PyQt application in which I'm placing instances of a QGraphicsWidget in a QGraphicsGridLayout and want to connect the widgets with lines drawn with a QGraphicsPath. Unfortunately, no matter what I try, I always get (0, 0) back as the position for both the start and end widgets.
I'm constructing the graph with a recursive function that adds widgets to the scene and layout. Once the recursive function is complete, the layout is added to a new widget, which is added to the scene to show everything. The edges are added to the scene as widgets are created.
How do I get a non-zero position of any of the widgets in the grid layout?
Update: I forgot to mention that I've tried both pos() and scenePos() on the widgets in the grid layout. Both always return (0, 0) as the position for every widget in the grid.
| [
"If you use the QGraphicsItem::pos(), it gives you the position of the item in the parent coordinates. When using QGraphicsLayout, the parent is probably the cell containing the object thus the coordinate is equal to zero.\nSince you want to connect widgets with path, you will need scene coordinate to define the control points: use QGraphicsItem::scenePos() to obtain the position of your QGraphicsWidget in the scene.\n"
] | [
1
] | [] | [] | [
"pyqt",
"python",
"qt"
] | stackoverflow_0002799776_pyqt_python_qt.txt |
Q:
testing existing attribute of a @classmethod function, yields AttributeError
i have a function which is a class method, and i want to test a attribute of the class which may or may not be None, but will exist always.
class classA():
def __init__(self, var1, var2 = None):
self.attribute1 = var1
self.attribute2 = var2
@classmethod
def func(self,x):
if self.attribute2 is None:
do something
i get the error
AttributeError: class classA has no attribute 'attributeB'
when i access the attribute like i showed but if on command line i can see it works,
x = classA()
x.attribute2 is None
True
so the test works.
if i remove the @classmethod decorator from func, the problem disapears.
if i leave the @classmethod decorator, it only seems to affect variables which are supplied default values in the super-class's constructor.
whats going on in the above code?
A:
There is a difference between class attributes and instance attributes. A quick demonstration would be this:
>>> class A(object):
... x=4
... def __init__(self):
... self.y=2
>>> a=A() #a is now an instance of A
>>> A.x #Works as x is an attribute of the class
2: 4
>>> a.x #Works as instances can access class variables
3: 4
>>> a.y #Works as y is an attribute of the instance
4: 2
>>> A.y #Fails as the class A has no attribute y
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
A.y #Fails as the class A has no attribute y
AttributeError: type object 'A' has no attribute 'y'
>>>
Now, when a method of a class is decorated with classmethod, that signals that it does not take an instance, but takes the class itself as the parameter. Thus, conventionally we name the first argument cls, and not self. In your code, classA has no attributes, and so trying to access attribute2 fails. This difference can be shown with the below code:
>>> class B(object):
... x=2
... def __init__(self):
... self.x=7
... def pr1(self):
... print self.x
... @classmethod
... def pr2(cls):
... print cls.x
>>> b=B()
>>> B.x
2
>>> b.x
7
>>> b.pr1()
7
>>> b.pr2()
2
>>> B.pr2()
2
I might not have been clear enough, so if you are still confused just search classmethod or new-style classes and read up a bit on this.
A:
You should first test to see if you HAVE the attribute with hasattr() or somesuch.
class classA(superClass):
def func(self,x):
if not hasattr(self, "attributeB") or self.attributeB is None:
do somthing
You may also want to make sure that the sub-class is calling the constructor method from the parent class. That attribute is obviously getting assigned after you're referencing it. So make sure the class is properly constructed with
parentclassName.__init__(self, ... )
A:
self in an instance method is the instance. self (or more traditionally, cls) in a class method is the class. Attributes bound on an instance are not visible on the class. The only way to make this work would be to pass the instance to the class method, at which point you may as well just make it an instance method.
A:
The two attributes are instance attributes, not class attributes. The class method is trying to reference class attributes. Neither your attribute1 nor your attribute2 exist on the class: they exist on the instance.
I don't know how to fix this, but this is the source of the problem.
(Verified by changing attribute2 to attribute1 in func.)
So the question should really be, "How to reference instance attributes within a class method?"
| testing existing attribute of a @classmethod function, yields AttributeError | i have a function which is a class method, and i want to test a attribute of the class which may or may not be None, but will exist always.
class classA():
def __init__(self, var1, var2 = None):
self.attribute1 = var1
self.attribute2 = var2
@classmethod
def func(self,x):
if self.attribute2 is None:
do something
i get the error
AttributeError: class classA has no attribute 'attributeB'
when i access the attribute like i showed but if on command line i can see it works,
x = classA()
x.attribute2 is None
True
so the test works.
if i remove the @classmethod decorator from func, the problem disapears.
if i leave the @classmethod decorator, it only seems to affect variables which are supplied default values in the super-class's constructor.
whats going on in the above code?
| [
"There is a difference between class attributes and instance attributes. A quick demonstration would be this:\n>>> class A(object):\n... x=4\n... def __init__(self):\n... self.y=2\n>>> a=A() #a is now an instance of A\n>>> A.x #Works as x is an attribute of the class\n2: 4\n>>> a.x #Works as instances can access class variables\n3: 4\n>>> a.y #Works as y is an attribute of the instance\n4: 2\n>>> A.y #Fails as the class A has no attribute y\nTraceback (most recent call last):\n File \"<pyshell#9>\", line 1, in <module>\n A.y #Fails as the class A has no attribute y\nAttributeError: type object 'A' has no attribute 'y'\n>>> \n\nNow, when a method of a class is decorated with classmethod, that signals that it does not take an instance, but takes the class itself as the parameter. Thus, conventionally we name the first argument cls, and not self. In your code, classA has no attributes, and so trying to access attribute2 fails. This difference can be shown with the below code:\n>>> class B(object):\n... x=2\n... def __init__(self):\n... self.x=7\n... def pr1(self):\n... print self.x\n... @classmethod\n... def pr2(cls):\n... print cls.x\n>>> b=B()\n>>> B.x\n2\n>>> b.x\n7\n>>> b.pr1()\n7\n>>> b.pr2()\n2\n>>> B.pr2()\n2\n\nI might not have been clear enough, so if you are still confused just search classmethod or new-style classes and read up a bit on this.\n",
"You should first test to see if you HAVE the attribute with hasattr() or somesuch.\nclass classA(superClass):\n def func(self,x):\n if not hasattr(self, \"attributeB\") or self.attributeB is None:\n do somthing \n\nYou may also want to make sure that the sub-class is calling the constructor method from the parent class. That attribute is obviously getting assigned after you're referencing it. So make sure the class is properly constructed with \nparentclassName.__init__(self, ... )\n\n",
"self in an instance method is the instance. self (or more traditionally, cls) in a class method is the class. Attributes bound on an instance are not visible on the class. The only way to make this work would be to pass the instance to the class method, at which point you may as well just make it an instance method.\n",
"The two attributes are instance attributes, not class attributes. The class method is trying to reference class attributes. Neither your attribute1 nor your attribute2 exist on the class: they exist on the instance.\nI don't know how to fix this, but this is the source of the problem. \n(Verified by changing attribute2 to attribute1 in func.)\nSo the question should really be, \"How to reference instance attributes within a class method?\"\n"
] | [
7,
2,
2,
0
] | [] | [] | [
"class",
"python",
"variables"
] | stackoverflow_0002791759_class_python_variables.txt |
Q:
How to find the file system type in python
I'm looking for a way in python to find out which type of file system is being used for a given path. I'm wanting to do this in a cross platform way. On linux I could just grab the output of df -T but that won't work on OSX or windows.
A:
Take the hint -- different platforms are actually different.
Use lsvfs on Mac OS X and those Linux that support it.
Use this on Windows.
Use an if-statement to decide.
A:
This is the Windows API you might want to call. This should be a good start for the OS X api you are looking for, instead.
| How to find the file system type in python | I'm looking for a way in python to find out which type of file system is being used for a given path. I'm wanting to do this in a cross platform way. On linux I could just grab the output of df -T but that won't work on OSX or windows.
| [
"Take the hint -- different platforms are actually different. \nUse lsvfs on Mac OS X and those Linux that support it.\nUse this on Windows.\nUse an if-statement to decide.\n",
"This is the Windows API you might want to call. This should be a good start for the OS X api you are looking for, instead.\n"
] | [
2,
0
] | [
"os.popen('/sbin/fdisk -l /dev/sda') on Linux\n"
] | [
-1
] | [
"filesystems",
"macos",
"python",
"windows"
] | stackoverflow_0002800798_filesystems_macos_python_windows.txt |
Q:
MySQL LOAD DATA LOCAL INFILE example in python?
I am looking for a syntax definition, example, sample code, wiki, etc. for
executing a LOAD DATA LOCAL INFILE command from python.
I believe I can use mysqlimport as well if that is available, so any feedback (and code snippet) on which is the better route, is welcome. A Google search is not turning up much in the way of current info
The goal in either case is the same: Automate loading hundreds of files with a known naming convention & date structure, into a single MySQL table.
David
A:
Well, using python's MySQLdb, I use this:
connection = MySQLdb.Connect(host='**', user='**', passwd='**', db='**')
cursor = connection.cursor()
query = "LOAD DATA INFILE '/path/to/my/file' INTO TABLE sometable FIELDS TERMINATED BY ';' ENCLOSED BY '\"' ESCAPED BY '\\\\'"
cursor.execute( query )
connection.commit()
replacing the host/user/passwd/db as appropriate for your needs. This is based on the MySQL docs here, The exact LOAD DATA INFILE statement would depend on your specific requirements etc (note the FIELDS TERMINATED BY, ENCLOSED BY, and ESCAPED BY statements will be specific to the type of file you are trying to read in).
| MySQL LOAD DATA LOCAL INFILE example in python? | I am looking for a syntax definition, example, sample code, wiki, etc. for
executing a LOAD DATA LOCAL INFILE command from python.
I believe I can use mysqlimport as well if that is available, so any feedback (and code snippet) on which is the better route, is welcome. A Google search is not turning up much in the way of current info
The goal in either case is the same: Automate loading hundreds of files with a known naming convention & date structure, into a single MySQL table.
David
| [
"Well, using python's MySQLdb, I use this:\nconnection = MySQLdb.Connect(host='**', user='**', passwd='**', db='**')\ncursor = connection.cursor()\nquery = \"LOAD DATA INFILE '/path/to/my/file' INTO TABLE sometable FIELDS TERMINATED BY ';' ENCLOSED BY '\\\"' ESCAPED BY '\\\\\\\\'\"\ncursor.execute( query )\nconnection.commit()\n\nreplacing the host/user/passwd/db as appropriate for your needs. This is based on the MySQL docs here, The exact LOAD DATA INFILE statement would depend on your specific requirements etc (note the FIELDS TERMINATED BY, ENCLOSED BY, and ESCAPED BY statements will be specific to the type of file you are trying to read in). \n"
] | [
30
] | [
"You can also get the results for the import by adding the following lines after your query:\nresults = connection.info()\n\n"
] | [
-1
] | [
"load_data_infile",
"mysql",
"python"
] | stackoverflow_0001231900_load_data_infile_mysql_python.txt |
Q:
Boost.Python wrapping hierarchies avoiding diamond inheritance
I'm having some trouble seeing what the best way to wrap a series of classes with Boost.Python while avoiding messy inheritance problems. Say I have the classes A, B, and C with the following structure:
struct A {
virtual void foo();
virtual void bar();
virtual void baz();
};
struct B : public A {
virtual void quux();
};
struct C : public A {
virtual void foobar();
};
I want to wrap all classes A, B, and C such that they are extendable from Python. The normal method for accomplishing this would be along the lines of:
struct A_Wrapper : public A, boost::python::wrapper<A> {
//dispatch logic for virtual functions
};
Now for classes B and C which extend from A I would like to be able to inherit and share the wrapping implementation for A. So I'd like to be able to do something along the lines of:
struct B_Wrapper : public B, public A_Wrapper, public boost::python::wrapper<B> {
//dispatch logic specific for B
};
struct C_Wrapper : public C, public A_Wrapper, public boost::python::wrapper<C> {
//dispatch logic specific for C
}
However, it seems like that would introduce all manner of nastiness with the double inheritance of the boost wrapper base and the double inheritance of A in the B_Wrapper and C_Wrapper objects. Is there a common way that this instance is solved that I'm missing?
thanks.
A:
One approach is to derive virtually:
struct B : virtual public A, ... { };
struct C : virtual public A, ... { };
struct A_Wrapper : virtual public A, ... { };
See the relevant C++ FAQ Lite items for notes and what this implies.
A:
I had exactly the same problem, and I simply didn't inherited B_Wrapper from A_Wrapper (copy and paste was sufficient for my needs).
I think it is possible to share the common implementation in a helper class:
template<class ADERIVED>
struct A_Implem: public ADERIVED, public wrapper<ADERIVED>
{
// dispatch logic
};
And then:
struct A_Wrapper: public A_Implem<A>
{
// ...
};
struct B_Wrapper: public A_Implem<B>
{
// ...
};
| Boost.Python wrapping hierarchies avoiding diamond inheritance | I'm having some trouble seeing what the best way to wrap a series of classes with Boost.Python while avoiding messy inheritance problems. Say I have the classes A, B, and C with the following structure:
struct A {
virtual void foo();
virtual void bar();
virtual void baz();
};
struct B : public A {
virtual void quux();
};
struct C : public A {
virtual void foobar();
};
I want to wrap all classes A, B, and C such that they are extendable from Python. The normal method for accomplishing this would be along the lines of:
struct A_Wrapper : public A, boost::python::wrapper<A> {
//dispatch logic for virtual functions
};
Now for classes B and C which extend from A I would like to be able to inherit and share the wrapping implementation for A. So I'd like to be able to do something along the lines of:
struct B_Wrapper : public B, public A_Wrapper, public boost::python::wrapper<B> {
//dispatch logic specific for B
};
struct C_Wrapper : public C, public A_Wrapper, public boost::python::wrapper<C> {
//dispatch logic specific for C
}
However, it seems like that would introduce all manner of nastiness with the double inheritance of the boost wrapper base and the double inheritance of A in the B_Wrapper and C_Wrapper objects. Is there a common way that this instance is solved that I'm missing?
thanks.
| [
"One approach is to derive virtually:\nstruct B : virtual public A, ... { };\nstruct C : virtual public A, ... { };\nstruct A_Wrapper : virtual public A, ... { };\n\nSee the relevant C++ FAQ Lite items for notes and what this implies.\n",
"I had exactly the same problem, and I simply didn't inherited B_Wrapper from A_Wrapper (copy and paste was sufficient for my needs). \nI think it is possible to share the common implementation in a helper class:\ntemplate<class ADERIVED>\nstruct A_Implem: public ADERIVED, public wrapper<ADERIVED>\n{\n // dispatch logic\n};\n\nAnd then:\nstruct A_Wrapper: public A_Implem<A>\n{\n// ...\n};\n\n\nstruct B_Wrapper: public A_Implem<B>\n{\n// ...\n};\n\n"
] | [
1,
1
] | [] | [] | [
"boost",
"boost_python",
"c++",
"python"
] | stackoverflow_0002792117_boost_boost_python_c++_python.txt |
Q:
is this a correct way to generate rsa keys?
is this code going to give me correct values for RSA keys (assuming that the other functions are correct)? im having trouble getting my program to decrypt properly, as in certain blocks are not decrypting properly
this is in python:
import random
def keygen(bits):
p = q = 3
while p == q:
p = random.randint(2**(bits/2-2),2**(bits/2))
q = random.randint(2**(bits/2-2),2**(bits/2))
p += not(p&1) # changes the values from
q += not(q&1) # even to odd
while MillerRabin(p) == False: # checks for primality
p -= 2
while MillerRabin(q) == False:
q -= 2
n = p * q
tot = (p-1) * (q-1)
e = tot
while gcd(tot,e) != 1:
e = random.randint(3,tot-1)
d = getd(tot,e) # gets the multiplicative inverse
while d<0: # i can probably replace this with mod
d = d + tot
return e,d,n
one set of keys generated:
e = 3daf16a37799d3b2c951c9baab30ad2d
d = 16873c0dd2825b2e8e6c2c68da3a5e25
n = dc2a732d64b83816a99448a2c2077ced
A:
Mathematically, your n, e and d appear to respect the RSA rules (i.e. for every prime r which divides n, r2 does not divide n, and d is an inverse of e modulo r-1). However, RSA is a bit more than that; it also mandates some padding rules, which govern how a message (a sequence of bytes) is to be transformed into an integer modulo n, and back. The standard padding (see PKCS#1) implies that at least 11 bytes are added to the message, and the result must still be no longer by n. Hence, with a 128-bit modulus
like the one you show, the maximum input message length for encryption will be 5 bytes.
Also, some RSA implementations will refuse to work with RSA keys which are much too small for security. A 128-bit modulus can be factor in a matter of seconds (see this page for a factorization Java applet, which uses ECM and quadratic sieve to factor relatively small numbers such as yours). The current record in factorization is 768 bits; a modulus length of at least 1024 bits is recommended for short-term security. A typical RSA implementation will accept to use 512-bit keys, but many will reject anything shorter than that.
Another possible issue is in the relative order of p and q. The equations laid out in PKCS#1 assume that p > q (otherwise, there is an extra subtraction to perform in the CRT part). If you have p < q, then some implementations may get it wrong (I encountered that with Microsoft's RSA standard implementation in Windows). Just compare p with q and swap them if necessary.
Still on the practicality level, some widespread RSA implementations will refuse a RSA key such that the public exponent e does not fit within a 32-bit integer (this includes the RSA implementation used in Windows, in particular by Internet Explorer to connect to HTTPS Web sites -- so when I write "widespread" I mean it). RSA security does not seem to be impacted by the choice of e, so it is customary to choose a small e, which speeds up the part which uses the public key (i.e. encryption, as opposed to decryption, or signature verification, as opposed to signature generation). e = 3 is about the best you could do, but for traditional reasons (including an historical misunderstanding on an alleged weakness), e=65537 is often used. You just need to have e relatively prime to p-1 and q-1. In a practical implementation, you choose e first, then loop within the generation for p and q as long as they do not match that additional rule.
From a security point of view:
Your generation process is not uniform, in that some prime integers will be selected more often than others. In particular, a prime p such that p+2 is also prime will almost never be selected. With a proper modulus size, this should not be an issue (that special kind of bias was studied and found out not to be a big issue) but it is bad public relations nonetheless.
Your n may be a bit smaller than your target size, in case both p and q are close to the lower bound of their generation range. A simple way to avoid that is to restrict the range to [sqrt(2)*2b-1, 2b] for both p and q.
I cannot vouch for the security of the random module you use. A cryptographically secure random number generator is not an easy thing to do.
Generally speaking, properly implementing RSA without leaking confidential information through various side channels (timing, cache memory usage...) is not an easy task. If you want security in a practical setup, you should really really use an existing package. I believe that Python has ways to interface with OpenSSL.
A:
I assume you are doing this for fun and learning, and not for something that needs actual security.
Here is a few things I noticed (in no particular order):
You are not guaranteed that n will have length bits. It might be as short as bits - 4.
random is not a cryptographically secure random number generator.
It is common (and just as secure) to select the public exponent, e, to 65537. This is a prime, so you can replace the coprime-check with a divisor check.
It is a bit strange the search for e by setting e = tot (the coprime-check is bound to fail).
Otherwise it looks fine. The key seems to work fine, too. Do you have an example of a block that is not decrypting correctly? Remember that you can only encrypt data that is smaller than n. So with a 128-bit key (as in you example) you cannot encrypt all 128-bit numbers.
| is this a correct way to generate rsa keys? | is this code going to give me correct values for RSA keys (assuming that the other functions are correct)? im having trouble getting my program to decrypt properly, as in certain blocks are not decrypting properly
this is in python:
import random
def keygen(bits):
p = q = 3
while p == q:
p = random.randint(2**(bits/2-2),2**(bits/2))
q = random.randint(2**(bits/2-2),2**(bits/2))
p += not(p&1) # changes the values from
q += not(q&1) # even to odd
while MillerRabin(p) == False: # checks for primality
p -= 2
while MillerRabin(q) == False:
q -= 2
n = p * q
tot = (p-1) * (q-1)
e = tot
while gcd(tot,e) != 1:
e = random.randint(3,tot-1)
d = getd(tot,e) # gets the multiplicative inverse
while d<0: # i can probably replace this with mod
d = d + tot
return e,d,n
one set of keys generated:
e = 3daf16a37799d3b2c951c9baab30ad2d
d = 16873c0dd2825b2e8e6c2c68da3a5e25
n = dc2a732d64b83816a99448a2c2077ced
| [
"Mathematically, your n, e and d appear to respect the RSA rules (i.e. for every prime r which divides n, r2 does not divide n, and d is an inverse of e modulo r-1). However, RSA is a bit more than that; it also mandates some padding rules, which govern how a message (a sequence of bytes) is to be transformed into an integer modulo n, and back. The standard padding (see PKCS#1) implies that at least 11 bytes are added to the message, and the result must still be no longer by n. Hence, with a 128-bit modulus\nlike the one you show, the maximum input message length for encryption will be 5 bytes.\nAlso, some RSA implementations will refuse to work with RSA keys which are much too small for security. A 128-bit modulus can be factor in a matter of seconds (see this page for a factorization Java applet, which uses ECM and quadratic sieve to factor relatively small numbers such as yours). The current record in factorization is 768 bits; a modulus length of at least 1024 bits is recommended for short-term security. A typical RSA implementation will accept to use 512-bit keys, but many will reject anything shorter than that.\nAnother possible issue is in the relative order of p and q. The equations laid out in PKCS#1 assume that p > q (otherwise, there is an extra subtraction to perform in the CRT part). If you have p < q, then some implementations may get it wrong (I encountered that with Microsoft's RSA standard implementation in Windows). Just compare p with q and swap them if necessary.\nStill on the practicality level, some widespread RSA implementations will refuse a RSA key such that the public exponent e does not fit within a 32-bit integer (this includes the RSA implementation used in Windows, in particular by Internet Explorer to connect to HTTPS Web sites -- so when I write \"widespread\" I mean it). RSA security does not seem to be impacted by the choice of e, so it is customary to choose a small e, which speeds up the part which uses the public key (i.e. encryption, as opposed to decryption, or signature verification, as opposed to signature generation). e = 3 is about the best you could do, but for traditional reasons (including an historical misunderstanding on an alleged weakness), e=65537 is often used. You just need to have e relatively prime to p-1 and q-1. In a practical implementation, you choose e first, then loop within the generation for p and q as long as they do not match that additional rule.\nFrom a security point of view:\n\nYour generation process is not uniform, in that some prime integers will be selected more often than others. In particular, a prime p such that p+2 is also prime will almost never be selected. With a proper modulus size, this should not be an issue (that special kind of bias was studied and found out not to be a big issue) but it is bad public relations nonetheless.\nYour n may be a bit smaller than your target size, in case both p and q are close to the lower bound of their generation range. A simple way to avoid that is to restrict the range to [sqrt(2)*2b-1, 2b] for both p and q.\nI cannot vouch for the security of the random module you use. A cryptographically secure random number generator is not an easy thing to do.\nGenerally speaking, properly implementing RSA without leaking confidential information through various side channels (timing, cache memory usage...) is not an easy task. If you want security in a practical setup, you should really really use an existing package. I believe that Python has ways to interface with OpenSSL.\n\n",
"I assume you are doing this for fun and learning, and not for something that needs actual security.\nHere is a few things I noticed (in no particular order):\n\nYou are not guaranteed that n will have length bits. It might be as short as bits - 4.\nrandom is not a cryptographically secure random number generator.\nIt is common (and just as secure) to select the public exponent, e, to 65537. This is a prime, so you can replace the coprime-check with a divisor check.\nIt is a bit strange the search for e by setting e = tot (the coprime-check is bound to fail).\n\nOtherwise it looks fine. The key seems to work fine, too. Do you have an example of a block that is not decrypting correctly? Remember that you can only encrypt data that is smaller than n. So with a 128-bit key (as in you example) you cannot encrypt all 128-bit numbers.\n"
] | [
16,
5
] | [] | [] | [
"cryptography",
"public_key",
"python",
"rsa"
] | stackoverflow_0002799503_cryptography_public_key_python_rsa.txt |
Q:
Overwrite method at runtime in python
I have method that run many times. I dont want to nest ifs inside but rather want to overwrite method and then run it. I know that i can overwrite class method by simple assigment, but overwriten method doesn't see private members:
class X:
def __init__(self, a):
self.a = a
self.__b = a
def m(self):
print self.a
print self.__b
def a2(self):
print (2*self.a)
print (2*self.__b)
x = X(2)
x.m()
X.m = a2
x.m()
output:
2
2
4
Traceback (most recent call last):
File "t.py", line 17, in <module>
x.m()
File "t.py", line 12, in a2
print (2*self.__b)
AttributeError: X instance has no attribute '__b'
Is there any chance to solve this problem? Google doesn't show answer :(
A:
Attributes within classes that start with double underscores are name-mangled. Never use them unless you're certain you need them. There's nothing private about them, so you should use a single underscore instead.
The reason you're having this problem is because the attribute access in a2() is not name-mangled.
| Overwrite method at runtime in python | I have method that run many times. I dont want to nest ifs inside but rather want to overwrite method and then run it. I know that i can overwrite class method by simple assigment, but overwriten method doesn't see private members:
class X:
def __init__(self, a):
self.a = a
self.__b = a
def m(self):
print self.a
print self.__b
def a2(self):
print (2*self.a)
print (2*self.__b)
x = X(2)
x.m()
X.m = a2
x.m()
output:
2
2
4
Traceback (most recent call last):
File "t.py", line 17, in <module>
x.m()
File "t.py", line 12, in a2
print (2*self.__b)
AttributeError: X instance has no attribute '__b'
Is there any chance to solve this problem? Google doesn't show answer :(
| [
"Attributes within classes that start with double underscores are name-mangled. Never use them unless you're certain you need them. There's nothing private about them, so you should use a single underscore instead.\nThe reason you're having this problem is because the attribute access in a2() is not name-mangled.\n"
] | [
4
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0002802896_oop_python.txt |
Q:
How to make if-elif-else statement in python more space-saving?
I have a lot of if-elif-else statements in my code
if message == '0' or message == '3' or message == '5' or message == '7':
...
elif message == '1' or message == '2' or message == '4' or message == '6' or message == '8':
...
else:
...
Is it possible to format this in a more space-saving way?
I tried it this way:
if message == '0' or '3' or '5' or '7':
...
elif message == '1' or '2' or '4' or '6' or '8':
...
else:
...
But without success.
A:
if message in ("0", "3", "5", "7"):
...
elif message in ...
would be one way.
If message is always one character long, you could also use
if message in "0357":
....
But this would also be true if message == "35", therefore the warning.
(EDIT)
A short explanation why your approach wasn't working:
if message == '0' or '3' or '5' or '7':
is interpreted as
if (message == '0') or '3' or '5' or '7':
and therefore always succeeds because '3' evaluates to True.
A:
if message in '0357' :
...
elif message in '12468' :
...
else:
...
In a more global way :
if value in [elem0, elem1, ... ]:
...
| How to make if-elif-else statement in python more space-saving? | I have a lot of if-elif-else statements in my code
if message == '0' or message == '3' or message == '5' or message == '7':
...
elif message == '1' or message == '2' or message == '4' or message == '6' or message == '8':
...
else:
...
Is it possible to format this in a more space-saving way?
I tried it this way:
if message == '0' or '3' or '5' or '7':
...
elif message == '1' or '2' or '4' or '6' or '8':
...
else:
...
But without success.
| [
"if message in (\"0\", \"3\", \"5\", \"7\"):\n ...\nelif message in ...\n\nwould be one way. \nIf message is always one character long, you could also use\nif message in \"0357\":\n ....\n\nBut this would also be true if message == \"35\", therefore the warning.\n\n(EDIT)\nA short explanation why your approach wasn't working:\nif message == '0' or '3' or '5' or '7':\n\nis interpreted as\nif (message == '0') or '3' or '5' or '7':\n\nand therefore always succeeds because '3' evaluates to True.\n",
"if message in '0357' :\n ...\nelif message in '12468' :\n ...\nelse:\n ...\n\nIn a more global way :\nif value in [elem0, elem1, ... ]:\n ...\n\n"
] | [
6,
1
] | [] | [] | [
"optimization",
"python"
] | stackoverflow_0002803133_optimization_python.txt |
Q:
How to get these values with BeautifulSoup?
I have this html table:
<table>
<tr>
<td class="datax">a</td>
<td class="datax">b</td>
<td class="datax">c</td>
<td class="datax">d</td>
</tr>
<tr>
<td class="datax">e</td>
<td class="datax">f</td>
<td class="datax">g</td>
<td class="datax">h</td>
</tr>
</table>
How to get the second and the fourth value of each <tr> ?
If i do:
bs.findAll('td', {'class':'datax'})
I get:
<td class="datax">a</td>
<td class="datax">b</td>
<td class="datax">c</td>
<td class="datax">d</td>
<td class="datax">e</td>
<td class="datax">f</td>
<td class="datax">g</td>
<td class="datax">h</td>
it's correct! but I would like to have this result:
<td class="datax">b</td>
<td class="datax">d</td>
<td class="datax">f</td>
<td class="datax">h</td>
so, the values I want are -> b - d - f - h
(the second and the forth <td> of each <tr>)
Is it possible with BeautifulSoup module?
Thank you very much!
A:
This should do it~
final_values=[td.string for td in bs.findAll('td', {'class':'datax'})[1::2]]
(after comment clarification) for your specific case it would be:
final_values=[td.b.a.string for td in bs.findAll('td', {'class':'datax'})[1::2]]
| How to get these values with BeautifulSoup? | I have this html table:
<table>
<tr>
<td class="datax">a</td>
<td class="datax">b</td>
<td class="datax">c</td>
<td class="datax">d</td>
</tr>
<tr>
<td class="datax">e</td>
<td class="datax">f</td>
<td class="datax">g</td>
<td class="datax">h</td>
</tr>
</table>
How to get the second and the fourth value of each <tr> ?
If i do:
bs.findAll('td', {'class':'datax'})
I get:
<td class="datax">a</td>
<td class="datax">b</td>
<td class="datax">c</td>
<td class="datax">d</td>
<td class="datax">e</td>
<td class="datax">f</td>
<td class="datax">g</td>
<td class="datax">h</td>
it's correct! but I would like to have this result:
<td class="datax">b</td>
<td class="datax">d</td>
<td class="datax">f</td>
<td class="datax">h</td>
so, the values I want are -> b - d - f - h
(the second and the forth <td> of each <tr>)
Is it possible with BeautifulSoup module?
Thank you very much!
| [
"This should do it~\nfinal_values=[td.string for td in bs.findAll('td', {'class':'datax'})[1::2]]\n\n(after comment clarification) for your specific case it would be:\nfinal_values=[td.b.a.string for td in bs.findAll('td', {'class':'datax'})[1::2]]\n\n"
] | [
5
] | [
"I know using HTQL, it is simple: \n<tr>.<td>2,4\n--\nHTQL only has COM support thought. Here is a complete example in javascript: \n<html> \n<body> \n<script language=JavaScript> \n var a= new ActiveXObject(\"HtqlCom.HtqlControl\"); \n a.setUrl(\"C:\\\\test_table.html\"); \n a.setQuery(\"<tr>.<td>2,4\"); \n for (a.moveFirst(); !a.isEOF(); a.moveNext()){ \n document.write(a.getValueByIndex(1)); \n } \n</script> \n</body> \n</html> \n"
] | [
-2
] | [
"beautifulsoup",
"python"
] | stackoverflow_0002803140_beautifulsoup_python.txt |
Q:
GUI Builder for Python
I looking for a GUI Builder for python
i know it exist, can see it in this image background
A:
It is Glade 3, a GUI Designer for GTK+. It generates an XML file representing your GUI. You can load this GUI later using PyGTK.
Specifically, the screenshot is running a Mac OS X port of Glade 3
A:
That's glade, it actually produces XML, which can be used with the PyGTK library in python
A:
The GUI designer isn't "for" python, it's for gtk+ and the associated language bindings known as pygtk.
there are two gui editors available:
http://glade.gnome.org/
http://www.mono-project.com/Stetic
A:
I use PyQt (PyQt Homepage); it is built on the QT Toolkit (http://www.qtsoftware.com/).
If you are deploying to Windows, it works well with the py2exe module (py2exe).
It's fairly straightforward to use, especially if you already have experience with the QT libraries.
A:
The one in the screenshot is Glade.
However, there are quite a few GUI-Builders for Python, as seen on http://wiki.python.org/moin/GuiProgramming
A:
Tkinter is one of many GUI builders available for python. I prefer it.
A:
Gazpacho is almost a clone of Glade, but written in pure PyGTK. We (the PIDA team) are currently refurbishing it.
A:
A python GUI builder is boa-constructor, whcih uses the WxWidgets toolkit
| GUI Builder for Python | I looking for a GUI Builder for python
i know it exist, can see it in this image background
| [
"It is Glade 3, a GUI Designer for GTK+. It generates an XML file representing your GUI. You can load this GUI later using PyGTK. \nSpecifically, the screenshot is running a Mac OS X port of Glade 3\n",
"That's glade, it actually produces XML, which can be used with the PyGTK library in python\n",
"The GUI designer isn't \"for\" python, it's for gtk+ and the associated language bindings known as pygtk.\nthere are two gui editors available:\n\nhttp://glade.gnome.org/\nhttp://www.mono-project.com/Stetic\n\n",
"I use PyQt (PyQt Homepage); it is built on the QT Toolkit (http://www.qtsoftware.com/). \nIf you are deploying to Windows, it works well with the py2exe module (py2exe). \nIt's fairly straightforward to use, especially if you already have experience with the QT libraries.\n",
"The one in the screenshot is Glade.\nHowever, there are quite a few GUI-Builders for Python, as seen on http://wiki.python.org/moin/GuiProgramming\n",
"Tkinter is one of many GUI builders available for python. I prefer it. \n",
"Gazpacho is almost a clone of Glade, but written in pure PyGTK. We (the PIDA team) are currently refurbishing it.\n",
"A python GUI builder is boa-constructor, whcih uses the WxWidgets toolkit\n"
] | [
8,
5,
4,
2,
2,
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0000529498_python.txt |
Q:
Chart for deciphering terms in different programming languages
This has been bugging me every since I started to use Python - in PHP you have this ability to use a string as a key in an array. PHP calls these associative arrays. Python calls these dictionaries.
Does anyone know of a premade chart that will let me see what the different terminology is in different languages. For example:
PHP | Python
Associative array | Dictionary
A:
I don't know where to find a chart, but Wikipedia has a detailed article about associative arrays in various languages
A:
I hope the below URL will solve your issue...this is ant a chat but see this blog, which express the performance management.
http://www.insideria.com/2008/04/dictionaries-and-associative-a.html
A:
You could keep a handy cheatsheet for your reference,
for python checkout http://www.addedbytes.com/download/python-cheat-sheet-v1/png/
for PHP checkout http://www.addedbytes.com/cheat-sheets/php-cheat-sheet/
| Chart for deciphering terms in different programming languages | This has been bugging me every since I started to use Python - in PHP you have this ability to use a string as a key in an array. PHP calls these associative arrays. Python calls these dictionaries.
Does anyone know of a premade chart that will let me see what the different terminology is in different languages. For example:
PHP | Python
Associative array | Dictionary
| [
"I don't know where to find a chart, but Wikipedia has a detailed article about associative arrays in various languages\n",
"I hope the below URL will solve your issue...this is ant a chat but see this blog, which express the performance management.\nhttp://www.insideria.com/2008/04/dictionaries-and-associative-a.html\n",
"You could keep a handy cheatsheet for your reference,\nfor python checkout http://www.addedbytes.com/download/python-cheat-sheet-v1/png/\nfor PHP checkout http://www.addedbytes.com/cheat-sheets/php-cheat-sheet/\n"
] | [
1,
0,
0
] | [] | [] | [
"php",
"programming_languages",
"python"
] | stackoverflow_0002803707_php_programming_languages_python.txt |
Q:
Why does not the Python MSI installers come with Tcl/Tk header files?
The MSI installers downloadable from python.org does not include Tcl/Tk header (not source) files (that are required to compile some packages like matplotlib). Does anyone know of the rationale behind not including them?
A:
The windows installers don't include ANY source files. Simply because that's how windows apps work. It can be compiled on one computer and it will work on all. So windows versions of things like python and php come precompiled with all options enabled.
If you want the source files you have to download a source tarball or something.
A:
Users, even on Unix systems, do not really need the Tcl/Tk headers to just use the Python interpreter.
If you were to wanting to embed the interpreter in another application, you only need the python headers and lib files (which are included in the installer). The tkinter module, which is what is linked to Tcl/Tk, is already compiled for you in the binary distribution, so your Python scripts can just use Tcl/Tk through tkinter...though you probably shouldn't in an embedded scenario. The reason being, your application can expose its UI features to Python through the Python/C API, and then you don't have a weird disconnect (visually and programmatically) between host-app windows and Python-source windows.
Long story short, the only real reason that I can see for needing the Tcl & Tk headers would be if you were trying to build the tkinter module from source, which pretty much nobody does on Windows, so they leave them out to save space.
| Why does not the Python MSI installers come with Tcl/Tk header files? | The MSI installers downloadable from python.org does not include Tcl/Tk header (not source) files (that are required to compile some packages like matplotlib). Does anyone know of the rationale behind not including them?
| [
"The windows installers don't include ANY source files. Simply because that's how windows apps work. It can be compiled on one computer and it will work on all. So windows versions of things like python and php come precompiled with all options enabled.\nIf you want the source files you have to download a source tarball or something.\n",
"Users, even on Unix systems, do not really need the Tcl/Tk headers to just use the Python interpreter.\nIf you were to wanting to embed the interpreter in another application, you only need the python headers and lib files (which are included in the installer). The tkinter module, which is what is linked to Tcl/Tk, is already compiled for you in the binary distribution, so your Python scripts can just use Tcl/Tk through tkinter...though you probably shouldn't in an embedded scenario. The reason being, your application can expose its UI features to Python through the Python/C API, and then you don't have a weird disconnect (visually and programmatically) between host-app windows and Python-source windows.\nLong story short, the only real reason that I can see for needing the Tcl & Tk headers would be if you were trying to build the tkinter module from source, which pretty much nobody does on Windows, so they leave them out to save space.\n"
] | [
1,
0
] | [] | [] | [
"header_files",
"python",
"tcl",
"tk_toolkit",
"tkinter"
] | stackoverflow_0002114615_header_files_python_tcl_tk_toolkit_tkinter.txt |
Q:
How can I parse a C header file with Perl?
I have a header file in which there is a large struct. I need to read this structure using some program and make some operations on each member of the structure and write them back.
For example I have some structure like
const BYTE Some_Idx[] = {
4,7,10,15,17,19,24,29,
31,32,35,45,49,51,52,54,
55,58,60,64,65,66,67,69,
70,72,76,77,81,82,83,85,
88,93,94,95,97,99,102,103,
105,106,113,115,122,124,125,126,
129,131,137,139,140,149,151,152,
153,155,158,159,160,163,165,169,
174,175,181,182,183,189,190,193,
197,201,204,206,208,210,211,212,
213,214,215,217,218,219,220,223,
225,228,230,234,236,237,240,241,
242,247,249};
Now, I need to read this and apply some operation on each of the member variable and create a new structure with different order, something like:
const BYTE Some_Idx_Mod_mul_2[] = {
8,14,20, ...
...
484,494,498};
Is there any Perl library already available for this? If not Perl, something else like Python is also OK.
Can somebody please help!!!
A:
Keeping your data lying around in a header makes it trickier to get at using other programs like Perl. Another approach you might consider is to keep this data in a database or another file and regenerate your header file as-needed, maybe even as part of your build system. The reason for this is that generating C is much easier than parsing C, it's trivial to write a script that parses a text file and makes a header for you, and such a script could even be invoked from your build system.
Assuming that you want to keep your data in a C header file, you will need one of two things to solve this problem:
a quick one-off script to parse exactly (or close to exactly) the input you describe.
a general, well-written script that can parse arbitrary C and work generally on to lots of different headers.
The first case seems more common than the second to me, but it's hard to tell from your question if this is better solved by a script that needs to parse arbitrary C or a script that needs to parse this specific file. For code that works on your specific case, the following works for me on your input:
#!/usr/bin/perl -w
use strict;
open FILE, "<header.h" or die $!;
my @file = <FILE>;
close FILE or die $!;
my $in_block = 0;
my $regex = 'Some_Idx\[\]';
my $byte_line = '';
my @byte_entries;
foreach my $line (@file) {
chomp $line;
if ( $line =~ /$regex.*\{(.*)/ ) {
$in_block = 1;
my @digits = @{ match_digits($1) };
push @digits, @byte_entries;
next;
}
if ( $in_block ) {
my @digits = @{ match_digits($line) };
push @byte_entries, @digits;
}
if ( $line =~ /\}/ ) {
$in_block = 0;
}
}
print "const BYTE Some_Idx_Mod_mul_2[] = {\n";
print join ",", map { $_ * 2 } @byte_entries;
print "};\n";
sub match_digits {
my $text = shift;
my @digits;
while ( $text =~ /(\d+),*/g ) {
push @digits, $1;
}
return \@digits;
}
Parsing arbitrary C is a little tricky and not worth it for many applications, but maybe you need to actually do this. One trick is to let GCC do the parsing for you and read in GCC's parse tree using a CPAN module named GCC::TranslationUnit.
Here's the GCC command to compile the code, assuming you have a single file named test.c:
gcc -fdump-translation-unit -c test.c
Here's the Perl code to read in the parse tree:
use GCC::TranslationUnit;
# echo '#include <stdio.h>' > stdio.c
# gcc -fdump-translation-unit -c stdio.c
$node = GCC::TranslationUnit::Parser->parsefile('stdio.c.tu')->root;
# list every function/variable name
while($node) {
if($node->isa('GCC::Node::function_decl') or
$node->isa('GCC::Node::var_decl')) {
printf "%s declared in %s\n",
$node->name->identifier, $node->source;
}
} continue {
$node = $node->chain;
}
A:
Sorry if this is a stupid question, but why worry about parsing the file at all? Why not write a C program that #includes the header, processes it as required and then spits out the source for the modified header. I'm sure this would be simpler than the Perl/Python solutions, and it would be much more reliable because the header would be being parsed by the C compilers parser.
A:
You don't really provide much information about how what is to be modified should be determined, but to address your specific example:
$ perl -pi.bak -we'if ( /const BYTE Some_Idx/ .. /;/ ) { s/Some_Idx/Some_Idx_Mod_mul_2/g; s/(\d+)/$1 * 2/ge; }' header.h
Breaking that down, -p says loop through input files, putting each line in $_, running the supplied code, then printing $_. -i.bak enables in-place editing, renaming each original file with a .bak suffix and printing to a new file named whatever the original was. -w enables warnings. -e'....' supplies the code to be run for each input line. header.h is the only input file.
In the perl code, if ( /const BYTE Some_Idx/ .. /;/ ) checks that we are in a range of lines beginning with a line matching /const BYTE Some_Idx/ and ending with a line matching /;/.
s/.../.../g does a substitution as many times as possible. /(\d+)/ matches a series of digits. The /e flag says the result ($1 * 2) is code that should be evaluated to produce a replacement string, instead of simply a replacement string. $1 is the digits that should be replaced.
A:
If all you need to do is to modify structs, you can directly use regex to split and apply changes to each value in the struct, looking for the declaration and the ending }; to know when to stop.
If you really need a more general solution you could use a parser generator, like PyParsing
A:
There is a Perl module called Parse::RecDescent which is a very powerful recursive descent parser generator. It comes with a bunch of examples. One of them is a grammar that can parse C.
Now, I don't think this matters in your case, but the recursive descent parsers using Parse::RecDescent are algorithmically slower (O(n^2), I think) than tools like Parse::Yapp or Parse::EYapp. I haven't checked whether Parse::EYapp comes with such a C-parser example, but if so, that's the tool I'd recommend learning.
A:
Python solution (not full, just a hint ;)) Sorry if any mistakes - not tested
import re
text = open('your file.c').read()
patt = r'(?is)(.*?{)(.*?)(}\s*;)'
m = re.search(patt, text)
g1, g2, g3 = m.group(1), m.group(2), m.group(3)
g2 = [int(i) * 2 for i in g2.split(',')
out = open('your file 2.c', 'w')
out.write(g1, ','.join(g2), g3)
out.close()
A:
There is a really useful Perl module called Convert::Binary::C that parses C header files and converts structs from/to Perl data structures.
A:
You could always use pack / unpack, to read, and write the data.
#! /usr/bin/env perl
use strict;
use warnings;
use autodie;
my @data;
{
open( my $file, '<', 'Some_Idx.bin' );
local $/ = \1; # read one byte at a time
while( my $byte = <$file> ){
push @data, unpack('C',$byte);
}
close( $file );
}
print join(',', @data), "\n";
{
open( my $file, '>', 'Some_Idx_Mod_mul_2.bin' );
# You have two options
for my $byte( @data ){
print $file pack 'C', $byte * 2;
}
# or
print $file pack 'C*', map { $_ * 2 } @data;
close( $file );
}
A:
For the GCC::TranslationUnit example see hparse.pl from http://gist.github.com/395160
which will make it into C::DynaLib, and the not yet written Ctypes also.
This parses functions for FFI's, and not bare structs contrary to Convert::Binary::C.
hparse will only add structs if used as func args.
| How can I parse a C header file with Perl? | I have a header file in which there is a large struct. I need to read this structure using some program and make some operations on each member of the structure and write them back.
For example I have some structure like
const BYTE Some_Idx[] = {
4,7,10,15,17,19,24,29,
31,32,35,45,49,51,52,54,
55,58,60,64,65,66,67,69,
70,72,76,77,81,82,83,85,
88,93,94,95,97,99,102,103,
105,106,113,115,122,124,125,126,
129,131,137,139,140,149,151,152,
153,155,158,159,160,163,165,169,
174,175,181,182,183,189,190,193,
197,201,204,206,208,210,211,212,
213,214,215,217,218,219,220,223,
225,228,230,234,236,237,240,241,
242,247,249};
Now, I need to read this and apply some operation on each of the member variable and create a new structure with different order, something like:
const BYTE Some_Idx_Mod_mul_2[] = {
8,14,20, ...
...
484,494,498};
Is there any Perl library already available for this? If not Perl, something else like Python is also OK.
Can somebody please help!!!
| [
"Keeping your data lying around in a header makes it trickier to get at using other programs like Perl. Another approach you might consider is to keep this data in a database or another file and regenerate your header file as-needed, maybe even as part of your build system. The reason for this is that generating C is much easier than parsing C, it's trivial to write a script that parses a text file and makes a header for you, and such a script could even be invoked from your build system. \nAssuming that you want to keep your data in a C header file, you will need one of two things to solve this problem:\n\na quick one-off script to parse exactly (or close to exactly) the input you describe. \na general, well-written script that can parse arbitrary C and work generally on to lots of different headers. \n\nThe first case seems more common than the second to me, but it's hard to tell from your question if this is better solved by a script that needs to parse arbitrary C or a script that needs to parse this specific file. For code that works on your specific case, the following works for me on your input:\n#!/usr/bin/perl -w\n\nuse strict;\n\nopen FILE, \"<header.h\" or die $!;\nmy @file = <FILE>;\nclose FILE or die $!;\n\nmy $in_block = 0;\nmy $regex = 'Some_Idx\\[\\]';\nmy $byte_line = '';\nmy @byte_entries;\nforeach my $line (@file) {\n chomp $line;\n\n if ( $line =~ /$regex.*\\{(.*)/ ) {\n $in_block = 1;\n my @digits = @{ match_digits($1) };\n push @digits, @byte_entries;\n next;\n }\n\n if ( $in_block ) {\n my @digits = @{ match_digits($line) };\n push @byte_entries, @digits;\n }\n\n if ( $line =~ /\\}/ ) {\n $in_block = 0;\n }\n}\n\nprint \"const BYTE Some_Idx_Mod_mul_2[] = {\\n\";\nprint join \",\", map { $_ * 2 } @byte_entries;\nprint \"};\\n\";\n\nsub match_digits {\n my $text = shift;\n my @digits;\n while ( $text =~ /(\\d+),*/g ) {\n push @digits, $1;\n }\n\n return \\@digits;\n}\n\nParsing arbitrary C is a little tricky and not worth it for many applications, but maybe you need to actually do this. One trick is to let GCC do the parsing for you and read in GCC's parse tree using a CPAN module named GCC::TranslationUnit. \nHere's the GCC command to compile the code, assuming you have a single file named test.c:\ngcc -fdump-translation-unit -c test.c \nHere's the Perl code to read in the parse tree:\n use GCC::TranslationUnit;\n\n # echo '#include <stdio.h>' > stdio.c\n # gcc -fdump-translation-unit -c stdio.c\n $node = GCC::TranslationUnit::Parser->parsefile('stdio.c.tu')->root;\n\n # list every function/variable name\n while($node) {\n if($node->isa('GCC::Node::function_decl') or\n $node->isa('GCC::Node::var_decl')) {\n printf \"%s declared in %s\\n\",\n $node->name->identifier, $node->source;\n }\n } continue {\n $node = $node->chain;\n }\n\n",
"Sorry if this is a stupid question, but why worry about parsing the file at all? Why not write a C program that #includes the header, processes it as required and then spits out the source for the modified header. I'm sure this would be simpler than the Perl/Python solutions, and it would be much more reliable because the header would be being parsed by the C compilers parser.\n",
"You don't really provide much information about how what is to be modified should be determined, but to address your specific example:\n$ perl -pi.bak -we'if ( /const BYTE Some_Idx/ .. /;/ ) { s/Some_Idx/Some_Idx_Mod_mul_2/g; s/(\\d+)/$1 * 2/ge; }' header.h\n\nBreaking that down, -p says loop through input files, putting each line in $_, running the supplied code, then printing $_. -i.bak enables in-place editing, renaming each original file with a .bak suffix and printing to a new file named whatever the original was. -w enables warnings. -e'....' supplies the code to be run for each input line. header.h is the only input file.\nIn the perl code, if ( /const BYTE Some_Idx/ .. /;/ ) checks that we are in a range of lines beginning with a line matching /const BYTE Some_Idx/ and ending with a line matching /;/.\ns/.../.../g does a substitution as many times as possible. /(\\d+)/ matches a series of digits. The /e flag says the result ($1 * 2) is code that should be evaluated to produce a replacement string, instead of simply a replacement string. $1 is the digits that should be replaced.\n",
"If all you need to do is to modify structs, you can directly use regex to split and apply changes to each value in the struct, looking for the declaration and the ending }; to know when to stop.\nIf you really need a more general solution you could use a parser generator, like PyParsing\n",
"There is a Perl module called Parse::RecDescent which is a very powerful recursive descent parser generator. It comes with a bunch of examples. One of them is a grammar that can parse C.\nNow, I don't think this matters in your case, but the recursive descent parsers using Parse::RecDescent are algorithmically slower (O(n^2), I think) than tools like Parse::Yapp or Parse::EYapp. I haven't checked whether Parse::EYapp comes with such a C-parser example, but if so, that's the tool I'd recommend learning.\n",
"Python solution (not full, just a hint ;)) Sorry if any mistakes - not tested\nimport re\ntext = open('your file.c').read()\npatt = r'(?is)(.*?{)(.*?)(}\\s*;)'\nm = re.search(patt, text)\ng1, g2, g3 = m.group(1), m.group(2), m.group(3)\ng2 = [int(i) * 2 for i in g2.split(',')\nout = open('your file 2.c', 'w')\nout.write(g1, ','.join(g2), g3)\nout.close()\n\n",
"There is a really useful Perl module called Convert::Binary::C that parses C header files and converts structs from/to Perl data structures.\n",
"You could always use pack / unpack, to read, and write the data.\n#! /usr/bin/env perl\nuse strict;\nuse warnings;\nuse autodie;\n\nmy @data;\n{\n open( my $file, '<', 'Some_Idx.bin' );\n\n local $/ = \\1; # read one byte at a time\n\n while( my $byte = <$file> ){\n push @data, unpack('C',$byte);\n }\n close( $file );\n}\n\nprint join(',', @data), \"\\n\";\n\n{\n open( my $file, '>', 'Some_Idx_Mod_mul_2.bin' );\n\n # You have two options\n for my $byte( @data ){\n print $file pack 'C', $byte * 2;\n }\n # or\n print $file pack 'C*', map { $_ * 2 } @data;\n\n close( $file );\n}\n\n",
"For the GCC::TranslationUnit example see hparse.pl from http://gist.github.com/395160\nwhich will make it into C::DynaLib, and the not yet written Ctypes also.\nThis parses functions for FFI's, and not bare structs contrary to Convert::Binary::C. \nhparse will only add structs if used as func args.\n"
] | [
10,
6,
4,
3,
2,
2,
2,
0,
0
] | [] | [] | [
"c",
"header_files",
"parsing",
"perl",
"python"
] | stackoverflow_0000994732_c_header_files_parsing_perl_python.txt |
Q:
twisted reactor stops too early
I'm doing a batch script to connect to a tcp server and then exiting.
My problem is that I can't stop the reactor, for example:
cmd = raw_input("Command: ")
# custom factory, the protocol just send a line
reactor.connectTCP(HOST,PORT, CommandClientFactory(cmd)
d = defer.Deferred()
d.addCallback(lambda x: reactor.stop())
reactor.callWhenRunning(d.callback,None)
reactor.run()
In this code the reactor stops before that the tcp connection is done and the cmd is passed.
How can I stop the reactor after that all the operation are finished?
A:
The simple solution is to call reactor.stop() at the point in your code when you detect your exit condition. Specifically, it would look like you'd want to call it somewhere within CommandClient after, I'm assuming, it sends your command to the remote machine and receives back the command's exit code.
As written, the reactor will start up and immediately execute d.callback which will, in turn, call reactor.stop(). There's no link between your program's logic and the call to reactor.stop(). Move the call into your program's core logic and you should be set. Specifically, I'd look at your CommandClient protocol's connectionMade() & dataReceived() methods as probable candidates for detecting your "im done" condition.
| twisted reactor stops too early | I'm doing a batch script to connect to a tcp server and then exiting.
My problem is that I can't stop the reactor, for example:
cmd = raw_input("Command: ")
# custom factory, the protocol just send a line
reactor.connectTCP(HOST,PORT, CommandClientFactory(cmd)
d = defer.Deferred()
d.addCallback(lambda x: reactor.stop())
reactor.callWhenRunning(d.callback,None)
reactor.run()
In this code the reactor stops before that the tcp connection is done and the cmd is passed.
How can I stop the reactor after that all the operation are finished?
| [
"The simple solution is to call reactor.stop() at the point in your code when you detect your exit condition. Specifically, it would look like you'd want to call it somewhere within CommandClient after, I'm assuming, it sends your command to the remote machine and receives back the command's exit code. \nAs written, the reactor will start up and immediately execute d.callback which will, in turn, call reactor.stop(). There's no link between your program's logic and the call to reactor.stop(). Move the call into your program's core logic and you should be set. Specifically, I'd look at your CommandClient protocol's connectionMade() & dataReceived() methods as probable candidates for detecting your \"im done\" condition.\n"
] | [
5
] | [] | [] | [
"networking",
"python",
"twisted"
] | stackoverflow_0002804381_networking_python_twisted.txt |
Q:
Is possible to auto-import a module from a different subfolder in other subfolder?
I have a kind of plugin system, with this layout:
Python
SDK
Plugins
Plugin1
Plugin2
All 3 have a __init__.py file. I wonder if is possible to be able to do import SDK from any plugin (as if SDK was in the site-packages folder).
I'm in a situation where need to deploy, update, delete, add or change SDK files or any of the plugins under non-admin accounts, and wonder if I can get SDK in a clean way (I could sys.path.append in all plugins but I wonder if exist a better option).
I imagine that using this in the Plugins init coulkd work:
import sys
import os
ROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),'..'))
print ROOT_DIR
sys.path.append( ROOT_DIR )
But clearly is not executed this code (I imagine __init__.py was auto-magicalled executed in the load of the module ☹)
A:
Python
start.py
from SDK.Plugins import Plugin1
print Plugin1.test()
SDK
__init__.py
Plugins
__init__.py
Plugin1.py
from SDK.Plugins import Plugin2
def test():
return Plugin2.test2()
Plugin2.py
def test2():
return "This worked!"
# python start.py
This worked!
This will work because in Plugin1.py you are doing an import relative to start.py, the executed script, not to itself.
If you were to execute directly Plugin1.py, you'd have to mess with the path, but if it's always going to be used from a script higher on the folder hierarchy, then this is the cleanest way to do it.
| Is possible to auto-import a module from a different subfolder in other subfolder? | I have a kind of plugin system, with this layout:
Python
SDK
Plugins
Plugin1
Plugin2
All 3 have a __init__.py file. I wonder if is possible to be able to do import SDK from any plugin (as if SDK was in the site-packages folder).
I'm in a situation where need to deploy, update, delete, add or change SDK files or any of the plugins under non-admin accounts, and wonder if I can get SDK in a clean way (I could sys.path.append in all plugins but I wonder if exist a better option).
I imagine that using this in the Plugins init coulkd work:
import sys
import os
ROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),'..'))
print ROOT_DIR
sys.path.append( ROOT_DIR )
But clearly is not executed this code (I imagine __init__.py was auto-magicalled executed in the load of the module ☹)
| [
"\nPython\n\nstart.py \nfrom SDK.Plugins import Plugin1\nprint Plugin1.test()\n\nSDK\n\n__init__.py\nPlugins\n\n__init__.py\nPlugin1.py\nfrom SDK.Plugins import Plugin2\ndef test():\n return Plugin2.test2()\n\nPlugin2.py\ndef test2():\n return \"This worked!\"\n\n\n\n\n\n\n# python start.py\nThis worked!\n\nThis will work because in Plugin1.py you are doing an import relative to start.py, the executed script, not to itself.\nIf you were to execute directly Plugin1.py, you'd have to mess with the path, but if it's always going to be used from a script higher on the folder hierarchy, then this is the cleanest way to do it.\n"
] | [
2
] | [] | [] | [
"path",
"plugins",
"python"
] | stackoverflow_0002804625_path_plugins_python.txt |
Q:
How to "signal" interested child processes (without signals)?
I'm trying to find a good and simple method to signal child processes
(created through SocketServer with ForkingMixIn) from the parent
process.
While Unix signals could be used, I want to avoid them since only
children who are interested should receive the signal, and it would be
overkill and complicated to require some kind of registration
mechanism to identify to the parent process who is interested.
(Please don't suggest threads, as this particular program won't work
with threads, and thus has to use forks.)
A:
Since you are on a unix system, semaphores should be the easy answer.
Unfortunately, python does not seem to offer a way to call the semop system call.
If you are using python 2.6 , you may be able to use the
multiprocessing module Condition class.
A:
I have come up with the idea of using a pipe file descriptor that the parent could write and then read/flush in combination with select, but this doesn't really qualify as a very elegant design.
In more detail: The parent would create a pipe, the subprocesses would inherit it, the parent process would write to the pipe, thereby waking up any subprocess select():ing on the file descriptor, but the parent would then immediately read from the read end of the pipe and empty it - the only effect being that those child processes that were select():ing on the pipe have woken up.
As I said, this feels odd and ugly, but I haven't found anything really better yet.
Edit:
It turns out that this doesn't work - some child processes are woken up and some aren't. I've resorted to using a Condition from the multiprocessing module.
| How to "signal" interested child processes (without signals)? | I'm trying to find a good and simple method to signal child processes
(created through SocketServer with ForkingMixIn) from the parent
process.
While Unix signals could be used, I want to avoid them since only
children who are interested should receive the signal, and it would be
overkill and complicated to require some kind of registration
mechanism to identify to the parent process who is interested.
(Please don't suggest threads, as this particular program won't work
with threads, and thus has to use forks.)
| [
"Since you are on a unix system, semaphores should be the easy answer.\nUnfortunately, python does not seem to offer a way to call the semop system call.\nIf you are using python 2.6 , you may be able to use the\nmultiprocessing module Condition class.\n",
"I have come up with the idea of using a pipe file descriptor that the parent could write and then read/flush in combination with select, but this doesn't really qualify as a very elegant design.\nIn more detail: The parent would create a pipe, the subprocesses would inherit it, the parent process would write to the pipe, thereby waking up any subprocess select():ing on the file descriptor, but the parent would then immediately read from the read end of the pipe and empty it - the only effect being that those child processes that were select():ing on the pipe have woken up.\nAs I said, this feels odd and ugly, but I haven't found anything really better yet.\nEdit:\nIt turns out that this doesn't work - some child processes are woken up and some aren't. I've resorted to using a Condition from the multiprocessing module.\n"
] | [
3,
2
] | [] | [] | [
"fork",
"python",
"signals",
"subprocess",
"unix"
] | stackoverflow_0002804964_fork_python_signals_subprocess_unix.txt |
Q:
How to build sqlite for Python 2.4?
I would like to use pysqlite interface between Python and sdlite database. I have already Python and SQLite on my computer. But I have troubles with installation of pysqlite. During the installation I get the following error message:
error: command 'gcc' failed with exit status 1
As far as I understood the problems appears because version of my Python is 2.4.3 and SQLite is integrated in Python since 2.5. However, I also found out that it IS possible to build sqlite for Python 2.4 (using some tricks, probably).
Does anybody know how to build sqlite for Python 2.4?
As another option I could try to install higher version of Python. However I do not have root privileges. Does anybody know what will be the easiest way to solve the problem (build SQLite fro Python 2.4, or install newer version of Python)? I have to mention that I would not like to overwrite the old version version of Python.
Thank you in advance.
A:
You can download and install Python to your home directory.
$ cd
$ mkdir opt
$ mkdir downloads
$ cd downloads
$ wget http://www.python.org/ftp/python/2.6.2/Python-2.6.2.tgz
$ tar xvzf Python-2.6.2.tgz
$ cd Python-2.6.2
$ ./configure --prefix=$HOME/opt/ --enable-unicode=ucs4
$ make
$ make install
Then, (if you are using bash) in your .bash_profile do
export PATH=$HOME/opt/bin/:$PATH
export PYTHONPATH=$HOME/opt/lib:$HOME/opt/lib/site-packages:$PYTHONPATH
Then, source the file to make it available
$ cd
$ source .bash_profile
$ python -V
where python -V will return the python version. If the correct version appears, any packages that you run with Python's setup.py util (assuming the developer followed the correct conventions) will install in ~/opt/lib/python2.x/site-packages directory.
A:
Download pysqlite here, cd into the directory you downloaded to, unpack the tarball:
$ tar xzf pysqlite-2.5.5.tar.gz
then just do (if your permissions are set right for this; may need sudo otherwise):
$ cd pysqlite-2.5.5
$ python2.4 setup.py install
one error does appear in the copious output:
File "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/site-packages/pysqlite2/test/py25tests.py", line 48
with self.con:
^
SyntaxError: invalid syntax
since as clearly shown that file is for py 2.5 tests only (with statement not present in 2.4!-). Nevertheless the install is successful:
$ python2.4 -c'import pysqlite2'
$
All this is on Mac OS X 10.5 but using python2.4 separately installed from the system-supplied Python 2.5.
The error you report doesn't tell us much -- maybe you're missing the headers or libraries for sqlite itself? Can you show us other output lines around that single error msg...?
A:
If you don't have root privileges, I would recommend installing a more recent version of Python in your home directory and then adding your local version to your PATH. It seems easier to go that direction than to try to make sqlite work with an old version of Python.
You will also be doing yourself a favor by using a recent version of Python, because you'll have access to the numerous recent improvements in the language.
A:
I had the same trouble with gcc failing with Ubuntu Karmic. I fixed this by installing the python-dev package. In my case, I'm working with python2.4, so I installed the python2.4-dev package. The python-dev package should work for python2.6.
| How to build sqlite for Python 2.4? | I would like to use pysqlite interface between Python and sdlite database. I have already Python and SQLite on my computer. But I have troubles with installation of pysqlite. During the installation I get the following error message:
error: command 'gcc' failed with exit status 1
As far as I understood the problems appears because version of my Python is 2.4.3 and SQLite is integrated in Python since 2.5. However, I also found out that it IS possible to build sqlite for Python 2.4 (using some tricks, probably).
Does anybody know how to build sqlite for Python 2.4?
As another option I could try to install higher version of Python. However I do not have root privileges. Does anybody know what will be the easiest way to solve the problem (build SQLite fro Python 2.4, or install newer version of Python)? I have to mention that I would not like to overwrite the old version version of Python.
Thank you in advance.
| [
"You can download and install Python to your home directory. \n$ cd\n$ mkdir opt\n$ mkdir downloads\n$ cd downloads\n$ wget http://www.python.org/ftp/python/2.6.2/Python-2.6.2.tgz\n$ tar xvzf Python-2.6.2.tgz\n$ cd Python-2.6.2\n$ ./configure --prefix=$HOME/opt/ --enable-unicode=ucs4\n$ make\n$ make install\n\nThen, (if you are using bash) in your .bash_profile do\nexport PATH=$HOME/opt/bin/:$PATH\nexport PYTHONPATH=$HOME/opt/lib:$HOME/opt/lib/site-packages:$PYTHONPATH\n\nThen, source the file to make it available\n$ cd\n$ source .bash_profile\n$ python -V\n\nwhere python -V will return the python version. If the correct version appears, any packages that you run with Python's setup.py util (assuming the developer followed the correct conventions) will install in ~/opt/lib/python2.x/site-packages directory.\n",
"Download pysqlite here, cd into the directory you downloaded to, unpack the tarball:\n$ tar xzf pysqlite-2.5.5.tar.gz \n\nthen just do (if your permissions are set right for this; may need sudo otherwise):\n$ cd pysqlite-2.5.5\n$ python2.4 setup.py install\n\none error does appear in the copious output:\n File \"/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/site-packages/pysqlite2/test/py25tests.py\", line 48\n with self.con:\n ^\nSyntaxError: invalid syntax\n\nsince as clearly shown that file is for py 2.5 tests only (with statement not present in 2.4!-). Nevertheless the install is successful:\n$ python2.4 -c'import pysqlite2'\n$\n\nAll this is on Mac OS X 10.5 but using python2.4 separately installed from the system-supplied Python 2.5.\nThe error you report doesn't tell us much -- maybe you're missing the headers or libraries for sqlite itself? Can you show us other output lines around that single error msg...?\n",
"If you don't have root privileges, I would recommend installing a more recent version of Python in your home directory and then adding your local version to your PATH. It seems easier to go that direction than to try to make sqlite work with an old version of Python.\nYou will also be doing yourself a favor by using a recent version of Python, because you'll have access to the numerous recent improvements in the language.\n",
"I had the same trouble with gcc failing with Ubuntu Karmic. I fixed this by installing the python-dev package. In my case, I'm working with python2.4, so I installed the python2.4-dev package. The python-dev package should work for python2.6.\n"
] | [
1,
1,
0,
0
] | [] | [] | [
"pysqlite",
"python",
"sqlite"
] | stackoverflow_0001455642_pysqlite_python_sqlite.txt |
Q:
How to compile Python scripts for use in FORTRAN?
Although I found many answers and discussions about this question, I am unable to find a solution particular to my situation. Here it is:
I have a main program written in FORTRAN.
I have been given a set of python scripts that are very useful.
My goal is to access these python scripts from my main FORTRAN program. Currently, I simply call the scripts from FORTRAN as such:
CALL SYSTEM ('python pyexample.py')
Data is read from .dat files and written to .dat files. This is how the python scripts and the main FORTRAN program communicate to each other.
I am currently running my code on my local machine. I have python installed with numpy, scipy, etc.
My problem:
The code needs to run on a remote server. For strictly FORTRAN code, I compile the code locally and send the executable to the server where it waits in a queue. However, the server does not have python installed. The server is being used as a number crunching station between universities and industry. Installing python along with the necessary modules on the server is not an option. This means that my “CALL SYSTEM ('python pyexample.py')” strategy no longer works.
Solution?:
I found some information on a couple of things in thread Is it feasible to compile Python to machine code?
Shedskin, Psyco, Cython, Pypy, Cpython API
These “modules”(? Not sure if that's what to call them) seem to compile python script to C code or C++. Apparently not all python features can be translated to C. As well, some of these appear to be experimental. Is it possible to compile my python scripts with my FORTRAN code? There exists f2py which converts FORTRAN code to python, but it doesn't work the other way around.
Any help would be greatly appreciated. Thank you for your time.
Vincent
PS: I'm using python 2.6 on Ubuntu
A:
One way or another, you'll need to get the Python runtime on your server, otherwise it won't be possible to execute Python bytecode. Ignacio is on the right track with suggesting invoking libpython directly, but due to Fortran's parameter-passing conventions, it will be a lot easier for you to write a C wrapper to handle the interface between Fortran and the CPython embedding API.
Unfortunately, you're doing this the hard way -- it's a lot easier to write a Python program that can call Fortran subroutines than the other way around.
A:
You don't want any of those. What you should do is use FORTRAN's FFI to talk with libpython and frob its API.
| How to compile Python scripts for use in FORTRAN? | Although I found many answers and discussions about this question, I am unable to find a solution particular to my situation. Here it is:
I have a main program written in FORTRAN.
I have been given a set of python scripts that are very useful.
My goal is to access these python scripts from my main FORTRAN program. Currently, I simply call the scripts from FORTRAN as such:
CALL SYSTEM ('python pyexample.py')
Data is read from .dat files and written to .dat files. This is how the python scripts and the main FORTRAN program communicate to each other.
I am currently running my code on my local machine. I have python installed with numpy, scipy, etc.
My problem:
The code needs to run on a remote server. For strictly FORTRAN code, I compile the code locally and send the executable to the server where it waits in a queue. However, the server does not have python installed. The server is being used as a number crunching station between universities and industry. Installing python along with the necessary modules on the server is not an option. This means that my “CALL SYSTEM ('python pyexample.py')” strategy no longer works.
Solution?:
I found some information on a couple of things in thread Is it feasible to compile Python to machine code?
Shedskin, Psyco, Cython, Pypy, Cpython API
These “modules”(? Not sure if that's what to call them) seem to compile python script to C code or C++. Apparently not all python features can be translated to C. As well, some of these appear to be experimental. Is it possible to compile my python scripts with my FORTRAN code? There exists f2py which converts FORTRAN code to python, but it doesn't work the other way around.
Any help would be greatly appreciated. Thank you for your time.
Vincent
PS: I'm using python 2.6 on Ubuntu
| [
"One way or another, you'll need to get the Python runtime on your server, otherwise it won't be possible to execute Python bytecode. Ignacio is on the right track with suggesting invoking libpython directly, but due to Fortran's parameter-passing conventions, it will be a lot easier for you to write a C wrapper to handle the interface between Fortran and the CPython embedding API.\nUnfortunately, you're doing this the hard way -- it's a lot easier to write a Python program that can call Fortran subroutines than the other way around.\n",
"You don't want any of those. What you should do is use FORTRAN's FFI to talk with libpython and frob its API.\n"
] | [
3,
2
] | [] | [] | [
"compilation",
"fortran",
"python"
] | stackoverflow_0002805244_compilation_fortran_python.txt |
Q:
regular expression search in python
I am trying to parse some data and just started reading up on regular Expressions so I am pretty new to it. This is the code I have so far
String = "MEASUREMENT 3835 303 Oxygen: 235.78 Saturation: 90.51 Temperature: 24.41 DPhase: 33.07 BPhase: 29.56 RPhase: 0.00 BAmp: 368.57 BPot: 18.00 RAmp: 0.00 RawTem.: 68.21"
String = String.strip('\t\x11\x13')
String = String.split("Oxygen:")
print String[1]
String[1].lstrip
print String[1]
What I am trying to do is to do is remove the oxygen data (235.78) and put it in its own variable using an regular expression search. I realize that there should be an easy solution but I am trying to figure out how regular expressions work and they are making my head hurt. Thanks for any help
Richard
A:
re.search( r"Oxygen: *([\d.]+)", String ).group( 1 )
A:
import re
string = "blabla Oxygen: 10.10 blabla"
regex_oxygen = re.compile('''Oxygen:\W+([0-9.]*)''')
result = re.findall(regex_oxygen,string)
print result
A:
What for?
print String.split()[4]
A:
For general parsing of lists like this one could
import re
String = "MEASUREMENT 3835 303 Oxygen: 235.78 Saturation: 90.51"
String = String.replace(':','')
value_list=re.split("MEASUREMENT\W+[0-9]+\W+[0-9]+\W",String)[1].rstrip().split()
values = dict(zip(value_list[::2],map(float,value_list[1::2])))
A:
I believe the answer to you specific problem has been posted. However I wanted to show you a few ressource for regular expression for python. The python documentation on regular expression is the place to start.
O'reilly also has many good books on the subject, either if you want to understand regular expression deep down or just enough to make things work.
Finally regular-expressions.info is a good ressource for regular expression among mainstream languages. You can even test your regular expression on the website.
| regular expression search in python | I am trying to parse some data and just started reading up on regular Expressions so I am pretty new to it. This is the code I have so far
String = "MEASUREMENT 3835 303 Oxygen: 235.78 Saturation: 90.51 Temperature: 24.41 DPhase: 33.07 BPhase: 29.56 RPhase: 0.00 BAmp: 368.57 BPot: 18.00 RAmp: 0.00 RawTem.: 68.21"
String = String.strip('\t\x11\x13')
String = String.split("Oxygen:")
print String[1]
String[1].lstrip
print String[1]
What I am trying to do is to do is remove the oxygen data (235.78) and put it in its own variable using an regular expression search. I realize that there should be an easy solution but I am trying to figure out how regular expressions work and they are making my head hurt. Thanks for any help
Richard
| [
"re.search( r\"Oxygen: *([\\d.]+)\", String ).group( 1 )\n\n",
"import re\nstring = \"blabla Oxygen: 10.10 blabla\"\nregex_oxygen = re.compile('''Oxygen:\\W+([0-9.]*)''')\nresult = re.findall(regex_oxygen,string)\nprint result\n\n",
"What for?\nprint String.split()[4]\n\n",
"For general parsing of lists like this one could\nimport re\nString = \"MEASUREMENT 3835 303 Oxygen: 235.78 Saturation: 90.51\"\nString = String.replace(':','')\nvalue_list=re.split(\"MEASUREMENT\\W+[0-9]+\\W+[0-9]+\\W\",String)[1].rstrip().split()\nvalues = dict(zip(value_list[::2],map(float,value_list[1::2])))\n\n",
"I believe the answer to you specific problem has been posted. However I wanted to show you a few ressource for regular expression for python. The python documentation on regular expression is the place to start. \nO'reilly also has many good books on the subject, either if you want to understand regular expression deep down or just enough to make things work.\nFinally regular-expressions.info is a good ressource for regular expression among mainstream languages. You can even test your regular expression on the website.\n"
] | [
2,
1,
0,
0,
0
] | [
"I would like to share my ?is this an email? regex expresion, just to inspire you. :)\n 9 emailregex = \"^[a-zA-Z.a-zA-Z]+@mycompany.org$\"\n 10\n 11 def validateEmail(email):\n 12 \"\"\"returns 1 if is an email, 0 if not \"\"\"\n 13 # len(x.y@mycompany.org) = 17\n 14 if len(email)>=17:\n 15 if re.match(emailregex,email)!= None:\n 16 return 1\n 17 return 0\n\n"
] | [
-1
] | [
"python",
"regex",
"string"
] | stackoverflow_0002803923_python_regex_string.txt |
Q:
Django: Applying Calculations To A Query Set
I have a QuerySet that I wish to pass to a generic view for pagination:
links = Link.objects.annotate(votes=Count('vote')).order_by('-created')[:300]
This is my "hot" page which lists my 300 latest submissions (10 pages of 30 links each). I want to now sort this QuerySet by an algorithm that HackerNews uses:
(p - 1) / (t + 2)^1.5
p = votes minus submitter's initial vote
t = age of submission in hours
Now because applying this algorithm over the entire database would be pretty costly I am content with just the last 300 submissions. My site is unlikely to be the next digg/reddit so while scalability is a plus it is required.
My question is now how do I iterate over my QuerySet and sort it by the above algorithm?
For more information, here are my applicable models:
class Link(models.Model):
category = models.ForeignKey(Category, blank=False, default=1)
user = models.ForeignKey(User)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
url = models.URLField(max_length=1024, unique=True, verify_exists=True)
name = models.CharField(max_length=512)
def __unicode__(self):
return u'%s (%s)' % (self.name, self.url)
class Vote(models.Model):
link = models.ForeignKey(Link)
user = models.ForeignKey(User)
created = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return u'%s vote for %s' % (self.user, self.link)
Notes:
I don't have "downvotes" so just the presence of a Vote row is an indicator of a vote or a particular link by a particular user.
EDIT
I think I have been overcomplicating things and found out a nifty little piece of code:
links = Link.objects.annotate(votes=Count('vote')).order_by('-created')[:300]
for link in links:
link.popularity = ((link.votes - 1) / (2 + 2)**1.5)
But for the life of me I cannot get that to translate to my templates:
{% for link in object_list %}
Popularity: {{ link.popularity }}
{% endfor %}
Why is it not showing up? I know popularity is working because:
print 'LinkID: %s - Votes: %s - Popularity: %s' % (link.id, link.votes, link.popularity)
returns what I'd expect in console.
A:
You can make a values dict or values list from your QuerySet if it's possible and apply your sorting algorithm to the dict(list) obtained.
See
http://docs.djangoproject.com/en/dev/ref/models/querysets/#values-fields
http://docs.djangoproject.com/en/dev/ref/models/querysets/#values-list-fields
Example
# select links
links = Link.objects.annotate(votes=Count('vote')).order_by('-created')[:300]
# make a values list:
links = links.values_list('id', 'votes', 'created')
# now sort
# TODO: you need to properly format your created date (x[2]) here
list(links).sort(key = lambda x: (x[1] - 1) / (x[2] + 2)^1.5)
A:
qs = [obj1, obj2, obj3] # queryset
s = [] # will hold the sorted items
for obj in qs:
s.append(((obj.votes-1)/pow((obj.submision_age+2), 1.5), obj))
s.sort()
s.reverse()
Where s should end up sorted from highest calculated importancy first lowest last and looking like:
[(calculated importancy, obj), (calculated importancy, obj), ...]
A:
While was unable to calculate over a QuerySet, instead I had to convert into a list of sorts
links = Link.objects.select_related().annotate(votes=Count('vote'))
for link in links:
delta_in_hours = (int(datetime.now().strftime("%s")) - int(link.created.strftime("%s"))) / 3600
link.popularity = ((link.votes - 1) / (delta_in_hours + 2)**1.5)
links = sorted(links, key=lambda x: x.popularity, reverse=True)
Not optimal but it works. I can't use my lovely object_list generic view with it's automatically pagination and have to resort to doing it manually but it's a fair compromise to having a working view...
| Django: Applying Calculations To A Query Set | I have a QuerySet that I wish to pass to a generic view for pagination:
links = Link.objects.annotate(votes=Count('vote')).order_by('-created')[:300]
This is my "hot" page which lists my 300 latest submissions (10 pages of 30 links each). I want to now sort this QuerySet by an algorithm that HackerNews uses:
(p - 1) / (t + 2)^1.5
p = votes minus submitter's initial vote
t = age of submission in hours
Now because applying this algorithm over the entire database would be pretty costly I am content with just the last 300 submissions. My site is unlikely to be the next digg/reddit so while scalability is a plus it is required.
My question is now how do I iterate over my QuerySet and sort it by the above algorithm?
For more information, here are my applicable models:
class Link(models.Model):
category = models.ForeignKey(Category, blank=False, default=1)
user = models.ForeignKey(User)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
url = models.URLField(max_length=1024, unique=True, verify_exists=True)
name = models.CharField(max_length=512)
def __unicode__(self):
return u'%s (%s)' % (self.name, self.url)
class Vote(models.Model):
link = models.ForeignKey(Link)
user = models.ForeignKey(User)
created = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return u'%s vote for %s' % (self.user, self.link)
Notes:
I don't have "downvotes" so just the presence of a Vote row is an indicator of a vote or a particular link by a particular user.
EDIT
I think I have been overcomplicating things and found out a nifty little piece of code:
links = Link.objects.annotate(votes=Count('vote')).order_by('-created')[:300]
for link in links:
link.popularity = ((link.votes - 1) / (2 + 2)**1.5)
But for the life of me I cannot get that to translate to my templates:
{% for link in object_list %}
Popularity: {{ link.popularity }}
{% endfor %}
Why is it not showing up? I know popularity is working because:
print 'LinkID: %s - Votes: %s - Popularity: %s' % (link.id, link.votes, link.popularity)
returns what I'd expect in console.
| [
"You can make a values dict or values list from your QuerySet if it's possible and apply your sorting algorithm to the dict(list) obtained.\nSee\nhttp://docs.djangoproject.com/en/dev/ref/models/querysets/#values-fields\nhttp://docs.djangoproject.com/en/dev/ref/models/querysets/#values-list-fields\nExample\n# select links\nlinks = Link.objects.annotate(votes=Count('vote')).order_by('-created')[:300]\n# make a values list:\nlinks = links.values_list('id', 'votes', 'created')\n# now sort \n# TODO: you need to properly format your created date (x[2]) here\nlist(links).sort(key = lambda x: (x[1] - 1) / (x[2] + 2)^1.5)\n\n",
"qs = [obj1, obj2, obj3] # queryset\ns = [] # will hold the sorted items\nfor obj in qs:\n s.append(((obj.votes-1)/pow((obj.submision_age+2), 1.5), obj))\ns.sort()\ns.reverse()\n\nWhere s should end up sorted from highest calculated importancy first lowest last and looking like:\n[(calculated importancy, obj), (calculated importancy, obj), ...]\n",
"While was unable to calculate over a QuerySet, instead I had to convert into a list of sorts\nlinks = Link.objects.select_related().annotate(votes=Count('vote'))\nfor link in links:\n delta_in_hours = (int(datetime.now().strftime(\"%s\")) - int(link.created.strftime(\"%s\"))) / 3600\n link.popularity = ((link.votes - 1) / (delta_in_hours + 2)**1.5)\n\nlinks = sorted(links, key=lambda x: x.popularity, reverse=True)\n\nNot optimal but it works. I can't use my lovely object_list generic view with it's automatically pagination and have to resort to doing it manually but it's a fair compromise to having a working view...\n"
] | [
2,
1,
0
] | [] | [] | [
"algorithm",
"django",
"python",
"sorting"
] | stackoverflow_0002799198_algorithm_django_python_sorting.txt |
Q:
Regular expression works normally, but fails when placed in an XML schema
I have a simple doc.xml file which contains a single root element with a Timestamp attribute:
<?xml version="1.0" encoding="utf-8"?>
<root Timestamp="04-21-2010 16:00:19.000" />
I'd like to validate this document against a my simple schema.xsd to make sure that the Timestamp is in the correct format:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="root">
<xs:complexType>
<xs:attribute name="Timestamp" use="required" type="timeStampType"/>
</xs:complexType>
</xs:element>
<xs:simpleType name="timeStampType">
<xs:restriction base="xs:string">
<xs:pattern value="(0[0-9]{1})|(1[0-2]{1})-(3[0-1]{1}|[0-2]{1}[0-9]{1})-[2-9]{1}[0-9]{3} ([0-1]{1}[0-9]{1}|2[0-3]{1}):[0-5]{1}[0-9]{1}:[0-5]{1}[0-9]{1}.[0-9]{3}" />
</xs:restriction>
</xs:simpleType>
</xs:schema>
So I use the lxml Python module and try to perform a simple schema validation and report any errors:
from lxml import etree
schema = etree.XMLSchema( etree.parse("schema.xsd") )
doc = etree.parse("doc.xml")
if not schema.validate(doc):
for e in schema.error_log:
print e.message
My XML document fails validation with the following error messages:
Element 'root', attribute 'Timestamp': [facet 'pattern'] The value '04-21-2010 16:00:19.000' is not accepted by the pattern '(0[0-9]{1})|(1[0-2]{1})-(3[0-1]{1}|[0-2]{1}[0-9]{1})-[2-9]{1}[0-9]{3} ([0-1]{1}[0-9]{1}|2[0-3]{1}):[0-5]{1}[0-9]{1}:[0-5]{1}[0-9]{1}.[0-9]{3}'.
Element 'root', attribute 'Timestamp': '04-21-2010 16:00:19.000' is not a valid value of the atomic type 'timeStampType'.
So it looks like my regular expression must be faulty. But when I try to validate the regular expression at the command line, it passes:
>>> import re
>>> pat = '(0[0-9]{1})|(1[0-2]{1})-(3[0-1]{1}|[0-2]{1}[0-9]{1})-[2-9]{1}[0-9]{3} ([0-1]{1}[0-9]{1}|2[0-3]{1}):[0-5]{1}[0-9]{1}:[0-5]{1}[0-9]{1}.[0-9]{3}'
>>> assert re.match(pat, '04-21-2010 16:00:19.000')
>>>
I'm aware that XSD regular expressions don't have every feature, but the documentation I've found indicates that every feature that I'm using should work.
So what am I mis-understanding, and why does my document fail?
A:
Your |s match wider than you think.
(0[0-9]{1})|(1[0-2]{1})-(3[0-1]{1}|[0-2]{1}[0-9]{1})-[2-9]{1}[0-9]{3}
is parsed as:
(0[0-9]{1})
-or-
(1[0-2]{1})-(3[0-1]{1}|[0-2]{1}[0-9]{1})-[2-9]{1}[0-9]{3}
You need to use more groupings if you want to avoid it; e.g.
((0[0-9]{1})|(1[0-2]{1}))-((3[0-1]{1}|[0-2]{1}[0-9]{1}))-[2-9]{1}[0-9]{3} (([0-1]{1}[0-9]{1}|2[0-3]{1})):[0-5]{1}[0-9]{1}:[0-5]{1}[0-9]{1}.[0-9]{3}
A:
The expression has several errors.
You allow 00 as a valid month.
A|BC matches A and BC - not AC and BC. Hence your expression starting with (0[0-9]{1})| matches any string containing 00 through 09. What you want is (0[1-9]|1[0-2])- only matching 01 through 12 followed by a dash.
You allow 00 as a valid day.
The pattern is not anchored to the beginning and end of the text - add ^ and $. That is why your test using Python succeeded.
By the way - why don't you use xs:dateTime? It has a very similar format - yyyy-mm-ddThh:mm:ss.fff I think.
| Regular expression works normally, but fails when placed in an XML schema | I have a simple doc.xml file which contains a single root element with a Timestamp attribute:
<?xml version="1.0" encoding="utf-8"?>
<root Timestamp="04-21-2010 16:00:19.000" />
I'd like to validate this document against a my simple schema.xsd to make sure that the Timestamp is in the correct format:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="root">
<xs:complexType>
<xs:attribute name="Timestamp" use="required" type="timeStampType"/>
</xs:complexType>
</xs:element>
<xs:simpleType name="timeStampType">
<xs:restriction base="xs:string">
<xs:pattern value="(0[0-9]{1})|(1[0-2]{1})-(3[0-1]{1}|[0-2]{1}[0-9]{1})-[2-9]{1}[0-9]{3} ([0-1]{1}[0-9]{1}|2[0-3]{1}):[0-5]{1}[0-9]{1}:[0-5]{1}[0-9]{1}.[0-9]{3}" />
</xs:restriction>
</xs:simpleType>
</xs:schema>
So I use the lxml Python module and try to perform a simple schema validation and report any errors:
from lxml import etree
schema = etree.XMLSchema( etree.parse("schema.xsd") )
doc = etree.parse("doc.xml")
if not schema.validate(doc):
for e in schema.error_log:
print e.message
My XML document fails validation with the following error messages:
Element 'root', attribute 'Timestamp': [facet 'pattern'] The value '04-21-2010 16:00:19.000' is not accepted by the pattern '(0[0-9]{1})|(1[0-2]{1})-(3[0-1]{1}|[0-2]{1}[0-9]{1})-[2-9]{1}[0-9]{3} ([0-1]{1}[0-9]{1}|2[0-3]{1}):[0-5]{1}[0-9]{1}:[0-5]{1}[0-9]{1}.[0-9]{3}'.
Element 'root', attribute 'Timestamp': '04-21-2010 16:00:19.000' is not a valid value of the atomic type 'timeStampType'.
So it looks like my regular expression must be faulty. But when I try to validate the regular expression at the command line, it passes:
>>> import re
>>> pat = '(0[0-9]{1})|(1[0-2]{1})-(3[0-1]{1}|[0-2]{1}[0-9]{1})-[2-9]{1}[0-9]{3} ([0-1]{1}[0-9]{1}|2[0-3]{1}):[0-5]{1}[0-9]{1}:[0-5]{1}[0-9]{1}.[0-9]{3}'
>>> assert re.match(pat, '04-21-2010 16:00:19.000')
>>>
I'm aware that XSD regular expressions don't have every feature, but the documentation I've found indicates that every feature that I'm using should work.
So what am I mis-understanding, and why does my document fail?
| [
"Your |s match wider than you think.\n(0[0-9]{1})|(1[0-2]{1})-(3[0-1]{1}|[0-2]{1}[0-9]{1})-[2-9]{1}[0-9]{3}\n\nis parsed as:\n(0[0-9]{1})\n -or-\n(1[0-2]{1})-(3[0-1]{1}|[0-2]{1}[0-9]{1})-[2-9]{1}[0-9]{3}\n\nYou need to use more groupings if you want to avoid it; e.g.\n((0[0-9]{1})|(1[0-2]{1}))-((3[0-1]{1}|[0-2]{1}[0-9]{1}))-[2-9]{1}[0-9]{3} (([0-1]{1}[0-9]{1}|2[0-3]{1})):[0-5]{1}[0-9]{1}:[0-5]{1}[0-9]{1}.[0-9]{3}\n\n",
"The expression has several errors.\n\nYou allow 00 as a valid month.\nA|BC matches A and BC - not AC and BC. Hence your expression starting with (0[0-9]{1})| matches any string containing 00 through 09. What you want is (0[1-9]|1[0-2])- only matching 01 through 12 followed by a dash.\nYou allow 00 as a valid day.\nThe pattern is not anchored to the beginning and end of the text - add ^ and $. That is why your test using Python succeeded.\n\nBy the way - why don't you use xs:dateTime? It has a very similar format - yyyy-mm-ddThh:mm:ss.fff I think.\n"
] | [
3,
3
] | [] | [] | [
"lxml",
"python",
"regex",
"schema",
"validation"
] | stackoverflow_0002806399_lxml_python_regex_schema_validation.txt |
Q:
What's the best way to aggregate the boolean values of a Python dictionary?
For the following Python dictionary:
dict = {
'stackoverflow': True,
'superuser': False,
'serverfault': False,
'meta': True,
}
I want to aggregate the boolean values above into the following boolean expression:
dict['stackoverflow'] and dict['superuser'] and dict['serverfault'] and dict['meta']
The above should return me False. I'm using keys with known names above but I want it to work so that there can be a large number of unknown key names.
A:
in python 2.5+:
all(dict.itervalues())
in python 3+
all(dict.values())
dict is a bad variable name, though, because it is the name of a builtin type
Edit: add syntax for python 3 version. values() constructs a view in python 3, unlike 2.x where it builds the list in memory.
| What's the best way to aggregate the boolean values of a Python dictionary? | For the following Python dictionary:
dict = {
'stackoverflow': True,
'superuser': False,
'serverfault': False,
'meta': True,
}
I want to aggregate the boolean values above into the following boolean expression:
dict['stackoverflow'] and dict['superuser'] and dict['serverfault'] and dict['meta']
The above should return me False. I'm using keys with known names above but I want it to work so that there can be a large number of unknown key names.
| [
"in python 2.5+:\nall(dict.itervalues())\n\nin python 3+\nall(dict.values())\n\ndict is a bad variable name, though, because it is the name of a builtin type\nEdit: add syntax for python 3 version. values() constructs a view in python 3, unlike 2.x where it builds the list in memory.\n"
] | [
23
] | [] | [] | [
"python"
] | stackoverflow_0002806611_python.txt |
Q:
How to bind a double precision using psycopg2
I'm trying to bind a float to a postgresql double precision using psycopg2.
ele = 1.0/3.0
dic = {'name': 'test', 'ele': ele}
sql = '''insert into waypoints (name, elevation) values (%(name)s, %(ele)s)'''
cur = db.cursor()
cur.execute(sql, dic)
db.commit()
sql = """select elevation from waypoints where name = 'test'"""
cur.execute(sql_out)
ele_out = cur.fetchone()[0]
ele_out
0.33333333333300003
ele
0.33333333333333331
Obviously I don't need the precision, but I would like to be able to simply compare the values. I could use the struct module and save it as a string, but thought there should be a better way. Thanks
A:
The reason you're getting this problem is the following line of code:
sql = '''insert into waypoints (name, elevation) values (%(name)s, %(ele)s)'''
because when the float is converted into a string here, you don't get all of the digits that you're expecting. For instance,
str(ele)
produces
'0.333333333333'
Changing the line to
sql = '''insert into waypoints (name, elevation) values (%(name)s, %(ele).17f)'''
I believe will give you your desired result because
'%(ele).17f' % dic
produces
'0.33333333333333331'
| How to bind a double precision using psycopg2 | I'm trying to bind a float to a postgresql double precision using psycopg2.
ele = 1.0/3.0
dic = {'name': 'test', 'ele': ele}
sql = '''insert into waypoints (name, elevation) values (%(name)s, %(ele)s)'''
cur = db.cursor()
cur.execute(sql, dic)
db.commit()
sql = """select elevation from waypoints where name = 'test'"""
cur.execute(sql_out)
ele_out = cur.fetchone()[0]
ele_out
0.33333333333300003
ele
0.33333333333333331
Obviously I don't need the precision, but I would like to be able to simply compare the values. I could use the struct module and save it as a string, but thought there should be a better way. Thanks
| [
"The reason you're getting this problem is the following line of code:\nsql = '''insert into waypoints (name, elevation) values (%(name)s, %(ele)s)'''\n\nbecause when the float is converted into a string here, you don't get all of the digits that you're expecting. For instance, \nstr(ele)\n\nproduces\n'0.333333333333'\n\nChanging the line to \nsql = '''insert into waypoints (name, elevation) values (%(name)s, %(ele).17f)'''\n\nI believe will give you your desired result because \n'%(ele).17f' % dic\n\nproduces\n'0.33333333333333331'\n\n"
] | [
0
] | [] | [] | [
"psycopg2",
"python"
] | stackoverflow_0002806517_psycopg2_python.txt |
Q:
On a Mac w/ Python2.6 and trying to install psycopg2
I am new to Python. I have Python2.6 running now. I am following the Tutorial on the Python site. My question is when I try to follow the instructions here:
http://py-psycopg.darwinports.com/
I get something like...
sudo port install py-psycopg
... bunch of errors here...
Error: The following dependencies failed to build: py-mx python24
I am running MacOS X 10.4.
How do i make this work?
Any reply would be greatly appreciated.
UPDATE:
After running the code below I get the errors below:
$ sudo port install py26-psycopg2
Warning: Skipping upgrade since openssl 0.9.8k_0 >= openssl 0.9.8k_0, even though installed variants "" do not match "+darwin". Use 'upgrade --enforce-variants' to switch to the requested variants.
Warning: Skipping upgrade since readline 6.0.000_1 >= readline 6.0.000_1, even though installed variants "" do not match "+darwin". Use 'upgrade --enforce-variants' to switch to the requested variants.
---> Computing dependencies for py26-psycopg2
---> Building python26
Error: Target org.macports.build returned: shell command " cd "/opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_release_ports_lang_python26/work/Python-2.6.2" && /usr/bin/make all MAKE="/usr/bin/make CC=/usr/bin/gcc-4.0" " returned error 2
Command output: /usr/bin/install -c -d -m 755 Python.framework/Versions/2.6
if test ""; then \
/usr/bin/gcc-4.0 -o Python.framework/Versions/2.6/Python -dynamiclib \
-isysroot "" \
-all_load libpython2.6.a -Wl,-single_module \
-install_name /opt/local/Library/Frameworks/Python.framework/Versions/2.6/Python \
-compatibility_version 2.6 \
-current_version 2.6; \
else \
/usr/bin/libtool -o Python.framework/Versions/2.6/Python -dynamic libpython2.6.a \
-lSystem -lSystemStubs -install_name /opt/local/Library/Frameworks/Python.framework/Versions/2.6/Python -compatibility_version 2.6 -current_version 2.6 ;\
fi
ld64 failed: in libpython2.6.a(__.SYMDEF), not a valid ppc64 mach-o file
/usr/bin/libtool: internal link edit command failed
make: *** [Python.framework/Versions/2.6/Python] Error 1
Error: The following dependencies failed to build: python26
Error: Status 1 encountered during processing.
FYI, the python i installed was the dmg file from the pythong site.
Thanks,
Wenbert
A:
If you're using Python 2.6, you actually want to build py26-psycopg2:
$ sudo port install py26-psycopg2
In MacPorts, py-* packages build using Python 2.4, py25-* using Python 2.5, and py26-* use Python 2.6.
A:
Maybe you need to look at the version for Python 2.6?
A:
I had problems installing psycopg2 on my 10.4 Mac too. I installed both Python and Postgres from dmg files, and sudo easy_install psycopg2 was giving an error I can't remember now. What worked for me was an easy solution:
PATH=$PATH:/Library/PostgreSQL/8.3/bin/ sudo easy_install psycopg2
which I've found at http://blog.jonypawks.net/2008/06/20/installing-psycopg2-on-os-x/
A:
I installed psycopg2 on my Mac with setuptools and easy_install. First get the Python 2.6 egg from the setuptools downloads page, then install it with the instructions on that page. Then you can run the following to install it:
sudo easy_install psycopg2
You may have different luck, but that's what did it for me.
A:
I tried everything and nothing works. At least this post:
http://benkreeger.com/post/312303245/conquering-symbol-not-found-pqbackendpid
led me to homebrew which made it perfectly.
| On a Mac w/ Python2.6 and trying to install psycopg2 | I am new to Python. I have Python2.6 running now. I am following the Tutorial on the Python site. My question is when I try to follow the instructions here:
http://py-psycopg.darwinports.com/
I get something like...
sudo port install py-psycopg
... bunch of errors here...
Error: The following dependencies failed to build: py-mx python24
I am running MacOS X 10.4.
How do i make this work?
Any reply would be greatly appreciated.
UPDATE:
After running the code below I get the errors below:
$ sudo port install py26-psycopg2
Warning: Skipping upgrade since openssl 0.9.8k_0 >= openssl 0.9.8k_0, even though installed variants "" do not match "+darwin". Use 'upgrade --enforce-variants' to switch to the requested variants.
Warning: Skipping upgrade since readline 6.0.000_1 >= readline 6.0.000_1, even though installed variants "" do not match "+darwin". Use 'upgrade --enforce-variants' to switch to the requested variants.
---> Computing dependencies for py26-psycopg2
---> Building python26
Error: Target org.macports.build returned: shell command " cd "/opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_release_ports_lang_python26/work/Python-2.6.2" && /usr/bin/make all MAKE="/usr/bin/make CC=/usr/bin/gcc-4.0" " returned error 2
Command output: /usr/bin/install -c -d -m 755 Python.framework/Versions/2.6
if test ""; then \
/usr/bin/gcc-4.0 -o Python.framework/Versions/2.6/Python -dynamiclib \
-isysroot "" \
-all_load libpython2.6.a -Wl,-single_module \
-install_name /opt/local/Library/Frameworks/Python.framework/Versions/2.6/Python \
-compatibility_version 2.6 \
-current_version 2.6; \
else \
/usr/bin/libtool -o Python.framework/Versions/2.6/Python -dynamic libpython2.6.a \
-lSystem -lSystemStubs -install_name /opt/local/Library/Frameworks/Python.framework/Versions/2.6/Python -compatibility_version 2.6 -current_version 2.6 ;\
fi
ld64 failed: in libpython2.6.a(__.SYMDEF), not a valid ppc64 mach-o file
/usr/bin/libtool: internal link edit command failed
make: *** [Python.framework/Versions/2.6/Python] Error 1
Error: The following dependencies failed to build: python26
Error: Status 1 encountered during processing.
FYI, the python i installed was the dmg file from the pythong site.
Thanks,
Wenbert
| [
"If you're using Python 2.6, you actually want to build py26-psycopg2:\n$ sudo port install py26-psycopg2\n\nIn MacPorts, py-* packages build using Python 2.4, py25-* using Python 2.5, and py26-* use Python 2.6.\n",
"Maybe you need to look at the version for Python 2.6? \n",
"I had problems installing psycopg2 on my 10.4 Mac too. I installed both Python and Postgres from dmg files, and sudo easy_install psycopg2 was giving an error I can't remember now. What worked for me was an easy solution:\nPATH=$PATH:/Library/PostgreSQL/8.3/bin/ sudo easy_install psycopg2\n\nwhich I've found at http://blog.jonypawks.net/2008/06/20/installing-psycopg2-on-os-x/\n",
"I installed psycopg2 on my Mac with setuptools and easy_install. First get the Python 2.6 egg from the setuptools downloads page, then install it with the instructions on that page. Then you can run the following to install it:\nsudo easy_install psycopg2\n\nYou may have different luck, but that's what did it for me.\n",
"I tried everything and nothing works. At least this post: \nhttp://benkreeger.com/post/312303245/conquering-symbol-not-found-pqbackendpid\nled me to homebrew which made it perfectly.\n"
] | [
10,
3,
1,
0,
0
] | [] | [] | [
"macos",
"python"
] | stackoverflow_0001374187_macos_python.txt |
Q:
How do I require that an element has either one set of attributes or another in an XSD schema?
I'm working with an XML document where a tag must either have one set of attributes or another. For example, it needs to either look like <tag foo="hello" bar="kitty" /> or <tag spam="goodbye" eggs="world" /> e.g.
<root>
<tag foo="hello" bar="kitty" />
<tag spam="goodbye" eggs="world" />
</root>
So I have an XSD schema where I use the xs:choice element to choose between two different attribute groups:
<xsi:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema" attributeFormDefault="unqualified" elementFormDefault="qualified">
<xs:element name="root">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" name="tag">
<xs:choice>
<xs:complexType>
<xs:attribute name="foo" type="xs:string" use="required" />
<xs:attribute name="bar" type="xs:string" use="required" />
</xs:complexType>
<xs:complexType>
<xs:attribute name="spam" type="xs:string" use="required" />
<xs:attribute name="eggs" type="xs:string" use="required" />
</xs:complexType>
</xs:choice>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xsi:schema>
However, when using lxml to attempt to load this schema, I get the following error:
>>> from lxml import etree
>>> etree.XMLSchema( etree.parse("schema_choice.xsd") )
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "xmlschema.pxi", line 85, in lxml.etree.XMLSchema.__init__ (src/lxml/lxml.etree.c:118685)
lxml.etree.XMLSchemaParseError: Element '{http://www.w3.org/2001/XMLSchema}element': The content is not valid. Expected is (annotation?, ((simpleType | complexType)?, (unique | key | keyref)*))., line 7
Since the error is with the placement of my xs:choice element, I've tried putting it in different places, but no matter what I try, I can't seem to use it to define a tag to have either one set of attributes (foo and bar) or another (spam and eggs).
Is this even possible? And if so, then what is the correct syntax?
A:
It is unfortunately not possible to use choice with attributes in XML schema. You will need to implement this validation at a higher level.
| How do I require that an element has either one set of attributes or another in an XSD schema? | I'm working with an XML document where a tag must either have one set of attributes or another. For example, it needs to either look like <tag foo="hello" bar="kitty" /> or <tag spam="goodbye" eggs="world" /> e.g.
<root>
<tag foo="hello" bar="kitty" />
<tag spam="goodbye" eggs="world" />
</root>
So I have an XSD schema where I use the xs:choice element to choose between two different attribute groups:
<xsi:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema" attributeFormDefault="unqualified" elementFormDefault="qualified">
<xs:element name="root">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" name="tag">
<xs:choice>
<xs:complexType>
<xs:attribute name="foo" type="xs:string" use="required" />
<xs:attribute name="bar" type="xs:string" use="required" />
</xs:complexType>
<xs:complexType>
<xs:attribute name="spam" type="xs:string" use="required" />
<xs:attribute name="eggs" type="xs:string" use="required" />
</xs:complexType>
</xs:choice>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xsi:schema>
However, when using lxml to attempt to load this schema, I get the following error:
>>> from lxml import etree
>>> etree.XMLSchema( etree.parse("schema_choice.xsd") )
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "xmlschema.pxi", line 85, in lxml.etree.XMLSchema.__init__ (src/lxml/lxml.etree.c:118685)
lxml.etree.XMLSchemaParseError: Element '{http://www.w3.org/2001/XMLSchema}element': The content is not valid. Expected is (annotation?, ((simpleType | complexType)?, (unique | key | keyref)*))., line 7
Since the error is with the placement of my xs:choice element, I've tried putting it in different places, but no matter what I try, I can't seem to use it to define a tag to have either one set of attributes (foo and bar) or another (spam and eggs).
Is this even possible? And if so, then what is the correct syntax?
| [
"It is unfortunately not possible to use choice with attributes in XML schema. You will need to implement this validation at a higher level.\n"
] | [
5
] | [] | [] | [
"lxml",
"python",
"schema",
"validation",
"xml"
] | stackoverflow_0002806880_lxml_python_schema_validation_xml.txt |
Q:
Loading datasets from datastore and merge into single dictionary. Resource problem
I have a productdatabase that contains products, parts and labels for each part based on langcodes.
The problem I'm having and haven't got around is a huge amount of resource used to get the different datasets and merging them into a dict to suit my needs.
The products in the database are based on a number of parts that is of a certain type (ie. color, size). And each part has a label for each language. I created 4 different models for this. Products, ProductParts, ProductPartTypes and ProductPartLabels.
I've narrowed it down to about 10 lines of code that seams to generate the problem. As of currently I have 3 Products, 3 Types, 3 parts for each type, and 2 languages. And the request takes a wooping 5500ms to generate.
for product in productData:
productDict = {}
typeDict = {}
productDict['productName'] = product.name
cache_key = 'productparts_%s' % (slugify(product.key()))
partData = memcache.get(cache_key)
if not partData:
for type in typeData:
typeDict[type.typeId] = { 'default' : '', 'optional' : [] }
## Start of problem lines ##
for defaultPart in product.defaultPartsData:
for label in labelsForLangCode:
if label.key() in defaultPart.partLabelList:
typeDict[defaultPart.type.typeId]['default'] = label.partLangLabel
for optionalPart in product.optionalPartsData:
for label in labelsForLangCode:
if label.key() in optionalPart.partLabelList:
typeDict[optionalPart.type.typeId]['optional'].append(label.partLangLabel)
## end problem lines ##
memcache.add(cache_key, typeDict, 500)
partData = memcache.get(cache_key)
productDict['parts'] = partData
productList.append(productDict)
I guess the problem lies in the number of for loops is too many and have to iterate over the same data over and over again. labelForLangCode get all labels from ProductPartLabels that match the current langCode.
All parts for a product is stored in a db.ListProperty(db.key). The same goes for all labels for a part.
The reason I need the some what complex dict is that I want to display all data for a product with it's default parts and show a selector for the optional one.
The defaultPartsData and optionaPartsData are properties in the Product Model that looks like this:
@property
def defaultPartsData(self):
return ProductParts.gql('WHERE __key__ IN :key', key = self.defaultParts)
@property
def optionalPartsData(self):
return ProductParts.gql('WHERE __key__ IN :key', key = self.optionalParts)
When the completed dict is in the memcache it works smoothly, but isn't the memcache reset if the application goes in to hibernation? Also I would like to show the page for first time user(memcache empty) with out the enormous delay.
Also as I said above, this is only a small amount of parts/product. What will the result be when it's 30 products with 100 parts.
Is one solution to create a scheduled task to cache it in the memcache every hour? It this efficient?
I know this is alot to take in, but I'm stuck. I've been at this for about 12 hours straight. And can't figure out a solution.
..fredrik
EDIT:
A AppStats screenshoot here.
From what I can read the queries seams fine in AppStats. only taking about 200-400 ms. How can the difference be that big?
EDIT 2:
I implemented dound's solution and added abit. Now it looks like this:
langCode = 'en'
typeData = Products.ProductPartTypes.all()
productData = Products.Product.all()
labelsForLangCode = Products.ProductPartLabels.gql('WHERE partLangCode = :langCode', langCode = langCode)
productList = []
label_cache_key = 'productpartslabels_%s' % (slugify(langCode))
labelData = memcache.get(label_cache_key)
if labelData is None:
langDict = {}
for langLabel in labelsForLangCode:
langDict[str(langLabel.key())] = langLabel.partLangLabel
memcache.add(label_cache_key, langDict, 500)
labelData = memcache.get(label_cache_key)
GQL_PARTS_BY_PRODUCT = Products.ProductParts.gql('WHERE products = :1')
for product in productData:
productDict = {}
typeDict = {}
productDict['productName'] = product.name
cache_key = 'productparts_%s' % (slugify(product.key()))
partData = memcache.get(cache_key)
if partData is None:
for type in typeData:
typeDict[type.typeId] = { 'default' : '', 'optional' : [] }
GQL_PARTS_BY_PRODUCT.bind(product)
parts = GQL_PARTS_BY_PRODUCT.fetch(1000)
for part in parts:
for lb in part.partLabelList:
if str(lb) in labelData:
label = labelData[str(lb)]
break
if part.key() in product.defaultParts:
typeDict[part.type.typeId]['default'] = label
elif part.key() in product.optionalParts:
typeDict[part.type.typeId]['optional'].append(label)
memcache.add(cache_key, typeDict, 500)
partData = memcache.get(cache_key)
productDict['parts'] = partData
productList.append(productDict)
The result is much better. I now have about 3000ms with out memcache and about 700ms with.
I'm still abit worried about the 3000ms, and on the local app_dev server the memcache gets filled up for each reload. Shouldn't put everything in there and then read from it?
Last but not least, does anyone know why the request take about 10x as long on the production server the the app_dev?
EDIT 3:
I noticed that non of the db.Model are indexed, could this make a differance?
EDIT 4:
After consulting AppStats (And understanding it, took some time. It seams that the big problems lies within part.type.typeId where part.type is a db.ReferenceProperty. Should have seen it before. And maybe explained it better :) I'll rethink that part. And get back to you.
..fredrik
A:
A few simple ideas:
1) Since you need all the results, instead of doing a for loop like you have, call fetch() explicitly to just go ahead and get all the results at once. Otherwise, the for loop may result in multiple queries to the datastore as it only gets so many items at once. For example, perhaps you could try:
return ProductParts.gql('WHERE __key__ IN :key', key = self.defaultParts).fetch(1000)
2) Maybe only load part of the data in the initial request. Then use AJAX techniques to load additional data as needed. For example, start by returning the product information, and then make additional AJAX requests to get the parts.
3) Like Will pointed out, IN queries perform one query PER argument.
Problem: An IN query does one equals query for each argument you give it. So key IN self.defaultParts actually does len(self.defaultParts) queries.
Possible Improvement: Try denormalizing your data more. Specifically, store a list of products each part is used in on each part. You could structure your Parts model like this:
class ProductParts(db.Model):
...
products = db.ListProperty(db.Key) # product keys
...
Then you can do ONE query to per product instead of N queries per product. For example, you could do this:
parts = ProductParts.all().filter("products =", product).fetch(1000)
The trade-off? You have to store more data in each ProductParts entity. Also, when you write a ProductParts entity, it will be a little slower because it will cause 1 row to be written in the index for each element in your list property. However, you stated that you only have 100 products so even if a part was used in every product the list still wouldn't be too big (Nick Johnson mentions here that you won't get in trouble until you try to index a list property with ~5,000 items).
Less critical improvement idea:
4) You can create the GqlQuery object ONCE and then reuse it. This isn't your main performance problem by any stretch, but it will help a little. Example:
GQL_PROD_PART_BY_KEYS = ProductParts.gql('WHERE __key__ IN :1')
@property
def defaultPartsData(self):
return GQL_PROD_PART_BY_KEYS.bind(self.defaultParts)
You should also use AppStats so you can see exactly why your request is taking so long. You might even consider posting a screenshot of appstats info about your request along with your post.
Here is what the code might look like if you re-wrote it fetch the data with fewer round-trips to the datastore (these changes are based on ideas #1, #3, and #4 above).
GQL_PARTS_BY_PRODUCT = ProductParts.gql('WHERE products = :1')
for product in productData:
productDict = {}
typeDict = {}
productDict['productName'] = product.name
cache_key = 'productparts_%s' % (slugify(product.key()))
partData = memcache.get(cache_key)
if not partData:
for type in typeData:
typeDict[type.typeId] = { 'default' : '', 'optional' : [] }
# here's a new approach that does just ONE datastore query (for each product)
GQL_PARTS_BY_PRODUCT.bind(product)
parts = GQL_PARTS_BY_PRODUCT.fetch(1000)
for part in parts:
if part.key() in self.defaultParts:
part_type = 'default'
else:
part_type = 'optional'
for label in labelsForLangCode:
if label.key() in defaultPart.partLabelList:
typeDict[defaultPart.type.typeId][part_type] = label.partLangLabel
# (end new code)
memcache.add(cache_key, typeDict, 500)
partData = memcache.get(cache_key)
productDict['parts'] = partData
productList.append(productDict)
A:
One important thing to be aware of is the fact that IN queries (along with != queries) result in multiple subqueries being spawned behind the scenes, and there's a limit of 30 subqueries.
So your ProductParts.gql('WHERE __key__ IN :key', key = self.defaultParts) query will actually spawn len(self.defaultParts) subqueries behind the scenes, and it will fail if len(self.defaultParts) is greater than 30.
Here's the relevant section from the GQL Reference:
Note: The IN and != operators use multiple queries behind the scenes. For example, the IN operator executes a separate underlying datastore query for every item in the list. The entities returned are a result of the cross-product of all the underlying datastore queries and are de-duplicated. A maximum of 30 datastore queries are allowed for any single GQL query.
You might try installing AppStats for your app to see where else it might be slowing down.
A:
I think the problem is one of design: wanting to construct a relational join table in memcache when the framework specifically abhors that.
GAE will toss your job out because it takes too long, but you shouldn't be doing it in the first place. I'm a GAE tyro myself, so I cannot specify how it should be done, unfortunately.
| Loading datasets from datastore and merge into single dictionary. Resource problem | I have a productdatabase that contains products, parts and labels for each part based on langcodes.
The problem I'm having and haven't got around is a huge amount of resource used to get the different datasets and merging them into a dict to suit my needs.
The products in the database are based on a number of parts that is of a certain type (ie. color, size). And each part has a label for each language. I created 4 different models for this. Products, ProductParts, ProductPartTypes and ProductPartLabels.
I've narrowed it down to about 10 lines of code that seams to generate the problem. As of currently I have 3 Products, 3 Types, 3 parts for each type, and 2 languages. And the request takes a wooping 5500ms to generate.
for product in productData:
productDict = {}
typeDict = {}
productDict['productName'] = product.name
cache_key = 'productparts_%s' % (slugify(product.key()))
partData = memcache.get(cache_key)
if not partData:
for type in typeData:
typeDict[type.typeId] = { 'default' : '', 'optional' : [] }
## Start of problem lines ##
for defaultPart in product.defaultPartsData:
for label in labelsForLangCode:
if label.key() in defaultPart.partLabelList:
typeDict[defaultPart.type.typeId]['default'] = label.partLangLabel
for optionalPart in product.optionalPartsData:
for label in labelsForLangCode:
if label.key() in optionalPart.partLabelList:
typeDict[optionalPart.type.typeId]['optional'].append(label.partLangLabel)
## end problem lines ##
memcache.add(cache_key, typeDict, 500)
partData = memcache.get(cache_key)
productDict['parts'] = partData
productList.append(productDict)
I guess the problem lies in the number of for loops is too many and have to iterate over the same data over and over again. labelForLangCode get all labels from ProductPartLabels that match the current langCode.
All parts for a product is stored in a db.ListProperty(db.key). The same goes for all labels for a part.
The reason I need the some what complex dict is that I want to display all data for a product with it's default parts and show a selector for the optional one.
The defaultPartsData and optionaPartsData are properties in the Product Model that looks like this:
@property
def defaultPartsData(self):
return ProductParts.gql('WHERE __key__ IN :key', key = self.defaultParts)
@property
def optionalPartsData(self):
return ProductParts.gql('WHERE __key__ IN :key', key = self.optionalParts)
When the completed dict is in the memcache it works smoothly, but isn't the memcache reset if the application goes in to hibernation? Also I would like to show the page for first time user(memcache empty) with out the enormous delay.
Also as I said above, this is only a small amount of parts/product. What will the result be when it's 30 products with 100 parts.
Is one solution to create a scheduled task to cache it in the memcache every hour? It this efficient?
I know this is alot to take in, but I'm stuck. I've been at this for about 12 hours straight. And can't figure out a solution.
..fredrik
EDIT:
A AppStats screenshoot here.
From what I can read the queries seams fine in AppStats. only taking about 200-400 ms. How can the difference be that big?
EDIT 2:
I implemented dound's solution and added abit. Now it looks like this:
langCode = 'en'
typeData = Products.ProductPartTypes.all()
productData = Products.Product.all()
labelsForLangCode = Products.ProductPartLabels.gql('WHERE partLangCode = :langCode', langCode = langCode)
productList = []
label_cache_key = 'productpartslabels_%s' % (slugify(langCode))
labelData = memcache.get(label_cache_key)
if labelData is None:
langDict = {}
for langLabel in labelsForLangCode:
langDict[str(langLabel.key())] = langLabel.partLangLabel
memcache.add(label_cache_key, langDict, 500)
labelData = memcache.get(label_cache_key)
GQL_PARTS_BY_PRODUCT = Products.ProductParts.gql('WHERE products = :1')
for product in productData:
productDict = {}
typeDict = {}
productDict['productName'] = product.name
cache_key = 'productparts_%s' % (slugify(product.key()))
partData = memcache.get(cache_key)
if partData is None:
for type in typeData:
typeDict[type.typeId] = { 'default' : '', 'optional' : [] }
GQL_PARTS_BY_PRODUCT.bind(product)
parts = GQL_PARTS_BY_PRODUCT.fetch(1000)
for part in parts:
for lb in part.partLabelList:
if str(lb) in labelData:
label = labelData[str(lb)]
break
if part.key() in product.defaultParts:
typeDict[part.type.typeId]['default'] = label
elif part.key() in product.optionalParts:
typeDict[part.type.typeId]['optional'].append(label)
memcache.add(cache_key, typeDict, 500)
partData = memcache.get(cache_key)
productDict['parts'] = partData
productList.append(productDict)
The result is much better. I now have about 3000ms with out memcache and about 700ms with.
I'm still abit worried about the 3000ms, and on the local app_dev server the memcache gets filled up for each reload. Shouldn't put everything in there and then read from it?
Last but not least, does anyone know why the request take about 10x as long on the production server the the app_dev?
EDIT 3:
I noticed that non of the db.Model are indexed, could this make a differance?
EDIT 4:
After consulting AppStats (And understanding it, took some time. It seams that the big problems lies within part.type.typeId where part.type is a db.ReferenceProperty. Should have seen it before. And maybe explained it better :) I'll rethink that part. And get back to you.
..fredrik
| [
"A few simple ideas:\n1) Since you need all the results, instead of doing a for loop like you have, call fetch() explicitly to just go ahead and get all the results at once. Otherwise, the for loop may result in multiple queries to the datastore as it only gets so many items at once. For example, perhaps you could try:\nreturn ProductParts.gql('WHERE __key__ IN :key', key = self.defaultParts).fetch(1000)\n\n2) Maybe only load part of the data in the initial request. Then use AJAX techniques to load additional data as needed. For example, start by returning the product information, and then make additional AJAX requests to get the parts.\n3) Like Will pointed out, IN queries perform one query PER argument.\n\nProblem: An IN query does one equals query for each argument you give it. So key IN self.defaultParts actually does len(self.defaultParts) queries.\nPossible Improvement: Try denormalizing your data more. Specifically, store a list of products each part is used in on each part. You could structure your Parts model like this:\n\n\n class ProductParts(db.Model):\n ...\n products = db.ListProperty(db.Key) # product keys\n ...\n\n\nThen you can do ONE query to per product instead of N queries per product. For example, you could do this:\n\nparts = ProductParts.all().filter(\"products =\", product).fetch(1000)\n\nThe trade-off? You have to store more data in each ProductParts entity. Also, when you write a ProductParts entity, it will be a little slower because it will cause 1 row to be written in the index for each element in your list property. However, you stated that you only have 100 products so even if a part was used in every product the list still wouldn't be too big (Nick Johnson mentions here that you won't get in trouble until you try to index a list property with ~5,000 items).\n\nLess critical improvement idea:\n4) You can create the GqlQuery object ONCE and then reuse it. This isn't your main performance problem by any stretch, but it will help a little. Example:\nGQL_PROD_PART_BY_KEYS = ProductParts.gql('WHERE __key__ IN :1')\n@property\ndef defaultPartsData(self):\n return GQL_PROD_PART_BY_KEYS.bind(self.defaultParts)\n\nYou should also use AppStats so you can see exactly why your request is taking so long. You might even consider posting a screenshot of appstats info about your request along with your post.\n\nHere is what the code might look like if you re-wrote it fetch the data with fewer round-trips to the datastore (these changes are based on ideas #1, #3, and #4 above).\nGQL_PARTS_BY_PRODUCT = ProductParts.gql('WHERE products = :1')\nfor product in productData:\n productDict = {}\n typeDict = {}\n productDict['productName'] = product.name\n\n cache_key = 'productparts_%s' % (slugify(product.key()))\n partData = memcache.get(cache_key)\n\n if not partData:\n for type in typeData:\n typeDict[type.typeId] = { 'default' : '', 'optional' : [] }\n\n # here's a new approach that does just ONE datastore query (for each product)\n GQL_PARTS_BY_PRODUCT.bind(product)\n parts = GQL_PARTS_BY_PRODUCT.fetch(1000)\n for part in parts:\n if part.key() in self.defaultParts:\n part_type = 'default'\n else:\n part_type = 'optional'\n\n for label in labelsForLangCode:\n if label.key() in defaultPart.partLabelList:\n typeDict[defaultPart.type.typeId][part_type] = label.partLangLabel\n # (end new code)\n memcache.add(cache_key, typeDict, 500)\n partData = memcache.get(cache_key)\n\n productDict['parts'] = partData \n productList.append(productDict)\n\n",
"One important thing to be aware of is the fact that IN queries (along with != queries) result in multiple subqueries being spawned behind the scenes, and there's a limit of 30 subqueries.\nSo your ProductParts.gql('WHERE __key__ IN :key', key = self.defaultParts) query will actually spawn len(self.defaultParts) subqueries behind the scenes, and it will fail if len(self.defaultParts) is greater than 30.\nHere's the relevant section from the GQL Reference:\n\nNote: The IN and != operators use multiple queries behind the scenes. For example, the IN operator executes a separate underlying datastore query for every item in the list. The entities returned are a result of the cross-product of all the underlying datastore queries and are de-duplicated. A maximum of 30 datastore queries are allowed for any single GQL query.\n\nYou might try installing AppStats for your app to see where else it might be slowing down.\n",
"I think the problem is one of design: wanting to construct a relational join table in memcache when the framework specifically abhors that.\nGAE will toss your job out because it takes too long, but you shouldn't be doing it in the first place. I'm a GAE tyro myself, so I cannot specify how it should be done, unfortunately.\n"
] | [
2,
1,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0002806760_google_app_engine_python.txt |
Q:
Django ValueError at /admin/
I am running Django with mod_python on a Red Hat Linux box in production. A little while ago, for a reason unknown to me, the admin stopped working, throwing a 500 error. The error is as follows:
ValueError at /admin/
Empty module name
Request Method: GET
Exception Type: ValueError
Exception Value:
Empty module name
Exception Location: /usr/local/lib/python2.6/site-packages/django/utils/importlib.py in import_module, line 35
Python Executable: /usr/bin/python
Python Version: 2.6.2
Has anyone encountered this before? I have absolutely no idea how to fix this problem.
Thank you for any help.
A:
I was just debugging this problem. The error arises when Django is attempting to set up the template context processors, and the root cause was a definition which should have been a tuple but was actually a string.
This is what I had in my config file:
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.auth'
)
This is what I should have had:
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.auth',
)
Without the trailing comma, Python treats the value of the variable as a string. Thus, Django code which looks like this:
for path in settings.TEMPLATE_CONTEXT_PROCESSORS:
i = path.rfind('.')
module,attr = path[:i],path[i+1:]
the first value of 'path' is 'd', not 'django.core.context_processors.auth'. This leads the value of 'i' to be -1 and thus the value of 'module' to be empty.
Make sure that all of the tuple-like things in your Django config are actually tuples, which means if they have a single value, they still need a trailing comma.
| Django ValueError at /admin/ | I am running Django with mod_python on a Red Hat Linux box in production. A little while ago, for a reason unknown to me, the admin stopped working, throwing a 500 error. The error is as follows:
ValueError at /admin/
Empty module name
Request Method: GET
Exception Type: ValueError
Exception Value:
Empty module name
Exception Location: /usr/local/lib/python2.6/site-packages/django/utils/importlib.py in import_module, line 35
Python Executable: /usr/bin/python
Python Version: 2.6.2
Has anyone encountered this before? I have absolutely no idea how to fix this problem.
Thank you for any help.
| [
"I was just debugging this problem. The error arises when Django is attempting to set up the template context processors, and the root cause was a definition which should have been a tuple but was actually a string.\nThis is what I had in my config file:\nTEMPLATE_CONTEXT_PROCESSORS = (\n'django.core.context_processors.auth'\n)\n\nThis is what I should have had:\nTEMPLATE_CONTEXT_PROCESSORS = (\n'django.core.context_processors.auth',\n)\n\nWithout the trailing comma, Python treats the value of the variable as a string. Thus, Django code which looks like this:\nfor path in settings.TEMPLATE_CONTEXT_PROCESSORS:\n i = path.rfind('.')\n module,attr = path[:i],path[i+1:]\n\nthe first value of 'path' is 'd', not 'django.core.context_processors.auth'. This leads the value of 'i' to be -1 and thus the value of 'module' to be empty.\nMake sure that all of the tuple-like things in your Django config are actually tuples, which means if they have a single value, they still need a trailing comma.\n"
] | [
5
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0001760797_django_django_admin_python.txt |
Q:
How do I delete in Django? (mysql transactions)
If you are familiar with Django, you know that they have a Authentication system with User model. Of course, I have many other tables that have a Foreign Key to this User model.
If I want to delete this user, how do I architect a script (or through mysql itself) to delete every table that is related to this user?
My only worry is that I can do this manually...but if I add a table , but I forget to add that table to my DELETE operation...then I have a row that links to a deleted, non-existing User.
A:
As far as I understand it, django does an "on delete cascade" by default:
http://docs.djangoproject.com/en/dev/topics/db/queries/#deleting-objects
A:
You don't need a script for this. When you delete a record, Django will automatically delete all dependent records (thus taking care of its own database integrity).
This is simple to test. In the admin, go to delete a User. On the confirmation page, you'll see a list of all dependent records in the system. You can use this any time as a quick test to see what's dependent on what (as long as you don't actually click Confirm).
If you perform deletions from your view code with .delete(), all dependent objects will be deleted automatically with no option for confirmation.
From the docs:
When Django deletes an object, it
emulates the behavior of the SQL
constraint ON DELETE CASCADE -- in
other words, any objects which had
foreign keys pointing at the object to
be deleted will be deleted along with
it.
| How do I delete in Django? (mysql transactions) | If you are familiar with Django, you know that they have a Authentication system with User model. Of course, I have many other tables that have a Foreign Key to this User model.
If I want to delete this user, how do I architect a script (or through mysql itself) to delete every table that is related to this user?
My only worry is that I can do this manually...but if I add a table , but I forget to add that table to my DELETE operation...then I have a row that links to a deleted, non-existing User.
| [
"As far as I understand it, django does an \"on delete cascade\" by default:\nhttp://docs.djangoproject.com/en/dev/topics/db/queries/#deleting-objects\n",
"You don't need a script for this. When you delete a record, Django will automatically delete all dependent records (thus taking care of its own database integrity).\nThis is simple to test. In the admin, go to delete a User. On the confirmation page, you'll see a list of all dependent records in the system. You can use this any time as a quick test to see what's dependent on what (as long as you don't actually click Confirm).\nIf you perform deletions from your view code with .delete(), all dependent objects will be deleted automatically with no option for confirmation.\nFrom the docs:\n\nWhen Django deletes an object, it\n emulates the behavior of the SQL\n constraint ON DELETE CASCADE -- in\n other words, any objects which had\n foreign keys pointing at the object to\n be deleted will be deleted along with\n it.\n\n"
] | [
2,
0
] | [] | [] | [
"database",
"django",
"mysql",
"python",
"transactions"
] | stackoverflow_0002795793_database_django_mysql_python_transactions.txt |
Q:
Implementing a popularity algorithm in Django
I am creating a site similar to reddit and hacker news that has a database of links and votes. I am implementing hacker news' popularity algorithm and things are going pretty swimmingly until it comes to actually gathering up these links and displaying them. The algorithm is simple:
Y Combinator's Hacker News:
Popularity = (p - 1) / (t + 2)^1.5`
Votes divided by age factor.
Where`
p : votes (points) from users.
t : time since submission in hours.
p is subtracted by 1 to negate submitter's vote.
Age factor is (time since submission in hours plus two) to the power of 1.5.factor is (time since submission in hours plus two) to the power of 1.5.
I asked a very similar question over yonder Complex ordering in Django but instead of contemplating my options I choose one and tried to make it work because that's how I did it with PHP/MySQL but I now know Django does things a lot differently.
My models look something (exactly) like this
class Link(models.Model):
category = models.ForeignKey(Category)
user = models.ForeignKey(User)
created = models.DateTimeField(auto_now_add = True)
modified = models.DateTimeField(auto_now = True)
fame = models.PositiveIntegerField(default = 1)
title = models.CharField(max_length = 256)
url = models.URLField(max_length = 2048)
def __unicode__(self):
return self.title
class Vote(models.Model):
link = models.ForeignKey(Link)
user = models.ForeignKey(User)
created = models.DateTimeField(auto_now_add = True)
modified = models.DateTimeField(auto_now = True)
karma_delta = models.SmallIntegerField()
def __unicode__(self):
return str(self.karma_delta)
and my view:
def index(request):
popular_links = Link.objects.select_related().annotate(karma_total = Sum('vote__karma_delta'))
return render_to_response('links/index.html', {'links': popular_links})
Now from my previous question, I am trying to implement the algorithm using the sorting function. An answer from that question seems to think I should put the algorithm in the select and sort then. I am going to paginate these results so I don't think I can do the sorting in python without grabbing everything. Any suggestions on how I could efficiently do this?
EDIT
This isn't working yet but I think it's a step in the right direction:
from django.shortcuts import render_to_response
from linkett.apps.links.models import *
def index(request):
popular_links = Link.objects.select_related()
popular_links = popular_links.extra(
select = {
'karma_total': 'SUM(vote.karma_delta)',
'popularity': '(karma_total - 1) / POW(2, 1.5)',
},
order_by = ['-popularity']
)
return render_to_response('links/index.html', {'links': popular_links})
This errors out into:
Caught an exception while rendering: column "karma_total" does not exist
LINE 1: SELECT ((karma_total - 1) / POW(2, 1.5)) AS "popularity", (S...
EDIT 2
Better error?
TemplateSyntaxError: Caught an exception while rendering: missing FROM-clause entry for table "vote"
LINE 1: SELECT ((vote.karma_total - 1) / POW(2, 1.5)) AS "popularity...
My index.html is simply:
{% block content %}
{% for link in links %}
karma-up
{{ link.karma_total }}
karma-down
{{ link.title }}
Posted by {{ link.user }} to {{ link.category }} at {{ link.created }}
{% empty %}
No Links
{% endfor %}
{% endblock content %}
EDIT 3
So very close! Again, all these answers are great but I am concentrating on a particular one because I feel it works best for my situation.
from django.db.models import Sum
from django.shortcuts import render_to_response
from linkett.apps.links.models import *
def index(request):
popular_links = Link.objects.select_related().extra(
select = {
'popularity': '(SUM(links_vote.karma_delta) - 1) / POW(2, 1.5)',
},
tables = ['links_link', 'links_vote'],
order_by = ['-popularity'],
)
return render_to_response('links/test.html', {'links': popular_links})
Running this I am presented with an error hating on my lack of group by values. Specifically:
TemplateSyntaxError at /
Caught an exception while rendering: column "links_link.id" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: ...karma_delta) - 1) / POW(2, 1.5)) AS "popularity", "links_lin...
Not sure why my links_link.id wouldn't be in my group by but I am not sure how to alter my group by, django usually does that.
A:
On Hacker News, only the 210 newest stories and 210 most popular stories are paginated (7 pages worth * 30 stories each). My guess is that the reason for the limit (at least in part) is this problem.
Why not drop all the fancy SQL for the most popular stories and just keep a running list instead? Once you've established a list of the top 210 stories you only need to worry about reordering when a new vote comes in since relative order is maintained over time. And when a new vote does come in, you only need to worry about reordering the story that received the vote.
If the story that received the vote is not on the list, calculate the score of that story, plus the least popular story that is on the list. If the story that received the vote is lower, you're done. If it's higher, calculate the current score for the second-to-least most popular (story 209) and compare again. Continue working up until you find a story with a higher score and then place the newly-voted-upon story right below that one in the rankings. Unless, of course, it reaches #1.
The benefit of this approach is that it limits the set of stories you have to look at to figure out the top stories list. In the absolute worst case scenario, you have to calculate the ranking for 211 stories. So it's very efficient unless you have to establish the list from an existing data set - but that's just a one-time penalty assuming you cache the list someplace.
Downvotes are another issue, but I can only upvote (at my karma level, anyway).
A:
popular_links = Link.objects.select_related()
popular_links = popular_links.extra(
select = {
'karma_total': 'SUM(vote.karma_delta)',
'popularity': '(karma_total - 1) / POW(2, 1.5)'
},
order_by = ['-popularity']
)
Or select some sane number, sort the selection using python in any way you like, and cache if its going to be static for all users which it looks like it will - set cache expiration to a minute or so.
But the extra will work better for paginated results in a highly dynamic setup.
A:
Seems like you could overload the save of the Vote class and have it update the corresponding Link object. Something like this should work well:
from datetime import datetime, timedelta
class Link(models.Model):
category = models.ForeignKey(Category)
user = models.ForeignKey(User)
created = models.DateTimeField(auto_now_add = True)
modified = models.DateTimeField(auto_now = True)
fame = models.PositiveIntegerField(default = 1)
title = models.CharField(max_length = 256)
url = models.URLField(max_length = 2048)
#a field to keep the most recently calculated popularity
popularity = models.FloatField(default = None)
def CalculatePopularity(self):
"""
Add a shorcut to make life easier ... this is used by the overloaded save() method and
can be used in a management function to do a mass-update periodically
"""
ts = datetime.now()-self.created
th = ts.seconds/60/60
self.popularity = (self.user_set.count()-1)/((th+2)**1.5)
def save(self, *args, **kwargs):
"""
Modify the save function to calculate the popularity
"""
self.CalculatePopularity()
super(Link, self).save(*args, **kwargs)
def __unicode__(self):
return self.title
class Vote(models.Model):
link = models.ForeignKey(Link)
user = models.ForeignKey(User)
created = models.DateTimeField(auto_now_add = True)
modified = models.DateTimeField(auto_now = True)
karma_delta = models.SmallIntegerField()
def save(self, *args, **kwargs):
"""
Modify the save function to calculate the popularity of the Link object
"""
self.link.CalculatePopularity()
super(Vote, self).save(*args, **kwargs)
def __unicode__(self):
return str(self.karma_delta)
This way every time you call a link_o.save() or vote_o.save() it will re-calculate the popularity. You have to be a little careful because when you call Link.objects.all().update('updating something') then it won't call our overloaded save() function. So when I use this sort of thing I create a management command which updates all of the objects so they're not too out of date. Something like this will work wonderfully:
from itertools import imap
imap(lambda x:x.CalculatePopularity(), Link.objects.all().select_related().iterator())
This way it will only load a single Link object into memory at once ... so if you have a giant database it won't cause a memory error.
Now to do your ranking all you have to do is:
Link.objects.all().order_by('-popularity')
It will be super-fast since all of you Link items have already calculated the popularity.
A:
Here was the final answer to my question although many months late and not exactly what I had in mind. Hopefully it will be useful to some.
def hot(request):
links = Link.objects.select_related().annotate(votes=Count('vote')).order_by('-created')[:150]
for link in links:
delta_in_hours = (int(datetime.now().strftime("%s")) - int(link.created.strftime("%s"))) / 3600
link.popularity = ((link.votes - 1) / (delta_in_hours + 2)**1.5)
links = sorted(links, key=lambda x: x.popularity, reverse=True)
links = paginate(request, links, 5)
return direct_to_template(
request,
template = 'links/link_list.html',
extra_context = {
'links': links
})
What's going on here is I pull the latest 150 submissions (5 pages of 30 links each) if you need more obviously you can go grab'em by altering my slice [:150]. This way I don't have to iterate over my queryset which might eventually become very large and really 150 links should be enough procrastination for anybody.
I then calculate the difference in time between now and when the link was created and turn it into hours (not nearly as easy as I thought)
Apply the algorithm to a non-existant field (I like this method because I don't have to store the value in my database and isn't reliant on surrounding links.
The line immediately after the for loop was where I also had another bit of trouble. I can't order_by('popularity') because it's not a real field in my database and is calculated on the fly so I have to convert my queryset into an object list and sort popularity from there.
The next line is just my paginator shortcut, thankfully pagination does not require a queryset unlike some generic views (talking to you object_list).
Spit everything out into a nice direct_to_template generic view and be on my merry way.
| Implementing a popularity algorithm in Django | I am creating a site similar to reddit and hacker news that has a database of links and votes. I am implementing hacker news' popularity algorithm and things are going pretty swimmingly until it comes to actually gathering up these links and displaying them. The algorithm is simple:
Y Combinator's Hacker News:
Popularity = (p - 1) / (t + 2)^1.5`
Votes divided by age factor.
Where`
p : votes (points) from users.
t : time since submission in hours.
p is subtracted by 1 to negate submitter's vote.
Age factor is (time since submission in hours plus two) to the power of 1.5.factor is (time since submission in hours plus two) to the power of 1.5.
I asked a very similar question over yonder Complex ordering in Django but instead of contemplating my options I choose one and tried to make it work because that's how I did it with PHP/MySQL but I now know Django does things a lot differently.
My models look something (exactly) like this
class Link(models.Model):
category = models.ForeignKey(Category)
user = models.ForeignKey(User)
created = models.DateTimeField(auto_now_add = True)
modified = models.DateTimeField(auto_now = True)
fame = models.PositiveIntegerField(default = 1)
title = models.CharField(max_length = 256)
url = models.URLField(max_length = 2048)
def __unicode__(self):
return self.title
class Vote(models.Model):
link = models.ForeignKey(Link)
user = models.ForeignKey(User)
created = models.DateTimeField(auto_now_add = True)
modified = models.DateTimeField(auto_now = True)
karma_delta = models.SmallIntegerField()
def __unicode__(self):
return str(self.karma_delta)
and my view:
def index(request):
popular_links = Link.objects.select_related().annotate(karma_total = Sum('vote__karma_delta'))
return render_to_response('links/index.html', {'links': popular_links})
Now from my previous question, I am trying to implement the algorithm using the sorting function. An answer from that question seems to think I should put the algorithm in the select and sort then. I am going to paginate these results so I don't think I can do the sorting in python without grabbing everything. Any suggestions on how I could efficiently do this?
EDIT
This isn't working yet but I think it's a step in the right direction:
from django.shortcuts import render_to_response
from linkett.apps.links.models import *
def index(request):
popular_links = Link.objects.select_related()
popular_links = popular_links.extra(
select = {
'karma_total': 'SUM(vote.karma_delta)',
'popularity': '(karma_total - 1) / POW(2, 1.5)',
},
order_by = ['-popularity']
)
return render_to_response('links/index.html', {'links': popular_links})
This errors out into:
Caught an exception while rendering: column "karma_total" does not exist
LINE 1: SELECT ((karma_total - 1) / POW(2, 1.5)) AS "popularity", (S...
EDIT 2
Better error?
TemplateSyntaxError: Caught an exception while rendering: missing FROM-clause entry for table "vote"
LINE 1: SELECT ((vote.karma_total - 1) / POW(2, 1.5)) AS "popularity...
My index.html is simply:
{% block content %}
{% for link in links %}
karma-up
{{ link.karma_total }}
karma-down
{{ link.title }}
Posted by {{ link.user }} to {{ link.category }} at {{ link.created }}
{% empty %}
No Links
{% endfor %}
{% endblock content %}
EDIT 3
So very close! Again, all these answers are great but I am concentrating on a particular one because I feel it works best for my situation.
from django.db.models import Sum
from django.shortcuts import render_to_response
from linkett.apps.links.models import *
def index(request):
popular_links = Link.objects.select_related().extra(
select = {
'popularity': '(SUM(links_vote.karma_delta) - 1) / POW(2, 1.5)',
},
tables = ['links_link', 'links_vote'],
order_by = ['-popularity'],
)
return render_to_response('links/test.html', {'links': popular_links})
Running this I am presented with an error hating on my lack of group by values. Specifically:
TemplateSyntaxError at /
Caught an exception while rendering: column "links_link.id" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: ...karma_delta) - 1) / POW(2, 1.5)) AS "popularity", "links_lin...
Not sure why my links_link.id wouldn't be in my group by but I am not sure how to alter my group by, django usually does that.
| [
"On Hacker News, only the 210 newest stories and 210 most popular stories are paginated (7 pages worth * 30 stories each). My guess is that the reason for the limit (at least in part) is this problem.\nWhy not drop all the fancy SQL for the most popular stories and just keep a running list instead? Once you've established a list of the top 210 stories you only need to worry about reordering when a new vote comes in since relative order is maintained over time. And when a new vote does come in, you only need to worry about reordering the story that received the vote.\nIf the story that received the vote is not on the list, calculate the score of that story, plus the least popular story that is on the list. If the story that received the vote is lower, you're done. If it's higher, calculate the current score for the second-to-least most popular (story 209) and compare again. Continue working up until you find a story with a higher score and then place the newly-voted-upon story right below that one in the rankings. Unless, of course, it reaches #1.\nThe benefit of this approach is that it limits the set of stories you have to look at to figure out the top stories list. In the absolute worst case scenario, you have to calculate the ranking for 211 stories. So it's very efficient unless you have to establish the list from an existing data set - but that's just a one-time penalty assuming you cache the list someplace.\nDownvotes are another issue, but I can only upvote (at my karma level, anyway).\n",
"popular_links = Link.objects.select_related()\npopular_links = popular_links.extra(\n select = {\n 'karma_total': 'SUM(vote.karma_delta)',\n 'popularity': '(karma_total - 1) / POW(2, 1.5)'\n },\n order_by = ['-popularity']\n)\n\nOr select some sane number, sort the selection using python in any way you like, and cache if its going to be static for all users which it looks like it will - set cache expiration to a minute or so.\nBut the extra will work better for paginated results in a highly dynamic setup.\n",
"Seems like you could overload the save of the Vote class and have it update the corresponding Link object. Something like this should work well:\nfrom datetime import datetime, timedelta\n\nclass Link(models.Model):\n category = models.ForeignKey(Category)\n user = models.ForeignKey(User)\n created = models.DateTimeField(auto_now_add = True)\n modified = models.DateTimeField(auto_now = True)\n fame = models.PositiveIntegerField(default = 1)\n title = models.CharField(max_length = 256)\n url = models.URLField(max_length = 2048)\n\n #a field to keep the most recently calculated popularity\n popularity = models.FloatField(default = None)\n\n def CalculatePopularity(self):\n \"\"\"\n Add a shorcut to make life easier ... this is used by the overloaded save() method and \n can be used in a management function to do a mass-update periodically\n \"\"\"\n ts = datetime.now()-self.created\n th = ts.seconds/60/60\n self.popularity = (self.user_set.count()-1)/((th+2)**1.5)\n\n def save(self, *args, **kwargs):\n \"\"\"\n Modify the save function to calculate the popularity\n \"\"\"\n self.CalculatePopularity()\n super(Link, self).save(*args, **kwargs)\n\n\n def __unicode__(self):\n return self.title\n\nclass Vote(models.Model):\n link = models.ForeignKey(Link)\n user = models.ForeignKey(User)\n created = models.DateTimeField(auto_now_add = True)\n modified = models.DateTimeField(auto_now = True)\n karma_delta = models.SmallIntegerField()\n\n def save(self, *args, **kwargs):\n \"\"\"\n Modify the save function to calculate the popularity of the Link object\n \"\"\"\n self.link.CalculatePopularity()\n super(Vote, self).save(*args, **kwargs)\n\n def __unicode__(self):\n return str(self.karma_delta)\n\nThis way every time you call a link_o.save() or vote_o.save() it will re-calculate the popularity. You have to be a little careful because when you call Link.objects.all().update('updating something') then it won't call our overloaded save() function. So when I use this sort of thing I create a management command which updates all of the objects so they're not too out of date. Something like this will work wonderfully:\nfrom itertools import imap\nimap(lambda x:x.CalculatePopularity(), Link.objects.all().select_related().iterator())\n\nThis way it will only load a single Link object into memory at once ... so if you have a giant database it won't cause a memory error.\nNow to do your ranking all you have to do is:\nLink.objects.all().order_by('-popularity')\n\nIt will be super-fast since all of you Link items have already calculated the popularity.\n",
"Here was the final answer to my question although many months late and not exactly what I had in mind. Hopefully it will be useful to some.\ndef hot(request):\n links = Link.objects.select_related().annotate(votes=Count('vote')).order_by('-created')[:150]\n for link in links:\n delta_in_hours = (int(datetime.now().strftime(\"%s\")) - int(link.created.strftime(\"%s\"))) / 3600\n link.popularity = ((link.votes - 1) / (delta_in_hours + 2)**1.5)\n\n links = sorted(links, key=lambda x: x.popularity, reverse=True)\n\n links = paginate(request, links, 5)\n\n return direct_to_template(\n request,\n template = 'links/link_list.html',\n extra_context = {\n 'links': links\n })\n\nWhat's going on here is I pull the latest 150 submissions (5 pages of 30 links each) if you need more obviously you can go grab'em by altering my slice [:150]. This way I don't have to iterate over my queryset which might eventually become very large and really 150 links should be enough procrastination for anybody.\nI then calculate the difference in time between now and when the link was created and turn it into hours (not nearly as easy as I thought)\nApply the algorithm to a non-existant field (I like this method because I don't have to store the value in my database and isn't reliant on surrounding links.\nThe line immediately after the for loop was where I also had another bit of trouble. I can't order_by('popularity') because it's not a real field in my database and is calculated on the fly so I have to convert my queryset into an object list and sort popularity from there.\nThe next line is just my paginator shortcut, thankfully pagination does not require a queryset unlike some generic views (talking to you object_list).\nSpit everything out into a nice direct_to_template generic view and be on my merry way.\n"
] | [
10,
4,
4,
1
] | [] | [] | [
"algorithm",
"django",
"postgresql",
"python"
] | stackoverflow_0001965341_algorithm_django_postgresql_python.txt |
Q:
How to get a html elements with python lxml
I have this html code:
<table>
<tr>
<td class="test"><b><a href="">aaa</a></b></td>
<td class="test">bbb</td>
<td class="test">ccc</td>
<td class="test"><small>ddd</small></td>
</tr>
<tr>
<td class="test"><b><a href="">eee</a></b></td>
<td class="test">fff</td>
<td class="test">ggg</td>
<td class="test"><small>hhh</small></td>
</tr>
</table>
I use this Python code to extract all <td class="test"> with lxml module.
import urllib2
import lxml.html
code = urllib.urlopen("http://www.example.com/page.html").read()
html = lxml.html.fromstring(code)
result = html.xpath('//td[@class="test"][position() = 1 or position() = 4]')
It works good! The result is:
<td class="test"><b><a href="">aaa</a></b></td>
<td class="test"><small>ddd</small></td>
<td class="test"><b><a href="">eee</a></b></td>
<td class="test"><small>hhh</small></td>
(so the first and the fourth column of each <tr>)
Now, I have to extract:
aaa (the title of the link)
ddd (text between <small> tag)
eee (the title of the link)
hhh (text between <small> tag)
How could I extract these values?
(the problem is that I have to remove <b> tag and get the title of the anchor on the first column and remove <small> tag on the forth column)
Thank you!
A:
If you do el.text_content() you'll strip all the tag stuff from each element, i.e.:
result = [el.text_content() for el in result]
A:
Why dont you just fetch what you want in each step?
links = [el.text for el in html.xpath('//td[@class="test"][position() = 1]/b/a')]
smalls = [el.text for el in html.xpath('//td[@class="test"][position() = 4]/small')]
print zip(links, smalls)
# => [('aaa', 'ddd'), ('eee', 'hhh')]
| How to get a html elements with python lxml | I have this html code:
<table>
<tr>
<td class="test"><b><a href="">aaa</a></b></td>
<td class="test">bbb</td>
<td class="test">ccc</td>
<td class="test"><small>ddd</small></td>
</tr>
<tr>
<td class="test"><b><a href="">eee</a></b></td>
<td class="test">fff</td>
<td class="test">ggg</td>
<td class="test"><small>hhh</small></td>
</tr>
</table>
I use this Python code to extract all <td class="test"> with lxml module.
import urllib2
import lxml.html
code = urllib.urlopen("http://www.example.com/page.html").read()
html = lxml.html.fromstring(code)
result = html.xpath('//td[@class="test"][position() = 1 or position() = 4]')
It works good! The result is:
<td class="test"><b><a href="">aaa</a></b></td>
<td class="test"><small>ddd</small></td>
<td class="test"><b><a href="">eee</a></b></td>
<td class="test"><small>hhh</small></td>
(so the first and the fourth column of each <tr>)
Now, I have to extract:
aaa (the title of the link)
ddd (text between <small> tag)
eee (the title of the link)
hhh (text between <small> tag)
How could I extract these values?
(the problem is that I have to remove <b> tag and get the title of the anchor on the first column and remove <small> tag on the forth column)
Thank you!
| [
"If you do el.text_content() you'll strip all the tag stuff from each element, i.e.:\nresult = [el.text_content() for el in result]\n\n",
"Why dont you just fetch what you want in each step?\nlinks = [el.text for el in html.xpath('//td[@class=\"test\"][position() = 1]/b/a')]\nsmalls = [el.text for el in html.xpath('//td[@class=\"test\"][position() = 4]/small')]\nprint zip(links, smalls) \n# => [('aaa', 'ddd'), ('eee', 'hhh')]\n\n"
] | [
8,
4
] | [] | [] | [
"lxml",
"python",
"xml"
] | stackoverflow_0002807209_lxml_python_xml.txt |
Q:
How can I specify a relative path in a Python logging config file?
I've the following file to config logging:
[loggers]
keys=root
[handlers]
keys = root
[formatters]
keys = generic
# Loggers
[logger_root]
level = DEBUG
handlers = root
# Handlers
[handler_root]
class = handlers.RotatingFileHandler
args = ("test.log", "maxBytes=1*1024*1024", "backupCount=10")
level = NOTSET
formatter = generic
# Formatters
[formatter_generic]
format = %(asctime)s,%(msecs)03d %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %Y-%m-%d %H:%M:%S
In Development this works great, but when I deploy the application test.log is trying to be written in a path in which I don't have the necessary permission.
So my question is, How can I do to specify a relative path in this configuration file.
A:
Mark is right, your path in the config file is relative to whatever directory is current when the logging.config.fileConfig call is made. This depends on the details of your deployment method.
You may need to specify an absolute path to your file, by prefixing 'test.log' with a directory you know to be writable by the process running your code.
Another problem might just be a permissions issue with the user your Django process runs under: typically when running the development server it runs under your account and you will typically not encounter permissions issues. When deploying (with Apache and mod_wsgi, say) the Apache process and/or mod_wsgi daemon process run under different accounts which may need to be given permission to the relevant folder.
If you need more help, please give more details about your deployment with respect to the method, location of log file directory etc.
| How can I specify a relative path in a Python logging config file? | I've the following file to config logging:
[loggers]
keys=root
[handlers]
keys = root
[formatters]
keys = generic
# Loggers
[logger_root]
level = DEBUG
handlers = root
# Handlers
[handler_root]
class = handlers.RotatingFileHandler
args = ("test.log", "maxBytes=1*1024*1024", "backupCount=10")
level = NOTSET
formatter = generic
# Formatters
[formatter_generic]
format = %(asctime)s,%(msecs)03d %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %Y-%m-%d %H:%M:%S
In Development this works great, but when I deploy the application test.log is trying to be written in a path in which I don't have the necessary permission.
So my question is, How can I do to specify a relative path in this configuration file.
| [
"Mark is right, your path in the config file is relative to whatever directory is current when the logging.config.fileConfig call is made. This depends on the details of your deployment method.\nYou may need to specify an absolute path to your file, by prefixing 'test.log' with a directory you know to be writable by the process running your code.\nAnother problem might just be a permissions issue with the user your Django process runs under: typically when running the development server it runs under your account and you will typically not encounter permissions issues. When deploying (with Apache and mod_wsgi, say) the Apache process and/or mod_wsgi daemon process run under different accounts which may need to be given permission to the relevant folder.\nIf you need more help, please give more details about your deployment with respect to the method, location of log file directory etc.\n"
] | [
7
] | [] | [] | [
"django",
"logging",
"python"
] | stackoverflow_0002806376_django_logging_python.txt |
Q:
GIS: When and why to use ArcObjects over GDAL programming to work with ArcGIS rasters and vectors?
Im just starting off with GDAL + python to support operations that cannot be done with ArcGIS python geoprocessing scripting. Mainly I am doing spatial modeling/analysis/editing of raster and vector data.
I am a bit confused when ArcObject development is required versus when GDAL can be used?
Is there functionality of ArcObjects that GDAL does not do? Is the opposite true too?
I am assuming that ArcObjects are more useful in developing online tools versus Desktop analysis and modeling where the difference is more to do with preference? In my case i prefer GDAL because of python support, which I believe ArcObjects lack.
thanks!
A:
GDAL is included in ArcGIS to work with some raster data formats. They do not use the GDAL utilities to do any geoprocessing. I would imagine ESRI have implemented most, if not all, of the functionality in GDAL with their own geoprocessing functions. In summary there is a big overlap in functionality between the two.
The ESRI geoprocessing functions can all be run and scripted through Python. The geoprocessing tools are higher level abstractions (a simplification) of ArcObjects, and have been built using ArcObjects. They should cover your requirements of "spatial modeling/analysis/editing of raster and vector data."
http://webhelp.esri.com/arcgisdesktop/9.2/index.cfm?id=596&pid=592&topicname=Geoprocessing_framework
What function do you find is missing in the ESRI geoprocessing tools?
The GDAL utilities can also be manipulated with Python (and other languages). If there is a utility in the link below that meets your needs then you can use this.
Link
A:
geographika's answer is superb. I'll only add that I use gdal/ogr when simplicity and speed is wanted in conversions. Examples include one format to another, adding image pyramids, simple merging and coordinate transformation (raster & vector). When all you want to do is jam a bunch of shapefiles together or convert a large series of rasters to a common projection gdal/ogr is faster to startup and run as it doesn't need to load the whole ArcObjects COM library to access one or two functions. (I've been told ESRI has the largest MS COM system on earth, by a large margin, including all of Microsoft's offerings.) Or check for a valid license. In one test I ran comparing ESRI arcgisscripting to GDAL ogr2ogr processing time went from 6 minutes to 10 seconds.
The only significant thing, in the realm of conversion and projection, that I feel is missing from gdal is the ability to log geoprocessing activity in the Lineage section of the metadata. ESRI tools do this automatically (most of the time).
When moving beyond conversion and getting into proper analysis though there really is no place outside of ESRI*. In my experience that is. Before you dig into ArcObjects directly I'd spend some time learning what can be accomplished via arcgisscripting (arcpy in v10), which is python, and dot net.
* 10 years later: I don't stand behind this statement anymore. Qgis has had a very steady improvement rate throughout the last decade and doesn't show any signs of slowing down. If anything it's been speeding up. True Esri has had significant improvements in the same period as well, but their focus is spread between desktop and online, in favour of the latter. My current recommendation is to look at the respective communities and choose based on which ones have the largest overlap with your own work and interests. It's not (so much) about which platform has what functions, but about who you might best work with.
A:
ArcObjects and geoprocessing add a lot more functionality than GDAL and is mostly aimed at the desktop. Another option for looking at Python is also using QGIS which has a python API, is Free and Open Source, and an active developer community.
There are also plenty of python libraries for doing spatial work, such as Shapely. I would say for raster that GDAL is your best bet but for vector you might want to use something like shapely.
| GIS: When and why to use ArcObjects over GDAL programming to work with ArcGIS rasters and vectors? | Im just starting off with GDAL + python to support operations that cannot be done with ArcGIS python geoprocessing scripting. Mainly I am doing spatial modeling/analysis/editing of raster and vector data.
I am a bit confused when ArcObject development is required versus when GDAL can be used?
Is there functionality of ArcObjects that GDAL does not do? Is the opposite true too?
I am assuming that ArcObjects are more useful in developing online tools versus Desktop analysis and modeling where the difference is more to do with preference? In my case i prefer GDAL because of python support, which I believe ArcObjects lack.
thanks!
| [
"GDAL is included in ArcGIS to work with some raster data formats. They do not use the GDAL utilities to do any geoprocessing. I would imagine ESRI have implemented most, if not all, of the functionality in GDAL with their own geoprocessing functions. In summary there is a big overlap in functionality between the two.\nThe ESRI geoprocessing functions can all be run and scripted through Python. The geoprocessing tools are higher level abstractions (a simplification) of ArcObjects, and have been built using ArcObjects. They should cover your requirements of \"spatial modeling/analysis/editing of raster and vector data.\"\nhttp://webhelp.esri.com/arcgisdesktop/9.2/index.cfm?id=596&pid=592&topicname=Geoprocessing_framework\nWhat function do you find is missing in the ESRI geoprocessing tools?\nThe GDAL utilities can also be manipulated with Python (and other languages). If there is a utility in the link below that meets your needs then you can use this.\nLink\n",
"geographika's answer is superb. I'll only add that I use gdal/ogr when simplicity and speed is wanted in conversions. Examples include one format to another, adding image pyramids, simple merging and coordinate transformation (raster & vector). When all you want to do is jam a bunch of shapefiles together or convert a large series of rasters to a common projection gdal/ogr is faster to startup and run as it doesn't need to load the whole ArcObjects COM library to access one or two functions. (I've been told ESRI has the largest MS COM system on earth, by a large margin, including all of Microsoft's offerings.) Or check for a valid license. In one test I ran comparing ESRI arcgisscripting to GDAL ogr2ogr processing time went from 6 minutes to 10 seconds.\nThe only significant thing, in the realm of conversion and projection, that I feel is missing from gdal is the ability to log geoprocessing activity in the Lineage section of the metadata. ESRI tools do this automatically (most of the time).\nWhen moving beyond conversion and getting into proper analysis though there really is no place outside of ESRI*. In my experience that is. Before you dig into ArcObjects directly I'd spend some time learning what can be accomplished via arcgisscripting (arcpy in v10), which is python, and dot net.\n* 10 years later: I don't stand behind this statement anymore. Qgis has had a very steady improvement rate throughout the last decade and doesn't show any signs of slowing down. If anything it's been speeding up. True Esri has had significant improvements in the same period as well, but their focus is spread between desktop and online, in favour of the latter. My current recommendation is to look at the respective communities and choose based on which ones have the largest overlap with your own work and interests. It's not (so much) about which platform has what functions, but about who you might best work with.\n",
"ArcObjects and geoprocessing add a lot more functionality than GDAL and is mostly aimed at the desktop. Another option for looking at Python is also using QGIS which has a python API, is Free and Open Source, and an active developer community. \nThere are also plenty of python libraries for doing spatial work, such as Shapely. I would say for raster that GDAL is your best bet but for vector you might want to use something like shapely.\n"
] | [
5,
4,
2
] | [] | [] | [
"arcgis",
"gdal",
"gis",
"python"
] | stackoverflow_0002276235_arcgis_gdal_gis_python.txt |
Q:
Asynchronous daemon processing / ORM interaction with Django
I'm looking for a way to do asynchronous data processing with a daemon that uses Django ORM. However, the ORM isn't thread-safe; it's not thread-safe to try to retrieve / modify django objects from within threads. So I'm wondering what the correct way to achieve asynchrony is?
Basically what I need to accomplish is taking a list of users in the db, querying a third party api and then making updates to user-profile rows for those users. As a daemon or background process. Doing this in series per user is easy, but it takes too long to be at all scalable. If the daemon is retrieving and updating the users through the ORM, how do I achieve processing 10-20 users at a time? I would use a standard threading / queue system for this but you can't thread interactions like
models.User.objects.get(id=foo) ...
Django itself is an asynchronous processing system which makes asynchronous ORM calls(?) for each request, so there should be a way to do it? I haven't found anything in the documentation so far.
Cheers
A:
Have a look at celery . I guess that would solve your problem. It uses multiprocessing module. It needs a (very) little setup, however helps a lot in scaling.
A:
If your asynchronous processing is being done in its own process, then thread safety is not an issue because your threads are not sharing an address space, so they can't interfere with each other. They would each have their own copy of model objects. Concurrency will be controlled by the database with transactions. So your fine.
If your going to spawn a thread inside one of the web server's processes to do your asynchronous business, then you need to lock all API calls that are not thread safe.
from threading import Lock
Apache uses multiple processes via the fork() system call to handle conncurrent web requests. This is why Django's ORM APIs don't need to be thread safe. I believe Apache may be able to use threads instead of processes, but it think that feature has to be disabled in order to use Django.
http://groups.google.com/group/django-developers/browse_thread/thread/905f79e350525c95
Btw, do you understand the difference between a thread and a process? Its kind of important.
| Asynchronous daemon processing / ORM interaction with Django | I'm looking for a way to do asynchronous data processing with a daemon that uses Django ORM. However, the ORM isn't thread-safe; it's not thread-safe to try to retrieve / modify django objects from within threads. So I'm wondering what the correct way to achieve asynchrony is?
Basically what I need to accomplish is taking a list of users in the db, querying a third party api and then making updates to user-profile rows for those users. As a daemon or background process. Doing this in series per user is easy, but it takes too long to be at all scalable. If the daemon is retrieving and updating the users through the ORM, how do I achieve processing 10-20 users at a time? I would use a standard threading / queue system for this but you can't thread interactions like
models.User.objects.get(id=foo) ...
Django itself is an asynchronous processing system which makes asynchronous ORM calls(?) for each request, so there should be a way to do it? I haven't found anything in the documentation so far.
Cheers
| [
"Have a look at celery . I guess that would solve your problem. It uses multiprocessing module. It needs a (very) little setup, however helps a lot in scaling.\n",
"If your asynchronous processing is being done in its own process, then thread safety is not an issue because your threads are not sharing an address space, so they can't interfere with each other. They would each have their own copy of model objects. Concurrency will be controlled by the database with transactions. So your fine.\nIf your going to spawn a thread inside one of the web server's processes to do your asynchronous business, then you need to lock all API calls that are not thread safe.\nfrom threading import Lock\n\nApache uses multiple processes via the fork() system call to handle conncurrent web requests. This is why Django's ORM APIs don't need to be thread safe. I believe Apache may be able to use threads instead of processes, but it think that feature has to be disabled in order to use Django.\nhttp://groups.google.com/group/django-developers/browse_thread/thread/905f79e350525c95\nBtw, do you understand the difference between a thread and a process? Its kind of important.\n"
] | [
3,
2
] | [] | [] | [
"django",
"django_models",
"django_orm",
"python"
] | stackoverflow_0002805914_django_django_models_django_orm_python.txt |
Q:
more efficient way to pickle a string
The pickle module seems to use string escape characters when pickling; this becomes inefficient e.g. on numpy arrays. Consider the following
z = numpy.zeros(1000, numpy.uint8)
len(z.dumps())
len(cPickle.dumps(z.dumps()))
The lengths are 1133 characters and 4249 characters respectively.
z.dumps() reveals something like "\x00\x00" (actual zeros in string), but pickle seems to be using the string's repr() function, yielding "'\x00\x00'" (zeros being ascii zeros).
i.e. ("0" in z.dumps() == False) and ("0" in cPickle.dumps(z.dumps()) == True)
A:
Try using a later version of the pickle protocol with the protocol parameter to pickle.dumps(). The default is 0 and is an ASCII text format. Ones greater than 1 (I suggest you use pickle.HIGHEST_PROTOCOL). Protocol formats 1 and 2 (and 3 but that's for py3k) are binary and should be more space conservative.
A:
Solution:
import zlib, cPickle
def zdumps(obj):
return zlib.compress(cPickle.dumps(obj,cPickle.HIGHEST_PROTOCOL),9)
def zloads(zstr):
return cPickle.loads(zlib.decompress(zstr))
>>> len(zdumps(z))
128
A:
z.dumps() is already pickled string i.e., it can be unpickled using pickle.loads():
>>> z = numpy.zeros(1000, numpy.uint8)
>>> s = z.dumps()
>>> a = pickle.loads(s)
>>> all(a == z)
True
A:
An improvement to vartec's answer, that seems a bit more memory efficient (since it doesn't force everything into a string):
def pickle(fname, obj):
import cPickle, gzip
cPickle.dump(obj=obj, file=gzip.open(fname, "wb", compresslevel=3), protocol=2)
def unpickle(fname):
import cPickle, gzip
return cPickle.load(gzip.open(fname, "rb"))
| more efficient way to pickle a string | The pickle module seems to use string escape characters when pickling; this becomes inefficient e.g. on numpy arrays. Consider the following
z = numpy.zeros(1000, numpy.uint8)
len(z.dumps())
len(cPickle.dumps(z.dumps()))
The lengths are 1133 characters and 4249 characters respectively.
z.dumps() reveals something like "\x00\x00" (actual zeros in string), but pickle seems to be using the string's repr() function, yielding "'\x00\x00'" (zeros being ascii zeros).
i.e. ("0" in z.dumps() == False) and ("0" in cPickle.dumps(z.dumps()) == True)
| [
"Try using a later version of the pickle protocol with the protocol parameter to pickle.dumps(). The default is 0 and is an ASCII text format. Ones greater than 1 (I suggest you use pickle.HIGHEST_PROTOCOL). Protocol formats 1 and 2 (and 3 but that's for py3k) are binary and should be more space conservative.\n",
"Solution:\nimport zlib, cPickle\n\ndef zdumps(obj):\n return zlib.compress(cPickle.dumps(obj,cPickle.HIGHEST_PROTOCOL),9)\n\ndef zloads(zstr):\n return cPickle.loads(zlib.decompress(zstr)) \n\n>>> len(zdumps(z))\n128\n\n",
"z.dumps() is already pickled string i.e., it can be unpickled using pickle.loads():\n>>> z = numpy.zeros(1000, numpy.uint8)\n>>> s = z.dumps()\n>>> a = pickle.loads(s)\n>>> all(a == z)\nTrue\n\n",
"An improvement to vartec's answer, that seems a bit more memory efficient (since it doesn't force everything into a string):\ndef pickle(fname, obj):\n import cPickle, gzip\n cPickle.dump(obj=obj, file=gzip.open(fname, \"wb\", compresslevel=3), protocol=2)\n\ndef unpickle(fname):\n import cPickle, gzip\n return cPickle.load(gzip.open(fname, \"rb\"))\n\n"
] | [
24,
9,
3,
1
] | [] | [] | [
"numpy",
"pickle",
"python",
"space_efficiency"
] | stackoverflow_0000695794_numpy_pickle_python_space_efficiency.txt |
Q:
how do I obtain all the elements of a generator expression I wrote?
I am using google-app-engine webapp, part of the code is :
class Post(db.Model):
title = db.StringProperty(required=True)
def categories(self):
return (x.category for x in self.postcategory_set)
class Category(db.Model):
name = db.StringProperty()
class PostCategory(db.Model):
post = db.ReferenceProperty(Post)
category = db.ReferenceProperty(Category)
class sss(webapp.RequestHandler):
def get(self):
obj1 = Post(title='hhaa')
#obj1.title = 'haha'
obj1.put()
obj2 = Category()
obj2.name='haha-kao'
obj2.put()
obj3=PostCategory()
obj3.post=obj1
obj3.category=obj2
obj3.put()
self.response.out.write(obj1.categories().get().name)
but I get an error:
Traceback (most recent call last):
File "D:\Program Files\Google\google_appengine\google\appengine\ext\webapp\__init__.py", line 511, in __call__
handler.get(*groups)
File "D:\zjm_code\helloworld\a.py", line 131, in get
self.response.out.write(obj1.categories().get().name)
AttributeError: 'generator' object has no attribute 'get'
so how can I obtain all values of the genexp I wrote?
A:
It is categories().next() that you need. Generators have no get.
A:
If you wanted an all method you should return a list comprehension instead of a generator:
return [x.category for x in self.postcategory_set]
but since postcategory_set is already an iterable (because you iterated it)
return self.postcategory_set
would be more natural, but that would give the caller a reference to your private, mutable data, except in this case Post.postcategory_set is not really a set type but rather an instance of google.app.engine.ext.db.Query which is indeed iterable but not mutable.
And you didn't ask, but your model is funny, with the PostCategory table being unnecessary when you could have:
class Post(db.Model):
title = db.StringProperty(required=True)
category = db.ReferenceProperty(Category)
def categories(self):
return list(self.postcategory_set)
And drop PostCategory completely.
| how do I obtain all the elements of a generator expression I wrote? | I am using google-app-engine webapp, part of the code is :
class Post(db.Model):
title = db.StringProperty(required=True)
def categories(self):
return (x.category for x in self.postcategory_set)
class Category(db.Model):
name = db.StringProperty()
class PostCategory(db.Model):
post = db.ReferenceProperty(Post)
category = db.ReferenceProperty(Category)
class sss(webapp.RequestHandler):
def get(self):
obj1 = Post(title='hhaa')
#obj1.title = 'haha'
obj1.put()
obj2 = Category()
obj2.name='haha-kao'
obj2.put()
obj3=PostCategory()
obj3.post=obj1
obj3.category=obj2
obj3.put()
self.response.out.write(obj1.categories().get().name)
but I get an error:
Traceback (most recent call last):
File "D:\Program Files\Google\google_appengine\google\appengine\ext\webapp\__init__.py", line 511, in __call__
handler.get(*groups)
File "D:\zjm_code\helloworld\a.py", line 131, in get
self.response.out.write(obj1.categories().get().name)
AttributeError: 'generator' object has no attribute 'get'
so how can I obtain all values of the genexp I wrote?
| [
"It is categories().next() that you need. Generators have no get. \n",
"If you wanted an all method you should return a list comprehension instead of a generator: \nreturn [x.category for x in self.postcategory_set]\n\nbut since postcategory_set is already an iterable (because you iterated it) \nreturn self.postcategory_set\n\nwould be more natural, but that would give the caller a reference to your private, mutable data, except in this case Post.postcategory_set is not really a set type but rather an instance of google.app.engine.ext.db.Query which is indeed iterable but not mutable.\nAnd you didn't ask, but your model is funny, with the PostCategory table being unnecessary when you could have:\nclass Post(db.Model):\n title = db.StringProperty(required=True)\n category = db.ReferenceProperty(Category)\n def categories(self):\n return list(self.postcategory_set)\n\nAnd drop PostCategory completely. \n"
] | [
1,
1
] | [] | [] | [
"google_app_engine",
"python",
"referenceproperty"
] | stackoverflow_0002807841_google_app_engine_python_referenceproperty.txt |
Q:
Scipy-Cluster installation for python 2.6
Has anyone used scipy-cluster for python? I am trying to compile its source code with python 2.6 but I get some irrelevant errors. has someone had the same problem?
A:
apt-get install python-hcluster worked for me on Ubuntu 10.04.
| Scipy-Cluster installation for python 2.6 | Has anyone used scipy-cluster for python? I am trying to compile its source code with python 2.6 but I get some irrelevant errors. has someone had the same problem?
| [
"apt-get install python-hcluster worked for me on Ubuntu 10.04.\n"
] | [
0
] | [] | [] | [
"python",
"scipy"
] | stackoverflow_0002805772_python_scipy.txt |
Q:
How do I retrieve program output in Python?
I'm not a Perl user, but from this question deduced that it's exceedingly easy to retrieve the standard output of a program executed through a Perl script using something akin to:
$version = `java -version`;
How would I go about getting the same end result in Python? Does the above line retrieve standard error (equivalent to C++ std::cerr) and standard log (std::clog) output as well? If not, how can I retrieve those output streams as well?
Thanks,
Geoff
A:
For python 2.5: sadly, no. You need to use subprocess:
import subprocess
proc = subprocess.Popen(['java', '-version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = proc.communicate()
Docs are at http://docs.python.org/library/subprocess.html
A:
In Python 2.7+
from subprocess import check_output as qx
output = qx(['java', '-version'])
The answer to Capturing system command output as a string question has implementation for Python < 2.7.
A:
As others have mentioned you want to use the Python subprocess module for this.
If you really want something that's more succinct you can create a function like:
#!/usr/bin/env python
import subprocess, shlex
def captcmd(cmd):
proc = subprocess.Popen(shlex.split(cmd), \
stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False)
out, err = proc.communicate()
ret = proc.returncode
return (ret, out, err)
... then you can call that as:
ok, o, e = captcmd('ls -al /foo /bar ...')
print o
if not ok:
print >> sys.stderr, "There was an error (%d):\n" % ok
print >> sys.stderr, e
... or whatever.
Note: I'm using shlex.split() as a vastly safer alternative to shell=True
Naturally you could write this to suit your own tastes. Of course for every call you have to either provide three names into which it can unpack the result tuple or you'd have to pull the desired output from the result using normal indexing (captcmd(...)[1] for the output, for example). Naturally you could write a variation of this function to combine stdout and stderr and to discard the result code. Those "features" would make it more like the Perl backtick expressions. (Do that and take out the shlex.split() call and you have something that's as crude and unsafe as what Perl does, in fact).
| How do I retrieve program output in Python? | I'm not a Perl user, but from this question deduced that it's exceedingly easy to retrieve the standard output of a program executed through a Perl script using something akin to:
$version = `java -version`;
How would I go about getting the same end result in Python? Does the above line retrieve standard error (equivalent to C++ std::cerr) and standard log (std::clog) output as well? If not, how can I retrieve those output streams as well?
Thanks,
Geoff
| [
"For python 2.5: sadly, no. You need to use subprocess:\nimport subprocess\nproc = subprocess.Popen(['java', '-version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\nout, err = proc.communicate()\n\nDocs are at http://docs.python.org/library/subprocess.html\n",
"In Python 2.7+\nfrom subprocess import check_output as qx\n\noutput = qx(['java', '-version'])\n\nThe answer to Capturing system command output as a string question has implementation for Python < 2.7.\n",
"As others have mentioned you want to use the Python subprocess module for this.\nIf you really want something that's more succinct you can create a function like:\n#!/usr/bin/env python \nimport subprocess, shlex\n\ndef captcmd(cmd):\n proc = subprocess.Popen(shlex.split(cmd), \\\n stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False)\n\n out, err = proc.communicate()\n ret = proc.returncode\n return (ret, out, err)\n\n... then you can call that as:\nok, o, e = captcmd('ls -al /foo /bar ...')\nprint o\nif not ok:\n print >> sys.stderr, \"There was an error (%d):\\n\" % ok\n print >> sys.stderr, e\n\n... or whatever.\nNote: I'm using shlex.split() as a vastly safer alternative to shell=True\nNaturally you could write this to suit your own tastes. Of course for every call you have to either provide three names into which it can unpack the result tuple or you'd have to pull the desired output from the result using normal indexing (captcmd(...)[1] for the output, for example). Naturally you could write a variation of this function to combine stdout and stderr and to discard the result code. Those \"features\" would make it more like the Perl backtick expressions. (Do that and take out the shlex.split() call and you have something that's as crude and unsafe as what Perl does, in fact).\n"
] | [
7,
6,
4
] | [] | [] | [
"c++",
"perl",
"python"
] | stackoverflow_0002804194_c++_perl_python.txt |
Q:
Google App Engine: 403 and 404 error
How do I implement using python if I want to manage the 403 and 404 error, for example, to know which URL is most the 403 or 404 error?
A:
There is no need to do this manually on App Engine. Just take a look at the "Errors" section in the dashboard for your app.
For more information on this, see http://code.google.com/intl/de-DE/appengine/kb/general.html#erroruris
| Google App Engine: 403 and 404 error | How do I implement using python if I want to manage the 403 and 404 error, for example, to know which URL is most the 403 or 404 error?
| [
"There is no need to do this manually on App Engine. Just take a look at the \"Errors\" section in the dashboard for your app.\nFor more information on this, see http://code.google.com/intl/de-DE/appengine/kb/general.html#erroruris\n"
] | [
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0002808416_google_app_engine_python.txt |
Q:
Are there any Bayeux clients in Python?
I need to connect to a Bayeux server form a wxPython APP.
I would appreciate any hint about that.
A:
Ok I've found an example client here:
http://svn.cometd.com/trunk/cometd-twisted/
| Are there any Bayeux clients in Python? | I need to connect to a Bayeux server form a wxPython APP.
I would appreciate any hint about that.
| [
"Ok I've found an example client here:\nhttp://svn.cometd.com/trunk/cometd-twisted/\n"
] | [
6
] | [] | [] | [
"bayeux",
"cometd",
"python"
] | stackoverflow_0002809202_bayeux_cometd_python.txt |
Q:
Installing Python egg dependencies without apt-get
I've got a Python module which is distributed on PyPI, and therefore installable using easy_install. It depends on lxml, which in turn depends on libxslt1-dev. I'm unable to install libxslt1-dev with easy_install, so it doesn't work to put it in install_requires. Is there any way I can get setuptools to install it instead of resorting to apt-get?
A:
It's better use apt-get to install lxml (or the python packages that has c extensions) and then pull pure python package from pypi. Also I generally try to avoid using easy_install for top level install, I rather create a virtual env using virtualenv and then use easy_install created by virtualenv to keep my setups clean.
This strategy is working successfully for me for couple of production environments.
A:
setuptools can only install Python packages that in the package index you are using, either the default index of the one you specify with easy_install -i http://myindex.site/index.
Any non-Python dependencies have to be installed using the standard installation package for the platform (apt-get on Debian based Linux distros). libxml2 and libxslt fall into this category so you should install these in the standard way.
| Installing Python egg dependencies without apt-get | I've got a Python module which is distributed on PyPI, and therefore installable using easy_install. It depends on lxml, which in turn depends on libxslt1-dev. I'm unable to install libxslt1-dev with easy_install, so it doesn't work to put it in install_requires. Is there any way I can get setuptools to install it instead of resorting to apt-get?
| [
"It's better use apt-get to install lxml (or the python packages that has c extensions) and then pull pure python package from pypi. Also I generally try to avoid using easy_install for top level install, I rather create a virtual env using virtualenv and then use easy_install created by virtualenv to keep my setups clean.\nThis strategy is working successfully for me for couple of production environments.\n",
"setuptools can only install Python packages that in the package index you are using, either the default index of the one you specify with easy_install -i http://myindex.site/index.\nAny non-Python dependencies have to be installed using the standard installation package for the platform (apt-get on Debian based Linux distros). libxml2 and libxslt fall into this category so you should install these in the standard way.\n"
] | [
1,
1
] | [] | [] | [
"installation",
"packaging",
"python",
"setuptools"
] | stackoverflow_0002808956_installation_packaging_python_setuptools.txt |
Q:
sort a list of percentages
I have the following list:
l = ['50%','12.5%','6.25%','25%']
Which I would like to sort in the following order:
['6.25%','12.5%','25%','50%']
Using l.sort() yields:
['12.5%','25%','50%','6.25%']
Any cool tricks to sort these lists easily in Python?
A:
You can sort with a custom key
b =['52.5%', '62.4%', '91.8%', '21.5%']
b.sort(key = lambda a: float(a[:-1]))
This resorts the set, but uses the numerical value as the key (i.e. chops of the '%' in the string and converts to float.
| sort a list of percentages | I have the following list:
l = ['50%','12.5%','6.25%','25%']
Which I would like to sort in the following order:
['6.25%','12.5%','25%','50%']
Using l.sort() yields:
['12.5%','25%','50%','6.25%']
Any cool tricks to sort these lists easily in Python?
| [
"You can sort with a custom key\nb =['52.5%', '62.4%', '91.8%', '21.5%']\nb.sort(key = lambda a: float(a[:-1]))\n\nThis resorts the set, but uses the numerical value as the key (i.e. chops of the '%' in the string and converts to float.\n"
] | [
17
] | [] | [] | [
"list",
"python",
"sorting"
] | stackoverflow_0002809415_list_python_sorting.txt |
Q:
Can I just broadcast a specific message in my own network in python?
I just want to broadcast a udp message on a specific port on my network. How can I accomplish this in python?
A:
This will only work with IPv4 networks:
BC_PORT = 12345
import sys, time
from socket import *
s = socket(AF_INET, SOCK_DGRAM)
s.bind(('', 0))
s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
s.sendto("hello world", ('<broadcast>', BC_PORT))
| Can I just broadcast a specific message in my own network in python? | I just want to broadcast a udp message on a specific port on my network. How can I accomplish this in python?
| [
"This will only work with IPv4 networks:\nBC_PORT = 12345\nimport sys, time\nfrom socket import *\ns = socket(AF_INET, SOCK_DGRAM)\ns.bind(('', 0))\ns.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)\ns.sendto(\"hello world\", ('<broadcast>', BC_PORT))\n\n"
] | [
5
] | [] | [] | [
"python"
] | stackoverflow_0002809392_python.txt |
Q:
Writing csv header removes data from numpy array written below
I'm trying to export data to a csv file. It should contain a header (from datastack) and restacked arrays with my data (from datastack). One line in datastack has the same length as dataset. The code below works but it removes parts of the first line from datastack. Any ideas why that could be?
s = ','.join(itertools.chain(dataset)) + '\n'
newfile = 'export.csv'
f = open(newfile,'w')
f.write(s)
numpy.savetxt(newfile, (numpy.transpose(datastack)), delimiter=', ')
f.close()
A:
You a file with the filename 'export.csv' twice, once when you call open() and once when you call numpy.savetxt(). Thus, there are two open file handles competing for the same filename. If you pass the file handle rather than the file name to numpy.savetxt() you avoid this race condition:
s = ','.join(itertools.chain(dataset)) + '\n'
newfile = 'export.csv'
f = open(newfile,'w')
f.write(s)
numpy.savetxt(f, (numpy.transpose(datastack)), delimiter=', ')
f.close()
| Writing csv header removes data from numpy array written below | I'm trying to export data to a csv file. It should contain a header (from datastack) and restacked arrays with my data (from datastack). One line in datastack has the same length as dataset. The code below works but it removes parts of the first line from datastack. Any ideas why that could be?
s = ','.join(itertools.chain(dataset)) + '\n'
newfile = 'export.csv'
f = open(newfile,'w')
f.write(s)
numpy.savetxt(newfile, (numpy.transpose(datastack)), delimiter=', ')
f.close()
| [
"You a file with the filename 'export.csv' twice, once when you call open() and once when you call numpy.savetxt(). Thus, there are two open file handles competing for the same filename. If you pass the file handle rather than the file name to numpy.savetxt() you avoid this race condition:\ns = ','.join(itertools.chain(dataset)) + '\\n'\nnewfile = 'export.csv'\nf = open(newfile,'w')\nf.write(s)\nnumpy.savetxt(f, (numpy.transpose(datastack)), delimiter=', ')\nf.close()\n\n"
] | [
6
] | [] | [] | [
"csv",
"numpy",
"python"
] | stackoverflow_0002809478_csv_numpy_python.txt |
Q:
Python byte per byte XOR decryption
I have an XOR encypted file by a VB.net program using this function to scramble:
Public Class Crypter
...
'This Will convert String to bytes, then call the other function.
Public Function Crypt(ByVal Data As String) As String
Return Encoding.Default.GetString(Crypt(Encoding.Default.GetBytes(Data)))
End Function
'This calls XorCrypt giving Key converted to bytes
Public Function Crypt(ByVal Data() As Byte) As Byte()
Return XorCrypt(Data, Encoding.Default.GetBytes(Me.Key))
End Function
'Xor Encryption.
Private Function XorCrypt(ByVal Data() As Byte, ByVal Key() As Byte) As Byte()
Dim i As Integer
If Key.Length <> 0 Then
For i = 0 To Data.Length - 1
Data(i) = Data(i) Xor Key(i Mod Key.Length)
Next
End If
Return Data
End Function
End Class
and saved this way:
Dim Crypter As New Cryptic(Key)
'open destination file
Dim objWriter As New StreamWriter(fileName)
'write crypted content
objWriter.Write(Crypter.Crypt(data))
Now I have to reopen the file with Python but I have troubles getting single bytes, this is the XOR function in python:
def crypto(self, data):
'crypto(self, data) -> str'
return ''.join(chr((ord(x) ^ ord(y)) % 256) \
for (x, y) in izip(data.decode('utf-8'), cycle(self.key))
I had to add the % 256 since sometimes x is > 256 i.e. not a single byte.
This thing of two bytes being passed does not break the decryption because the key keeps "paired" with the following data.
The problem is some decrypted character in the conversion is wrong.
These chars are all accented letters like à, è, ì but just a few of the overall accented letters. The others are all correctly restored.
I guess it could be due to the 256 mod but without it I of course get a chr exception...
Thanks for your support
A:
Your decoded data appears to contain unicode characters with values above 256. In Python 2.x chr can only handle values below 256. Use unichr instead of chr and it should work:
return ''.join(unichr((ord(x) ^ ord(y))) \
for (x, y) in izip(data.decode('utf-8'), cycle(self.key))
A:
is it correct to save scrambled data as string (i.e. re-encoded with default encoding) with StreamWriter? Wouldn't be correct to save bytes directly?
Or is it the same thing?
Dim objWriter As New StreamWriter(fileName)
objWriter.Write(Crypter.Crypt(data))
Which Crypter.Crypt is called by StreamWriter.Write?
This
Public Function Crypt(ByVal Data() As Byte) As Byte()
or this?
Public Function Crypt(ByVal Data As String) As String
I'm not handy with Vb.net...
I've run this to get what chars are involved in the right/wrong "²" conversion
for (x, y) in izip(data.decode('utf-8'), cycle(self.key.decode('utf-8'))):
if (ord(x) ^ ord(y)) > 255 or chr(ord(x) ^ ord(y)) == '\xb2':
print (x, y, chr((ord(x) ^ ord(y)) % 256),
unichr(ord(x) ^ ord(y)), ord(x), ord(y))
I got this:
ù K ² ² 249 75
 p ² ² 194 112
Æ t ² ² 198 116
‚ 0 * 8218 48
the last one is wrong because a double byte is used... but if just one would be passed probably the rest of the decryption would result outh of phase
A:
If you're opening the file in text mode, it might be interpreted as Unicode text. Try opening it in binary mode to make all characters into bytes. That should avoid your issues with chr. If you're using Python 3.x, do remember that when working in binary mode you should be using bytes literals rather than string literals, the latter of which are Unicode strings by design.
A:
Indeed, the following line is wrong:
Return Encoding.Default.GetString(Crypt(Encoding.Default.GetBytes(Data)))
There's no general guarantee that the bytes being returned from Crypt are valid to decode as a string. You'd be better using Convert.ToBase64String, and then passing that string to your Python code (where obviously, you'd need to be able to Base-64 decode the bytes.
And as others have pointed out, the level of security XORing provides is adequate to protect your data from, maybe, your little sister.
| Python byte per byte XOR decryption | I have an XOR encypted file by a VB.net program using this function to scramble:
Public Class Crypter
...
'This Will convert String to bytes, then call the other function.
Public Function Crypt(ByVal Data As String) As String
Return Encoding.Default.GetString(Crypt(Encoding.Default.GetBytes(Data)))
End Function
'This calls XorCrypt giving Key converted to bytes
Public Function Crypt(ByVal Data() As Byte) As Byte()
Return XorCrypt(Data, Encoding.Default.GetBytes(Me.Key))
End Function
'Xor Encryption.
Private Function XorCrypt(ByVal Data() As Byte, ByVal Key() As Byte) As Byte()
Dim i As Integer
If Key.Length <> 0 Then
For i = 0 To Data.Length - 1
Data(i) = Data(i) Xor Key(i Mod Key.Length)
Next
End If
Return Data
End Function
End Class
and saved this way:
Dim Crypter As New Cryptic(Key)
'open destination file
Dim objWriter As New StreamWriter(fileName)
'write crypted content
objWriter.Write(Crypter.Crypt(data))
Now I have to reopen the file with Python but I have troubles getting single bytes, this is the XOR function in python:
def crypto(self, data):
'crypto(self, data) -> str'
return ''.join(chr((ord(x) ^ ord(y)) % 256) \
for (x, y) in izip(data.decode('utf-8'), cycle(self.key))
I had to add the % 256 since sometimes x is > 256 i.e. not a single byte.
This thing of two bytes being passed does not break the decryption because the key keeps "paired" with the following data.
The problem is some decrypted character in the conversion is wrong.
These chars are all accented letters like à, è, ì but just a few of the overall accented letters. The others are all correctly restored.
I guess it could be due to the 256 mod but without it I of course get a chr exception...
Thanks for your support
| [
"Your decoded data appears to contain unicode characters with values above 256. In Python 2.x chr can only handle values below 256. Use unichr instead of chr and it should work:\nreturn ''.join(unichr((ord(x) ^ ord(y))) \\\n for (x, y) in izip(data.decode('utf-8'), cycle(self.key))\n\n",
"is it correct to save scrambled data as string (i.e. re-encoded with default encoding) with StreamWriter? Wouldn't be correct to save bytes directly?\nOr is it the same thing?\nDim objWriter As New StreamWriter(fileName)\nobjWriter.Write(Crypter.Crypt(data))\n\nWhich Crypter.Crypt is called by StreamWriter.Write?\nThis\nPublic Function Crypt(ByVal Data() As Byte) As Byte()\n\nor this?\nPublic Function Crypt(ByVal Data As String) As String\n\nI'm not handy with Vb.net...\n\nI've run this to get what chars are involved in the right/wrong \"²\" conversion\nfor (x, y) in izip(data.decode('utf-8'), cycle(self.key.decode('utf-8'))):\n if (ord(x) ^ ord(y)) > 255 or chr(ord(x) ^ ord(y)) == '\\xb2':\n print (x, y, chr((ord(x) ^ ord(y)) % 256),\n unichr(ord(x) ^ ord(y)), ord(x), ord(y))\n\nI got this:\nù K ² ² 249 75\n p ² ² 194 112\nÆ t ² ² 198 116\n‚ 0 * 8218 48\n\nthe last one is wrong because a double byte is used... but if just one would be passed probably the rest of the decryption would result outh of phase\n",
"If you're opening the file in text mode, it might be interpreted as Unicode text. Try opening it in binary mode to make all characters into bytes. That should avoid your issues with chr. If you're using Python 3.x, do remember that when working in binary mode you should be using bytes literals rather than string literals, the latter of which are Unicode strings by design.\n",
"Indeed, the following line is wrong:\nReturn Encoding.Default.GetString(Crypt(Encoding.Default.GetBytes(Data)))\n\nThere's no general guarantee that the bytes being returned from Crypt are valid to decode as a string. You'd be better using Convert.ToBase64String, and then passing that string to your Python code (where obviously, you'd need to be able to Base-64 decode the bytes.\nAnd as others have pointed out, the level of security XORing provides is adequate to protect your data from, maybe, your little sister.\n"
] | [
3,
2,
1,
1
] | [] | [] | [
"encryption",
"python",
"xor"
] | stackoverflow_0002806423_encryption_python_xor.txt |
Q:
Efficient way to combine results of two database queries
I have two tables on different servers, and I'd like some help finding an efficient way to combine and match the datasets. Here's an example:
From server 1, which holds our stories, I perform a query like:
query = """SELECT author_id, title, text
FROM stories
ORDER BY timestamp_created DESC
LIMIT 10
"""
results = DB.getAll(query)
for i in range(len(results)):
#Build a string of author_ids, e.g. '1314,4134,2624,2342'
But, I'd like to fetch some info about each author_id from server 2:
query = """SELECT id, avatar_url
FROM members
WHERE id IN (%s)
"""
values = (uid_list)
results = DB.getAll(query, values)
Now I need some way to combine these two queries so I have a dict that has the story as well as avatar_url and member_id.
If this data were on one server, it would be a simple join that would look like:
SELECT *
FROM members, stories
WHERE members.id = stories.author_id
But since we store the data on multiple servers, this is not possible.
What is the most efficient way to do this? I understand the merging probably has to happen in my application code ... any efficient sample code that minimizes the number of dict loops would be greatly appreciated!
Thanks.
A:
If memory isn't a problem, you could use a dictionary.
results1_dict = dict((row[0], list(row[1:])) for row in results1)
results2_dict = dict((row[0], list(row[1:])) for row in results2)
for key, value in results2_dict:
if key in results1_dict:
results1_dict[key].extend(value)
else:
results1_dict[key] = value
This isn't particularly efficient (n2), but it is relatively simple and you can tweak it to do precisely what you need.
A:
You will have to bring the data together somehow.
There are things like server links (though that is probably not the correct term in mysql context) that might allow querying accross different DBs. This opens up another set of problems (security!)
The easier solution is to bring the data together in one DB.
The last (least desirable) solution is to join in code as Padmarag suggests.
A:
The only option looks to be Database Link, but is unfortunately unavailable in MySQL.
You'll have to do the merging in your application code. Better to keep the data in same database.
A:
Is it possible to setup replication of the needed tables from one server to a database on the other?
That way you could have all your data on one server.
Also, see FEDERATED storage engine, available since mysql 5.0.3.
| Efficient way to combine results of two database queries | I have two tables on different servers, and I'd like some help finding an efficient way to combine and match the datasets. Here's an example:
From server 1, which holds our stories, I perform a query like:
query = """SELECT author_id, title, text
FROM stories
ORDER BY timestamp_created DESC
LIMIT 10
"""
results = DB.getAll(query)
for i in range(len(results)):
#Build a string of author_ids, e.g. '1314,4134,2624,2342'
But, I'd like to fetch some info about each author_id from server 2:
query = """SELECT id, avatar_url
FROM members
WHERE id IN (%s)
"""
values = (uid_list)
results = DB.getAll(query, values)
Now I need some way to combine these two queries so I have a dict that has the story as well as avatar_url and member_id.
If this data were on one server, it would be a simple join that would look like:
SELECT *
FROM members, stories
WHERE members.id = stories.author_id
But since we store the data on multiple servers, this is not possible.
What is the most efficient way to do this? I understand the merging probably has to happen in my application code ... any efficient sample code that minimizes the number of dict loops would be greatly appreciated!
Thanks.
| [
"If memory isn't a problem, you could use a dictionary.\nresults1_dict = dict((row[0], list(row[1:])) for row in results1)\nresults2_dict = dict((row[0], list(row[1:])) for row in results2)\n\nfor key, value in results2_dict:\n if key in results1_dict:\n results1_dict[key].extend(value)\n else:\n results1_dict[key] = value\n\nThis isn't particularly efficient (n2), but it is relatively simple and you can tweak it to do precisely what you need.\n",
"You will have to bring the data together somehow. \n\nThere are things like server links (though that is probably not the correct term in mysql context) that might allow querying accross different DBs. This opens up another set of problems (security!)\nThe easier solution is to bring the data together in one DB.\nThe last (least desirable) solution is to join in code as Padmarag suggests. \n\n",
"The only option looks to be Database Link, but is unfortunately unavailable in MySQL.\nYou'll have to do the merging in your application code. Better to keep the data in same database.\n",
"Is it possible to setup replication of the needed tables from one server to a database on the other?\nThat way you could have all your data on one server.\nAlso, see FEDERATED storage engine, available since mysql 5.0.3.\n"
] | [
2,
0,
0,
0
] | [] | [] | [
"database",
"mysql",
"pylons",
"python",
"sharding"
] | stackoverflow_0002808142_database_mysql_pylons_python_sharding.txt |
Q:
Sleeping a thread is blocking stdin
I'm running a function which evaluates commands passed in using stdin and another function which runs a bunch of jobs. I need to make the latter function sleep at regular intervals but that seems to be blocking the stdin. Any advice on how to resolve this would be appreciated.
The source code for the functions is
def runJobs(comps, jobQueue, numRunning, limit, lock):
while len(jobQueue) >= 0:
print(len(jobQueue));
if len(jobQueue) > 0:
comp, tasks = find_computer(comps, 0);
#do something
time.sleep(5);
def manageStdin():
print "Global Stdin Begins Now"
for line in fileinput.input():
try:
print(eval(line));
except Exception, e:
print e;
--Thanks
A:
Use a single thread:
import time
import select
import logging
import sys
def stdinWait(interval):
start = time.time()
while True:
time_left = interval - (time.time() - start)
if time_left <= 0:
break
r, w, x = select.select([sys.stdin], [], [], time_left)
if r:
line = r[0].readline()
try:
print(eval(line));
except Exception, e:
logging.exception(e)
def runJobs(comps, jobQueue, numRunning, limit, lock):
while len(jobQueue) >= 0:
print(len(jobQueue));
if len(jobQueue) > 0:
comp, tasks = find_computer(comps, 0);
#do something
stdinWait(5) # wait 5 seconds while watching stdin
| Sleeping a thread is blocking stdin | I'm running a function which evaluates commands passed in using stdin and another function which runs a bunch of jobs. I need to make the latter function sleep at regular intervals but that seems to be blocking the stdin. Any advice on how to resolve this would be appreciated.
The source code for the functions is
def runJobs(comps, jobQueue, numRunning, limit, lock):
while len(jobQueue) >= 0:
print(len(jobQueue));
if len(jobQueue) > 0:
comp, tasks = find_computer(comps, 0);
#do something
time.sleep(5);
def manageStdin():
print "Global Stdin Begins Now"
for line in fileinput.input():
try:
print(eval(line));
except Exception, e:
print e;
--Thanks
| [
"Use a single thread:\nimport time\nimport select\nimport logging\nimport sys\n\ndef stdinWait(interval):\n start = time.time()\n while True:\n time_left = interval - (time.time() - start)\n if time_left <= 0:\n break\n r, w, x = select.select([sys.stdin], [], [], time_left)\n if r:\n line = r[0].readline()\n try:\n print(eval(line));\n except Exception, e:\n logging.exception(e)\n\ndef runJobs(comps, jobQueue, numRunning, limit, lock):\n while len(jobQueue) >= 0:\n print(len(jobQueue));\n if len(jobQueue) > 0:\n comp, tasks = find_computer(comps, 0);\n #do something\n stdinWait(5) # wait 5 seconds while watching stdin\n\n"
] | [
1
] | [] | [] | [
"multithreading",
"python",
"sleep",
"time"
] | stackoverflow_0002809282_multithreading_python_sleep_time.txt |
Q:
Routing Skype call to another Voip company
As my project to do over this summer I would like to create a program that answers a Skype call using the Skype API and allows a user to connect to another VOIP provider (through SIP) and make calls by dialling through the client callers Skype application.
I understand that the Skype API allows me to answer and receive keypad input, but I'm stuck on actually sending the sound of the call to a SIP client.
Is there an API/library that would allow me to take the Skype receiving audio as input in the SIP client?
Is this even possible?
I'm not tied to a language but I had planned on using Python.
Thanks.
A:
I think you'll have to hook into your OS' sound processing.
On Windows, you could install Virtual Audio Cable and configure Skype to use those virtual devices. Since nothing else will use them you can just capture and send sound from/to them to "talk" with Skype.
| Routing Skype call to another Voip company | As my project to do over this summer I would like to create a program that answers a Skype call using the Skype API and allows a user to connect to another VOIP provider (through SIP) and make calls by dialling through the client callers Skype application.
I understand that the Skype API allows me to answer and receive keypad input, but I'm stuck on actually sending the sound of the call to a SIP client.
Is there an API/library that would allow me to take the Skype receiving audio as input in the SIP client?
Is this even possible?
I'm not tied to a language but I had planned on using Python.
Thanks.
| [
"I think you'll have to hook into your OS' sound processing.\nOn Windows, you could install Virtual Audio Cable and configure Skype to use those virtual devices. Since nothing else will use them you can just capture and send sound from/to them to \"talk\" with Skype.\n"
] | [
1
] | [] | [] | [
"api",
"python",
"skype",
"voip"
] | stackoverflow_0002805595_api_python_skype_voip.txt |
Q:
Can I get the raw SQL generated by a prepared statement in Python’s sqlite3 module?
If so, how can I do this?
A:
When executing a prepared statement, no new SQL is generated.
The idea of prepared statements is that the SQL query and its data are transmitted separately (that's why you don't have to escape any arguments) - the query is most likely only stored in an optimized form after preparing it.
A:
when you create a prepared statement, the "template" SQL code is sent to the DBMS already, which compiles it into an expression tree. When you pass the values, the corresponding library (python sqlite3 module in your case) doesn't merge the values into the statement. The DBMS does.
If you still want to produce a normal SQL string, you can use string replace functions to replace the placeholders by the values (after escaping them).
What do you need this for?
| Can I get the raw SQL generated by a prepared statement in Python’s sqlite3 module? | If so, how can I do this?
| [
"When executing a prepared statement, no new SQL is generated.\nThe idea of prepared statements is that the SQL query and its data are transmitted separately (that's why you don't have to escape any arguments) - the query is most likely only stored in an optimized form after preparing it.\n",
"when you create a prepared statement, the \"template\" SQL code is sent to the DBMS already, which compiles it into an expression tree. When you pass the values, the corresponding library (python sqlite3 module in your case) doesn't merge the values into the statement. The DBMS does.\nIf you still want to produce a normal SQL string, you can use string replace functions to replace the placeholders by the values (after escaping them).\nWhat do you need this for?\n"
] | [
2,
1
] | [] | [] | [
"pysqlite",
"python",
"sqlite"
] | stackoverflow_0002810235_pysqlite_python_sqlite.txt |
Q:
python socket problem
I write this python code:
import socks
import socket
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "64.83.219.7", 58279)
socket.socket = socks.socksocket
socket.setdefaulttimeout(19)
import urllib2
print urllib2.urlopen('http://www.google.com').read()
but when I execute it, I get this error:
urllib2.URLError: <urlopen error timed out>
What am I doing wrong?
A:
Something timed out in your script. I guess the connection to google because of wrong proxy setup. I think your goal is to fetch the contents of http://www.google.com through a proxy?
I don't know about this method to set it using socket/socks module. Maybe you want to take a look at the following chapters in the python documentation:
http://docs.python.org/library/urllib2.html?highlight=urllib2#examples (code sinppet 5 and the text above)
http://docs.python.org/library/urllib2.html?highlight=urllib2#urllib2.Request.set_proxy
http://docs.python.org/library/urllib2.html?highlight=urllib2#proxyhandler-objects
| python socket problem | I write this python code:
import socks
import socket
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "64.83.219.7", 58279)
socket.socket = socks.socksocket
socket.setdefaulttimeout(19)
import urllib2
print urllib2.urlopen('http://www.google.com').read()
but when I execute it, I get this error:
urllib2.URLError: <urlopen error timed out>
What am I doing wrong?
| [
"Something timed out in your script. I guess the connection to google because of wrong proxy setup. I think your goal is to fetch the contents of http://www.google.com through a proxy?\nI don't know about this method to set it using socket/socks module. Maybe you want to take a look at the following chapters in the python documentation:\nhttp://docs.python.org/library/urllib2.html?highlight=urllib2#examples (code sinppet 5 and the text above)\nhttp://docs.python.org/library/urllib2.html?highlight=urllib2#urllib2.Request.set_proxy\nhttp://docs.python.org/library/urllib2.html?highlight=urllib2#proxyhandler-objects\n"
] | [
2
] | [] | [] | [
"python",
"sockets",
"socks"
] | stackoverflow_0002810256_python_sockets_socks.txt |
Q:
GTK Progressbar pulsing python
How can I get a Progressbar to "pulse" while another function is run?
A:
Push that another function into a separate thread. As long as your main thread runs any code, GUI is frozen. This is not a problem for short code pieces, but obviously a problem in your case.
Also read what PyGTK FAQ has to say about using threads in PyGTK program.
A:
There is an example of how to do this here.
A:
If your function runs in many iterations that don't take too long by themselves, then you don't necessarily need to mess around with separate threads. You can also cause the GUI to update itself during your long calculation:
def long_function(some_args):
while task_is_not_finished():
do_some_stuff_that_doesnt_take_too_long()
progress_bar.pulse()
while gtk.events_pending():
gtk.main_iteration()
| GTK Progressbar pulsing python | How can I get a Progressbar to "pulse" while another function is run?
| [
"Push that another function into a separate thread. As long as your main thread runs any code, GUI is frozen. This is not a problem for short code pieces, but obviously a problem in your case.\nAlso read what PyGTK FAQ has to say about using threads in PyGTK program.\n",
"There is an example of how to do this here.\n",
"If your function runs in many iterations that don't take too long by themselves, then you don't necessarily need to mess around with separate threads. You can also cause the GUI to update itself during your long calculation:\ndef long_function(some_args):\n while task_is_not_finished():\n do_some_stuff_that_doesnt_take_too_long()\n progress_bar.pulse()\n while gtk.events_pending():\n gtk.main_iteration()\n\n"
] | [
1,
1,
0
] | [] | [] | [
"gtk",
"python"
] | stackoverflow_0002805455_gtk_python.txt |
Q:
Making a CharField use a PasswordInput in the admin
I have a Django site in which the site admin inputs their Twitter Username/Password in order to use the Twitter API. The Model is set up like this:
class TwitterUser(models.Model):
screen_name = models.CharField(max_length=100)
password = models.CharField(max_length=255)
def __unicode__(self):
return self.screen_name
I need the Admin site to display the password field as a password input, but can't seem to figure out how to do it. I have tried using a ModelAdmin class, a ModelAdmin with a ModelForm, but can't seem to figure out how to make django display that form as a password input...
A:
From the docs, you can build your own form, something like this:
from django.forms import ModelForm, PasswordInput
class TwitterUserForm(ModelForm):
class Meta:
model = TwitterUser
widgets = {
'password': PasswordInput(),
}
Or you can do it like this:
from django.forms import ModelForm, PasswordInput
class TwitterUserForm(ModelForm):
password = forms.CharField(widget=PasswordInput())
class Meta:
model = TwitterUser
I've no idea which one is better - I slightly prefer the first one, since it means you'll still get any help_text and verbose_name from your model.
Regardless of which of those two approaches you take, you can then make the admin use your form like this (in your app's admin.py):
from django.contrib import admin
class TwitterUserAdmin(admin.ModelAdmin):
form = TwitterUserForm
admin.site.register(TwitterUser, TwitterUserAdmin)
| Making a CharField use a PasswordInput in the admin | I have a Django site in which the site admin inputs their Twitter Username/Password in order to use the Twitter API. The Model is set up like this:
class TwitterUser(models.Model):
screen_name = models.CharField(max_length=100)
password = models.CharField(max_length=255)
def __unicode__(self):
return self.screen_name
I need the Admin site to display the password field as a password input, but can't seem to figure out how to do it. I have tried using a ModelAdmin class, a ModelAdmin with a ModelForm, but can't seem to figure out how to make django display that form as a password input...
| [
"From the docs, you can build your own form, something like this:\nfrom django.forms import ModelForm, PasswordInput\n\nclass TwitterUserForm(ModelForm):\n class Meta:\n model = TwitterUser\n widgets = {\n 'password': PasswordInput(),\n }\n\nOr you can do it like this:\nfrom django.forms import ModelForm, PasswordInput\n\nclass TwitterUserForm(ModelForm):\n password = forms.CharField(widget=PasswordInput())\n class Meta:\n model = TwitterUser\n\nI've no idea which one is better - I slightly prefer the first one, since it means you'll still get any help_text and verbose_name from your model.\nRegardless of which of those two approaches you take, you can then make the admin use your form like this (in your app's admin.py):\nfrom django.contrib import admin\n\nclass TwitterUserAdmin(admin.ModelAdmin):\n form = TwitterUserForm\n\nadmin.site.register(TwitterUser, TwitterUserAdmin)\n\n"
] | [
34
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0002810996_django_django_admin_python.txt |
Q:
Python file input string: how to handle escaped unicode characters?
In a text file (test.txt), my string looks like this:
Gro\u00DFbritannien
Reading it, python escapes the backslash:
>>> file = open('test.txt', 'r')
>>> input = file.readline()
>>> input
'Gro\\u00DFbritannien'
How can I have this interpreted as unicode? decode() and unicode() won't do the job.
The following code writes Gro\u00DFbritannien back to the file, but I want it to be Großbritannien
>>> input.decode('latin-1')
u'Gro\\u00DFbritannien'
>>> out = codecs.open('out.txt', 'w', 'utf-8')
>>> out.write(input)
A:
You want to use the unicode_escape codec:
>>> x = 'Gro\\u00DFbritannien'
>>> y = unicode(x, 'unicode_escape')
>>> print y
Großbritannien
See the docs for the vast number of standard encodings that come as part of the Python standard library.
A:
Use the built-in 'unicode_escape' codec:
>>> file = open('test.txt', 'r')
>>> input = file.readline()
>>> input
'Gro\\u00DFbritannien\n'
>>> input.decode('unicode_escape')
u'Gro\xdfbritannien\n'
You may also use codecs.open():
>>> import codecs
>>> file = codecs.open('test.txt', 'r', 'unicode_escape')
>>> input = file.readline()
>>> input
u'Gro\xdfbritannien\n'
The list of standard encodings is available in the Python documentation: http://docs.python.org/library/codecs.html#standard-encodings
| Python file input string: how to handle escaped unicode characters? | In a text file (test.txt), my string looks like this:
Gro\u00DFbritannien
Reading it, python escapes the backslash:
>>> file = open('test.txt', 'r')
>>> input = file.readline()
>>> input
'Gro\\u00DFbritannien'
How can I have this interpreted as unicode? decode() and unicode() won't do the job.
The following code writes Gro\u00DFbritannien back to the file, but I want it to be Großbritannien
>>> input.decode('latin-1')
u'Gro\\u00DFbritannien'
>>> out = codecs.open('out.txt', 'w', 'utf-8')
>>> out.write(input)
| [
"You want to use the unicode_escape codec:\n>>> x = 'Gro\\\\u00DFbritannien'\n>>> y = unicode(x, 'unicode_escape')\n>>> print y\nGroßbritannien\n\nSee the docs for the vast number of standard encodings that come as part of the Python standard library.\n",
"Use the built-in 'unicode_escape' codec:\n>>> file = open('test.txt', 'r')\n>>> input = file.readline()\n>>> input\n'Gro\\\\u00DFbritannien\\n'\n>>> input.decode('unicode_escape')\nu'Gro\\xdfbritannien\\n'\n\nYou may also use codecs.open():\n>>> import codecs\n>>> file = codecs.open('test.txt', 'r', 'unicode_escape')\n>>> input = file.readline()\n>>> input\nu'Gro\\xdfbritannien\\n'\n\nThe list of standard encodings is available in the Python documentation: http://docs.python.org/library/codecs.html#standard-encodings\n"
] | [
9,
4
] | [] | [] | [
"decode",
"python",
"unicode",
"utf_8"
] | stackoverflow_0002811174_decode_python_unicode_utf_8.txt |
Q:
trouble setting up GtkTreeViews in PyGtk
I've got some code in a class that extends gtk.TreeView, and this is the init method. I want to create a tree view that has 3 columns. A toggle button, a label, and a drop down box that the user can type stuff into. The code below works, except that the toggle button doesn't react to mouse clicks and the label and the ComboEntry aren't drawn. (So I guess you can say it doesn't work). I can add rows just fine however.
#make storage enable/disable label user entry
self.tv_store = gtk.TreeStore(gtk.ToggleButton, str, gtk.ComboBoxEntry)
#make widget
gtk.TreeView.__init__(self, self.tv_store)
#make renderers
self.buttonRenderer = gtk.CellRendererToggle()
self.labelRenderer = gtk.CellRendererText()
self.entryRenderer = gtk.CellRendererCombo()
#make columns
self.columnButton = gtk.TreeViewColumn('Enabled')
self.columnButton.pack_start(self.buttonRenderer, False)
self.columnLabel = gtk.TreeViewColumn('Label')
self.columnLabel.pack_start(self.labelRenderer, False)
self.columnEntry = gtk.TreeViewColumn('Data')
self.columnEntry.pack_start(self.entryRenderer, True)
self.append_column(self.columnButton)
self.append_column(self.columnLabel)
self.append_column(self.columnEntry)
self.tmpButton = gtk.ToggleButton('example')
self.tmpCombo = gtk.ComboBoxEntry(None)
self.tv_store.insert(None, 0, [self.tmpButton, 'example label', self.tmpCombo])
A:
First of all, you need to create a model with bool, str and str columns, not the way you are doing now. Second, you need to bind properties of renderers from appropriate model columns, e.g. as in
self.columnButton = \
gtk.TreeViewColumn ('Enabled', self.buttonRenderer,
active = 0) # 0 is the tree store column index
Then you need to set editable property on the renderer to True. And finally, you need to handle signals (changed or editing-done, depending on renderer type) yourself and update the store accordingly.
It may be easier to use some helpers, e.g.
Py-gtktree — there's even an example for editing a tree there.
A:
Just connnect the toggled signal in the gtk.CellRendererToggle, when you click on it, it will emit that signal, then in your callback change the value in the model.
ej.
def toggle(self, cellrenderer, path):
Self.model[path][column] = not self.model[path][column]
self.model is the model asociated to the treeview,
| trouble setting up GtkTreeViews in PyGtk | I've got some code in a class that extends gtk.TreeView, and this is the init method. I want to create a tree view that has 3 columns. A toggle button, a label, and a drop down box that the user can type stuff into. The code below works, except that the toggle button doesn't react to mouse clicks and the label and the ComboEntry aren't drawn. (So I guess you can say it doesn't work). I can add rows just fine however.
#make storage enable/disable label user entry
self.tv_store = gtk.TreeStore(gtk.ToggleButton, str, gtk.ComboBoxEntry)
#make widget
gtk.TreeView.__init__(self, self.tv_store)
#make renderers
self.buttonRenderer = gtk.CellRendererToggle()
self.labelRenderer = gtk.CellRendererText()
self.entryRenderer = gtk.CellRendererCombo()
#make columns
self.columnButton = gtk.TreeViewColumn('Enabled')
self.columnButton.pack_start(self.buttonRenderer, False)
self.columnLabel = gtk.TreeViewColumn('Label')
self.columnLabel.pack_start(self.labelRenderer, False)
self.columnEntry = gtk.TreeViewColumn('Data')
self.columnEntry.pack_start(self.entryRenderer, True)
self.append_column(self.columnButton)
self.append_column(self.columnLabel)
self.append_column(self.columnEntry)
self.tmpButton = gtk.ToggleButton('example')
self.tmpCombo = gtk.ComboBoxEntry(None)
self.tv_store.insert(None, 0, [self.tmpButton, 'example label', self.tmpCombo])
| [
"First of all, you need to create a model with bool, str and str columns, not the way you are doing now. Second, you need to bind properties of renderers from appropriate model columns, e.g. as in\nself.columnButton = \\\n gtk.TreeViewColumn ('Enabled', self.buttonRenderer, \n active = 0) # 0 is the tree store column index\n\nThen you need to set editable property on the renderer to True. And finally, you need to handle signals (changed or editing-done, depending on renderer type) yourself and update the store accordingly.\nIt may be easier to use some helpers, e.g. \nPy-gtktree — there's even an example for editing a tree there.\n",
"Just connnect the toggled signal in the gtk.CellRendererToggle, when you click on it, it will emit that signal, then in your callback change the value in the model.\nej.\ndef toggle(self, cellrenderer, path):\n Self.model[path][column] = not self.model[path][column]\n\nself.model is the model asociated to the treeview,\n"
] | [
2,
1
] | [] | [] | [
"gtk",
"gtktreeview",
"pygtk",
"python"
] | stackoverflow_0002794296_gtk_gtktreeview_pygtk_python.txt |
Q:
Embedding Python and adding C functions to the interpreter
I'm currently writing an applications that embedds the python interpreter. The idea is to have the program call user specified scripts on certain events in the program. I managed this part but now I want the scripts to be able to call functions in my program.
Here's my code so far:
#include "python.h"
static PyObject* myTest(PyObject* self,PyObject *args)
{
return Py_BuildValue("s","123456789");
}
static PyMethodDef myMethods[] = {{"myTest",myTest},{NULL,NULL}};
int main()
{
Py_Initialize();
Py_InitModule("PROGRAM",myMethods);
PyRun_SimpleString("print PROGRAM.myTest()");
Py_Finalize();
}
Thanks!
A:
You need to bind that function to some module, see http://docs.python.org/extending/embedding.html#extending-embedded-python
Edit:
Basicly your code should work. Whats not working?
| Embedding Python and adding C functions to the interpreter | I'm currently writing an applications that embedds the python interpreter. The idea is to have the program call user specified scripts on certain events in the program. I managed this part but now I want the scripts to be able to call functions in my program.
Here's my code so far:
#include "python.h"
static PyObject* myTest(PyObject* self,PyObject *args)
{
return Py_BuildValue("s","123456789");
}
static PyMethodDef myMethods[] = {{"myTest",myTest},{NULL,NULL}};
int main()
{
Py_Initialize();
Py_InitModule("PROGRAM",myMethods);
PyRun_SimpleString("print PROGRAM.myTest()");
Py_Finalize();
}
Thanks!
| [
"You need to bind that function to some module, see http://docs.python.org/extending/embedding.html#extending-embedded-python\nEdit:\nBasicly your code should work. Whats not working?\n"
] | [
2
] | [] | [] | [
"c",
"c++",
"embedding",
"function_pointers",
"python"
] | stackoverflow_0002811596_c_c++_embedding_function_pointers_python.txt |
Q:
Django-registration and ReCaptcha integration - how to pass the user's IP
New to django and trying to setup django-registration 0.8 with recaptcha-client. I followed the advice posted in the answer to this question.
I used the custom form and custom backend from that post and the widget and field from this tutorial. My form is displaying properly with the recaptcha widget but when I submit it throws the error about the missing IP. What's the best way to pass the IP using django-registration?
A:
I also used the code from the tutorial you linked, in my case to add reCaptcha to the django comments app.
You need something like initial={'captcha': request.META['REMOTE_ADDR']} at the point where your RecaptchaRegistrationForm gets instantiated.
Unfortunately this is buried in the registration/views.py register method.
You need to do something like copy and paste their code into a view method of your own and edit it. Then you need a urls.py for your customised backend that looks like the one in registration/backends/default/ but points to your new register view in place of theirs.
| Django-registration and ReCaptcha integration - how to pass the user's IP | New to django and trying to setup django-registration 0.8 with recaptcha-client. I followed the advice posted in the answer to this question.
I used the custom form and custom backend from that post and the widget and field from this tutorial. My form is displaying properly with the recaptcha widget but when I submit it throws the error about the missing IP. What's the best way to pass the IP using django-registration?
| [
"I also used the code from the tutorial you linked, in my case to add reCaptcha to the django comments app.\nYou need something like initial={'captcha': request.META['REMOTE_ADDR']} at the point where your RecaptchaRegistrationForm gets instantiated.\nUnfortunately this is buried in the registration/views.py register method. \nYou need to do something like copy and paste their code into a view method of your own and edit it. Then you need a urls.py for your customised backend that looks like the one in registration/backends/default/ but points to your new register view in place of theirs.\n"
] | [
2
] | [] | [] | [
"django",
"python",
"recaptcha",
"registration"
] | stackoverflow_0002711680_django_python_recaptcha_registration.txt |
Q:
PyImport_ImportModule("PyQt4.QtGui") fails
I've got a C++ windows app that is trying to load a PyQt4 object, similar to the way PyQt4 does it for providing python widgets in the QtDesigner. The app loads other Python modules just fine, but fails to load PyQt4.QtGui. Also, with straight Python, I can load PyQt4.QtGui just fine. The debug output when it attempts that is:
'devenv.exe': Loaded 'C:\Python26\Lib\site-packages\PyQt4\QtGui.pyd', Binary was not built with debug information.
'devenv.exe': Loaded 'C:\Qt\4.6.2\bin\QtCore4.dll', Binary was not built with debug information.
First-chance exception at 0x77747e52 in devenv.exe: 0xC0000139: Entry Point Not Found.
'devenv.exe': Unloaded 'C:\Python26\Lib\site-packages\PyQt4\QtGui.pyd'
'devenv.exe': Unloaded 'C:\Qt\4.6.2\bin\QtCore4.dll'
It looks like it's trying to load another module after QtCore4.dll, but fails. Any ideas why this might be happening?
A:
After some investigation, it appears that my C++ app is using Qt dlls from one install of Qt, and Python is trying to load different Qt dlls - the ones installed with PyQt. I suspect that the failure is happening because the same process is trying to two dlls that are mostly the same.
| PyImport_ImportModule("PyQt4.QtGui") fails | I've got a C++ windows app that is trying to load a PyQt4 object, similar to the way PyQt4 does it for providing python widgets in the QtDesigner. The app loads other Python modules just fine, but fails to load PyQt4.QtGui. Also, with straight Python, I can load PyQt4.QtGui just fine. The debug output when it attempts that is:
'devenv.exe': Loaded 'C:\Python26\Lib\site-packages\PyQt4\QtGui.pyd', Binary was not built with debug information.
'devenv.exe': Loaded 'C:\Qt\4.6.2\bin\QtCore4.dll', Binary was not built with debug information.
First-chance exception at 0x77747e52 in devenv.exe: 0xC0000139: Entry Point Not Found.
'devenv.exe': Unloaded 'C:\Python26\Lib\site-packages\PyQt4\QtGui.pyd'
'devenv.exe': Unloaded 'C:\Qt\4.6.2\bin\QtCore4.dll'
It looks like it's trying to load another module after QtCore4.dll, but fails. Any ideas why this might be happening?
| [
"After some investigation, it appears that my C++ app is using Qt dlls from one install of Qt, and Python is trying to load different Qt dlls - the ones installed with PyQt. I suspect that the failure is happening because the same process is trying to two dlls that are mostly the same. \n"
] | [
0
] | [] | [] | [
"pyqt4",
"python"
] | stackoverflow_0002811982_pyqt4_python.txt |
Q:
Sqlalchemy+elixir: How query with a ManyToMany relationship?
I'm using sqlalchemy with Elixir and have some troubles trying to make a query..
I have 2 entities, Customer and CustomerList, with a many to many relationship.
customer_lists_customers_table = Table('customer_lists_customers',
metadata,
Column('id', Integer, primary_key=True),
Column('customer_list_id', Integer, ForeignKey("customer_lists.id")),
Column('customer_id', Integer, ForeignKey("customers.id")))
class Customer(Entity):
[...]
customer_lists = ManyToMany('CustomerList', table=customer_lists_customers_table)
class CustomerList(Entity):
[...]
customers = ManyToMany('Customer', table=customer_lists_customers_table)
I'm tryng to find CustomerList with some customer:
customer = [...]
CustomerList.query.filter_by(customers.contains(customer)).all()
But I get the error:
NameError:
global name 'customers' is not defined
customers seems to be unrelated to the entity fields, there's an special query form to work with relationships (or ManyToMany relationships)?
Thanks
A:
Read the error message with attention, it points to the source of problem. Did you mean
CustomerList.query.filter_by(CustomerList.customers.contains(customer)).all()?
Update: When using declarative definition you can use just defined relation in class scope, but these properties are not visible outside class:
class MyClass(object):
prop1 = 'somevalue'
prop2 = prop1.upper() # prop1 is visible here
val2 = MyClass.prop1 # This is OK
val1 = prop1.lower() # And this will raise NameError, since there is no
# variable `prop1` is global scope
A:
You can use regular filter: query.filter(CustomerList.customers.contains(customer)). See SQLAlchemy documentation for more examples. It's actually filter_by that's a special case. The query.filter_by(**kwargs) shorthand works only for simple equality comparisons. Under the cover query.filter_by(foo="bar", baz=42) is delegated to the equivalent of query.filter(and_(MyClass.foo == "bar", MyClass.baz == 42)). (There's actually slightly more magic to figure out which property you meant you have many entities, but it still uses simple delegation)
A:
CustomerList.query.filter_by(CustomerList.customers.contains(customer)).all() should work fine.
| Sqlalchemy+elixir: How query with a ManyToMany relationship? | I'm using sqlalchemy with Elixir and have some troubles trying to make a query..
I have 2 entities, Customer and CustomerList, with a many to many relationship.
customer_lists_customers_table = Table('customer_lists_customers',
metadata,
Column('id', Integer, primary_key=True),
Column('customer_list_id', Integer, ForeignKey("customer_lists.id")),
Column('customer_id', Integer, ForeignKey("customers.id")))
class Customer(Entity):
[...]
customer_lists = ManyToMany('CustomerList', table=customer_lists_customers_table)
class CustomerList(Entity):
[...]
customers = ManyToMany('Customer', table=customer_lists_customers_table)
I'm tryng to find CustomerList with some customer:
customer = [...]
CustomerList.query.filter_by(customers.contains(customer)).all()
But I get the error:
NameError:
global name 'customers' is not defined
customers seems to be unrelated to the entity fields, there's an special query form to work with relationships (or ManyToMany relationships)?
Thanks
| [
"Read the error message with attention, it points to the source of problem. Did you mean\nCustomerList.query.filter_by(CustomerList.customers.contains(customer)).all()?\nUpdate: When using declarative definition you can use just defined relation in class scope, but these properties are not visible outside class:\nclass MyClass(object):\n prop1 = 'somevalue'\n prop2 = prop1.upper() # prop1 is visible here\n\nval2 = MyClass.prop1 # This is OK \n\nval1 = prop1.lower() # And this will raise NameError, since there is no \n # variable `prop1` is global scope\n\n",
"You can use regular filter: query.filter(CustomerList.customers.contains(customer)). See SQLAlchemy documentation for more examples. It's actually filter_by that's a special case. The query.filter_by(**kwargs) shorthand works only for simple equality comparisons. Under the cover query.filter_by(foo=\"bar\", baz=42) is delegated to the equivalent of query.filter(and_(MyClass.foo == \"bar\", MyClass.baz == 42)). (There's actually slightly more magic to figure out which property you meant you have many entities, but it still uses simple delegation)\n",
"CustomerList.query.filter_by(CustomerList.customers.contains(customer)).all() should work fine.\n"
] | [
1,
1,
0
] | [] | [] | [
"python",
"python_elixir",
"sqlalchemy"
] | stackoverflow_0002810534_python_python_elixir_sqlalchemy.txt |
Q:
How To Create Per-Request Singleton in Pylons?
In our Pylons based web-app, we're creating a class that essentially provides some logging functionality. We need a new instance of this class for each http request that comes in, but only one per request.
What is the proper way to go about this? Should we just create the object in middleware and store in in request.environ? Is there a more appropriate way to go about this?
A:
There's a good implementation of request local variables in Paste: paste.registry Pylons uses this for its own request-local global variables.
Just create the object in "middleware" like documented and import the global variable to the modules where you need it. (middleware in scarequotes because it's not strictly middleware, because you depend on it to function it's a part of your application/framework)
A:
May be to rely on the built-in functionality?
import logging
logging.getLogger(__name__)
The logging functionality is rather customizable in Python.
| How To Create Per-Request Singleton in Pylons? | In our Pylons based web-app, we're creating a class that essentially provides some logging functionality. We need a new instance of this class for each http request that comes in, but only one per request.
What is the proper way to go about this? Should we just create the object in middleware and store in in request.environ? Is there a more appropriate way to go about this?
| [
"There's a good implementation of request local variables in Paste: paste.registry Pylons uses this for its own request-local global variables.\nJust create the object in \"middleware\" like documented and import the global variable to the modules where you need it. (middleware in scarequotes because it's not strictly middleware, because you depend on it to function it's a part of your application/framework)\n",
"May be to rely on the built-in functionality?\nimport logging\nlogging.getLogger(__name__)\n\nThe logging functionality is rather customizable in Python.\n"
] | [
1,
0
] | [] | [] | [
"pylons",
"python",
"singleton"
] | stackoverflow_0002812011_pylons_python_singleton.txt |
Q:
Generic function that accept a table and column name and returns all the primary key values that matches a filter value given
i have functions that look like this that is littered through out the code
def get_M_status(S):
M_id = marital.select(marital.c.marital_status_description == S).execute().fetchone()
if M_id == None:
print "Warning: No Marital id found for %s Marital status to Single" % S
M_id = marital.select(marital.c.marital_status_description == "Single").execute().fetchone()
return M_id[0]
i was wondering if their is a way to write a generic function where i can pass the relevant values ie: table name primary key column filter column and filter value
cheers
A:
If the primary key is only one column, you can do something like:
getattr(table.c, pkey_col_name) == S
as the 'generic' version of marital.c.marital_status_description == S.
So, something like (please note: this is untested):
def get_row(table, col_name, val, default=None):
col = getattr(table.c, col_name)
row = table.select(col == S).execute().fetchone()
if row == None:
print "Warning: No row found for %s in %s; using %s" % (val, table, default)
row = table.select(col == default).execute().fetchone()
return row[0]
If you have mapped classes, this is even easier; you can do things like:
record = session.query(Marital).get(key)
where Marital is the mapped class for the table marital, session is a sql alchemy session, key is a tuple of key columns (in order). If the key exists in the table, record will be the row found; otherwise it will be None.
A:
The table object has a primary_key attribute that contains the columns that make up the primary key. Select that, just add the where clause and you're done:
def get_pks_by_col(tbl, col_name, col_value):
s = select(tbl.primary_key.columns).where(tbl.columns[col_name] == col_value)
return s.execute().fetchall()
Modify to suit your specific conditions. (len(tbl.primary_key) == 1 is guaranteed, need to pass in the connection to execute on, etc.)
| Generic function that accept a table and column name and returns all the primary key values that matches a filter value given | i have functions that look like this that is littered through out the code
def get_M_status(S):
M_id = marital.select(marital.c.marital_status_description == S).execute().fetchone()
if M_id == None:
print "Warning: No Marital id found for %s Marital status to Single" % S
M_id = marital.select(marital.c.marital_status_description == "Single").execute().fetchone()
return M_id[0]
i was wondering if their is a way to write a generic function where i can pass the relevant values ie: table name primary key column filter column and filter value
cheers
| [
"If the primary key is only one column, you can do something like:\ngetattr(table.c, pkey_col_name) == S\n\nas the 'generic' version of marital.c.marital_status_description == S.\nSo, something like (please note: this is untested):\ndef get_row(table, col_name, val, default=None):\n col = getattr(table.c, col_name)\n row = table.select(col == S).execute().fetchone()\n if row == None:\n print \"Warning: No row found for %s in %s; using %s\" % (val, table, default)\n row = table.select(col == default).execute().fetchone() \n return row[0]\n\nIf you have mapped classes, this is even easier; you can do things like:\nrecord = session.query(Marital).get(key)\n\nwhere Marital is the mapped class for the table marital, session is a sql alchemy session, key is a tuple of key columns (in order). If the key exists in the table, record will be the row found; otherwise it will be None.\n",
"The table object has a primary_key attribute that contains the columns that make up the primary key. Select that, just add the where clause and you're done:\ndef get_pks_by_col(tbl, col_name, col_value):\n s = select(tbl.primary_key.columns).where(tbl.columns[col_name] == col_value)\n return s.execute().fetchall()\n\nModify to suit your specific conditions. (len(tbl.primary_key) == 1 is guaranteed, need to pass in the connection to execute on, etc.)\n"
] | [
1,
1
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0002801164_python_sqlalchemy.txt |
Q:
Python proper use of __str__ and __repr__
My current project requires extensive use of bit fields. I found a simple, functional recipe for bit a field class but it was lacking a few features I needed, so I decided to extend it. I've just got to implementing __str__ and __repr__ and I want to make sure I'm following convention.
__str__ is supposed to be informal and concice, so I've made it return the bit field's decimal value (i.e. str(bit field 11) would be "3".
__repr__ is supposed to be a official representation of the object, so I've made it return the actual bit string (i.e. repr(bit field 11) would be "11").
In your opinion would this implementation meet the conventions for str and repr?
Additionally, I have used the bin() function to get the bit string of the value stored in the class. This isn't compatible with Python < 2.6, is there an alternative method?
Cheers,
Pete
A:
The __repr__ should preferably be a string that could be used to recreate the object, for example if you use eval on it - see the docs here. This isn't an exact science, as it can depend on how the user of your module imported it, for example.
I would have the __str__ return the binary string, and the __repr__ return Classname(binary_string), or whatever could be used to recreate the object.
In the bitstring module (which I maintain) the __str__ is hexadecimal if the bitstring is a multiple of 4 bits long, otherwise it's either binary or a combination of the two. Also if the bitstring is very long then it gets truncated (you don't want to try to print a 100 MB bitstring in an interactive session!)
I'd avoid using the bin() function altogether if I were you. The reason being that it can't be used if your bitstring starts with zero bits (see my question here). I'd advise using either use a bin method or property instead.
A:
I'd consider having __str__ return a hexadecimal representation instead. This way, it's easier to eyeball what the actual bit values are, and thus more useful. But still quite concise (in fact, fewer characters than the decimal representation).
A:
__repr__ needs to return something that, if passed to your constructor, would create a new object that is an identical copy of the original one.
Yours returns '11' but if you passed '11' to your constructor you would not get the same bitfield as a result. So this __repr__ is not ok.
| Python proper use of __str__ and __repr__ | My current project requires extensive use of bit fields. I found a simple, functional recipe for bit a field class but it was lacking a few features I needed, so I decided to extend it. I've just got to implementing __str__ and __repr__ and I want to make sure I'm following convention.
__str__ is supposed to be informal and concice, so I've made it return the bit field's decimal value (i.e. str(bit field 11) would be "3".
__repr__ is supposed to be a official representation of the object, so I've made it return the actual bit string (i.e. repr(bit field 11) would be "11").
In your opinion would this implementation meet the conventions for str and repr?
Additionally, I have used the bin() function to get the bit string of the value stored in the class. This isn't compatible with Python < 2.6, is there an alternative method?
Cheers,
Pete
| [
"The __repr__ should preferably be a string that could be used to recreate the object, for example if you use eval on it - see the docs here. This isn't an exact science, as it can depend on how the user of your module imported it, for example.\nI would have the __str__ return the binary string, and the __repr__ return Classname(binary_string), or whatever could be used to recreate the object.\nIn the bitstring module (which I maintain) the __str__ is hexadecimal if the bitstring is a multiple of 4 bits long, otherwise it's either binary or a combination of the two. Also if the bitstring is very long then it gets truncated (you don't want to try to print a 100 MB bitstring in an interactive session!)\nI'd avoid using the bin() function altogether if I were you. The reason being that it can't be used if your bitstring starts with zero bits (see my question here). I'd advise using either use a bin method or property instead.\n",
"I'd consider having __str__ return a hexadecimal representation instead. This way, it's easier to eyeball what the actual bit values are, and thus more useful. But still quite concise (in fact, fewer characters than the decimal representation).\n",
"__repr__ needs to return something that, if passed to your constructor, would create a new object that is an identical copy of the original one.\nYours returns '11' but if you passed '11' to your constructor you would not get the same bitfield as a result. So this __repr__ is not ok.\n"
] | [
12,
1,
0
] | [] | [] | [
"bit_manipulation",
"conventions",
"python",
"representation"
] | stackoverflow_0002812809_bit_manipulation_conventions_python_representation.txt |
Q:
Which button was clicked?
How can I detect which mouse button was clicked (right or left)
in the slot for QtCore.SIGNAL('cellClicked(int,int)')?
A:
You would probably pass the event to your cellClicked function. I'm assuming you emit your signal from a place that has access to a QMouseEvent.
Check out this thread.
Excerpt:
def mousePressEvent(self, event):
if event.button() == QtCore.Qt.RightButton:
event.accept()
self.rightClickMenu(event)
else:
event.ignore()
Also, this mailing list thread looks like a more complete example.
| Which button was clicked? | How can I detect which mouse button was clicked (right or left)
in the slot for QtCore.SIGNAL('cellClicked(int,int)')?
| [
"You would probably pass the event to your cellClicked function. I'm assuming you emit your signal from a place that has access to a QMouseEvent.\nCheck out this thread.\nExcerpt:\ndef mousePressEvent(self, event):\n if event.button() == QtCore.Qt.RightButton:\n event.accept()\n self.rightClickMenu(event)\n else:\n event.ignore()\n\nAlso, this mailing list thread looks like a more complete example.\n"
] | [
0
] | [] | [] | [
"pyqt4",
"python",
"qtablewidget"
] | stackoverflow_0002810074_pyqt4_python_qtablewidget.txt |
Q:
using an alternative string quotation syntax in python
Just wondering...
I find using escape characters too distracting. I'd rather do something like this (console code):
>>> print ^'Let's begin and end with sets of unlikely 2 chars and bingo!'^
Let's begin and end with sets of unlikely 2 chars and bingo!
Note the ' inside the string, and how this syntax would have no issue with it, or whatever else inside for basically all cases. Too bad markdown can't properly colorize it (yet), so I decided to <pre> it.
Sure, the ^ could be any other char, I'm not sure what would look/work better. That sounds good enough to me, tho.
Probably some other language already have a similar solution. And, just maybe, Python already have such a feature and I overlooked it. I hope this is the case.
But if it isn't, would it be too hard to, somehow, change Python's interpreter and be able to select an arbitrary (or even standardized) syntax for notating the strings?
I realize there are many ways to change statements and the whole syntax in general by using pre-compilators, but this is far more specific. And going any of those routes is what I call "too hard". I'm not really needing to do this so, again, I'm just wondering.
A:
Python has this use """ or ''' as the delimiters
print '''Let's begin and end with sets of unlikely 2 chars and bingo'''
How often do you have both of 3' and 3" in a string
| using an alternative string quotation syntax in python | Just wondering...
I find using escape characters too distracting. I'd rather do something like this (console code):
>>> print ^'Let's begin and end with sets of unlikely 2 chars and bingo!'^
Let's begin and end with sets of unlikely 2 chars and bingo!
Note the ' inside the string, and how this syntax would have no issue with it, or whatever else inside for basically all cases. Too bad markdown can't properly colorize it (yet), so I decided to <pre> it.
Sure, the ^ could be any other char, I'm not sure what would look/work better. That sounds good enough to me, tho.
Probably some other language already have a similar solution. And, just maybe, Python already have such a feature and I overlooked it. I hope this is the case.
But if it isn't, would it be too hard to, somehow, change Python's interpreter and be able to select an arbitrary (or even standardized) syntax for notating the strings?
I realize there are many ways to change statements and the whole syntax in general by using pre-compilators, but this is far more specific. And going any of those routes is what I call "too hard". I'm not really needing to do this so, again, I'm just wondering.
| [
"Python has this use \"\"\" or ''' as the delimiters\nprint '''Let's begin and end with sets of unlikely 2 chars and bingo'''\n\nHow often do you have both of 3' and 3\" in a string\n"
] | [
13
] | [] | [] | [
"python",
"quotations",
"string",
"syntax"
] | stackoverflow_0002813638_python_quotations_string_syntax.txt |
Q:
python : in which timezone is it a specific time right now?
i have users from all timezones, and i want to send out alerts at around 8AM in each users respective timezone.
i need a python script that runs every hour [in a cron job] and i need to find out at which timezone it is 8AM right now, and i can use that info to select the users that have to receive the alerts.
how do i go about doing this? there seems to be gmt+14 to gmt-12 that is 27 timezones, and there are only 24 hours in a day!
A:
Python defines a tzinfo class that gives you the offset of a time zone, but it doesn't provide any concrete implementation of the class. There are a few implementations available, I've used python-dateutil successfully. Obviously you'll need a time zone for each user; at the hourly (or half-hourly) run, take the current UTC time and set its tzinfo member to the UTZ timezone; then use the astimezone function to convert to each user's time zone in turn, and compare to some range around 8:00.
A:
Some time zones are in half hour increments, for example Newfoundland Time is UTC-3:30. You should be able to get all the offsets and do the appropriate math to get all the notification times. I would do the scheduling in advance though, otherwise your notifications may be wrong on the daylight savings day turn-overs, etc. So every 24 hours, you would create a list of times to send notifications for the next day and instruct your scheduler appropriately.
| python : in which timezone is it a specific time right now? | i have users from all timezones, and i want to send out alerts at around 8AM in each users respective timezone.
i need a python script that runs every hour [in a cron job] and i need to find out at which timezone it is 8AM right now, and i can use that info to select the users that have to receive the alerts.
how do i go about doing this? there seems to be gmt+14 to gmt-12 that is 27 timezones, and there are only 24 hours in a day!
| [
"Python defines a tzinfo class that gives you the offset of a time zone, but it doesn't provide any concrete implementation of the class. There are a few implementations available, I've used python-dateutil successfully. Obviously you'll need a time zone for each user; at the hourly (or half-hourly) run, take the current UTC time and set its tzinfo member to the UTZ timezone; then use the astimezone function to convert to each user's time zone in turn, and compare to some range around 8:00.\n",
"Some time zones are in half hour increments, for example Newfoundland Time is UTC-3:30. You should be able to get all the offsets and do the appropriate math to get all the notification times. I would do the scheduling in advance though, otherwise your notifications may be wrong on the daylight savings day turn-overs, etc. So every 24 hours, you would create a list of times to send notifications for the next day and instruct your scheduler appropriately.\n"
] | [
1,
0
] | [] | [] | [
"python",
"timezone"
] | stackoverflow_0002813745_python_timezone.txt |
Q:
How do you check the presence of many keys in a Python dictionary?
I have the following dictionary:
sites = {
'stackoverflow': 1,
'superuser': 2,
'meta': 3,
'serverfault': 4,
'mathoverflow': 5
}
To check if there are more than one key available in the above dictionary, I will do something like:
'stackoverflow' in sites and 'serverfault' in sites
The above is maintainable with only 2 key lookups. Is there a better way to handle checking a large number of keys in a very big dictionary?
A:
You can pretend the keys of the dict are a set, and then use set.issubset:
set(['stackoverflow', 'serverfault']).issubset(sites) # ==> True
set(['stackoverflow', 'google']).issubset(sites) # ==> False
A:
You could use all:
print( all(site in sites for site in ('stackoverflow','meta')) )
# True
print( all(site in sites for site in ('stackoverflow','meta','roger')) )
# False
A:
mysites = ['stackoverflow', 'superuser']
[i for i in mysites if i in sites.keys()] # ==> sites in the list mysites that are in your dictionary
[i for i in mysites if i not in sites.keys()] # ==> sites in the list mysites that are not in your dictionary
A:
How many lookups are you planning to do? I think the method you are using is fine.
If there are dozens, hundreds, etc of keys you are comparing against you could put all of the target keys in a list and then iterate over the list, checking to make sure each item is in the dictionary.
| How do you check the presence of many keys in a Python dictionary? | I have the following dictionary:
sites = {
'stackoverflow': 1,
'superuser': 2,
'meta': 3,
'serverfault': 4,
'mathoverflow': 5
}
To check if there are more than one key available in the above dictionary, I will do something like:
'stackoverflow' in sites and 'serverfault' in sites
The above is maintainable with only 2 key lookups. Is there a better way to handle checking a large number of keys in a very big dictionary?
| [
"You can pretend the keys of the dict are a set, and then use set.issubset:\nset(['stackoverflow', 'serverfault']).issubset(sites) # ==> True\n\nset(['stackoverflow', 'google']).issubset(sites) # ==> False\n\n",
"You could use all:\nprint( all(site in sites for site in ('stackoverflow','meta')) )\n# True\nprint( all(site in sites for site in ('stackoverflow','meta','roger')) )\n# False\n\n",
"mysites = ['stackoverflow', 'superuser']\n[i for i in mysites if i in sites.keys()] # ==> sites in the list mysites that are in your dictionary\n[i for i in mysites if i not in sites.keys()] # ==> sites in the list mysites that are not in your dictionary\n\n",
"How many lookups are you planning to do? I think the method you are using is fine. \nIf there are dozens, hundreds, etc of keys you are comparing against you could put all of the target keys in a list and then iterate over the list, checking to make sure each item is in the dictionary.\n"
] | [
12,
9,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0002813806_python.txt |
Q:
Python MD5 Hash Faster Calculation
I will try my best to explain my problem and my line of thought on how I think I can solve it.
I use this code
for root, dirs, files in os.walk(downloaddir):
for infile in files:
f = open(os.path.join(root,infile),'rb')
filehash = hashlib.md5()
while True:
data = f.read(10240)
if len(data) == 0:
break
filehash.update(data)
print "FILENAME: " , infile
print "FILE HASH: " , filehash.hexdigest()
and using start = time.time() elapsed = time.time() - start I measure how long it takes to calculate an hash. Pointing my code to a file with 653megs this is the result:
root@Mars:/home/tiago# python algorithm-timer.py
FILENAME: freebsd.iso
FILE HASH: ace0afedfa7c6e0ad12c77b6652b02ab
12.624
root@Mars:/home/tiago# python algorithm-timer.py
FILENAME: freebsd.iso
FILE HASH: ace0afedfa7c6e0ad12c77b6652b02ab
12.373
root@Mars:/home/tiago# python algorithm-timer.py
FILENAME: freebsd.iso
FILE HASH: ace0afedfa7c6e0ad12c77b6652b02ab
12.540
Ok now 12 seconds +- on a 653mb file, my problem is I intend to use this code on a program that will run through multiple files, some of them might be 4/5/6Gb and it will take wayy longer to calculate. What am wondering is if there is a faster way for me to calculate the hash of the file? Maybe by doing some multithreading? I used a another script to check the use of the CPU second by second and I see that my code is only using 1 out of my 2 CPUs and only at 25% max, any way I can change this?
Thank you all in advance for the given help.
A:
Hash calculation in your case will almost certanly be I/O bound (unless you'll be running it on a machine with a really slow processor), so multithreading or processing of multiple files at once probably won't yield you expected results.
Arraging files over multiple drives or on a faster (SSD) drive would probably help, even though that is probably not the solution you are looking for.
A:
Aren't disk operations a bottleneck here?
Assuming 80MB/sec read speed (this is how my hard disk performs), it takes about 8 seconds to read the file.
A:
For what it's worth, doing this:
c:\python\Python.exe c:\python\Tools\scripts\md5sum.py cd.iso
takes 9.671 seconds on my laptop (2GHz core2 duo with an 80 GB SATA laptop hard drive).
As others have mentioned, MD5s are disk-bound, but your 12 second benchmark is probably pretty close to the fastest you could get.
Also, python's md5sum.py uses 8096 for the buffer size (even though I'm sure they meant either 4096 or 8192).
A:
It helped me to increase my buffer size, up to a point. I started with 1024 and multiplied it with 2^N, increasing N each time starting from 1. With this method, I found that on my system that a buffer size of 65536 seemed to be about as good as it would get. However, it only gave me about an 7% improvement in running time.
Profiling indicated that about 80% of the time is spent in the MD5 update method and the other 20% is reading in the file. Since MD5 is a serial algorithm and the Python algorithm is already implemented in C, I don't think that there is much that you can do to speed up the MD5 part. You can try calculating the MD5s of two different files in parallel, but as everyone has said, you're ultimately going to be limited by the disk access speed.
| Python MD5 Hash Faster Calculation | I will try my best to explain my problem and my line of thought on how I think I can solve it.
I use this code
for root, dirs, files in os.walk(downloaddir):
for infile in files:
f = open(os.path.join(root,infile),'rb')
filehash = hashlib.md5()
while True:
data = f.read(10240)
if len(data) == 0:
break
filehash.update(data)
print "FILENAME: " , infile
print "FILE HASH: " , filehash.hexdigest()
and using start = time.time() elapsed = time.time() - start I measure how long it takes to calculate an hash. Pointing my code to a file with 653megs this is the result:
root@Mars:/home/tiago# python algorithm-timer.py
FILENAME: freebsd.iso
FILE HASH: ace0afedfa7c6e0ad12c77b6652b02ab
12.624
root@Mars:/home/tiago# python algorithm-timer.py
FILENAME: freebsd.iso
FILE HASH: ace0afedfa7c6e0ad12c77b6652b02ab
12.373
root@Mars:/home/tiago# python algorithm-timer.py
FILENAME: freebsd.iso
FILE HASH: ace0afedfa7c6e0ad12c77b6652b02ab
12.540
Ok now 12 seconds +- on a 653mb file, my problem is I intend to use this code on a program that will run through multiple files, some of them might be 4/5/6Gb and it will take wayy longer to calculate. What am wondering is if there is a faster way for me to calculate the hash of the file? Maybe by doing some multithreading? I used a another script to check the use of the CPU second by second and I see that my code is only using 1 out of my 2 CPUs and only at 25% max, any way I can change this?
Thank you all in advance for the given help.
| [
"Hash calculation in your case will almost certanly be I/O bound (unless you'll be running it on a machine with a really slow processor), so multithreading or processing of multiple files at once probably won't yield you expected results.\nArraging files over multiple drives or on a faster (SSD) drive would probably help, even though that is probably not the solution you are looking for.\n",
"Aren't disk operations a bottleneck here?\nAssuming 80MB/sec read speed (this is how my hard disk performs), it takes about 8 seconds to read the file.\n",
"For what it's worth, doing this: \nc:\\python\\Python.exe c:\\python\\Tools\\scripts\\md5sum.py cd.iso\n\ntakes 9.671 seconds on my laptop (2GHz core2 duo with an 80 GB SATA laptop hard drive). \nAs others have mentioned, MD5s are disk-bound, but your 12 second benchmark is probably pretty close to the fastest you could get. \nAlso, python's md5sum.py uses 8096 for the buffer size (even though I'm sure they meant either 4096 or 8192). \n",
"It helped me to increase my buffer size, up to a point. I started with 1024 and multiplied it with 2^N, increasing N each time starting from 1. With this method, I found that on my system that a buffer size of 65536 seemed to be about as good as it would get. However, it only gave me about an 7% improvement in running time. \nProfiling indicated that about 80% of the time is spent in the MD5 update method and the other 20% is reading in the file. Since MD5 is a serial algorithm and the Python algorithm is already implemented in C, I don't think that there is much that you can do to speed up the MD5 part. You can try calculating the MD5s of two different files in parallel, but as everyone has said, you're ultimately going to be limited by the disk access speed. \n"
] | [
4,
2,
2,
2
] | [] | [] | [
"md5",
"multicore",
"multithreading",
"python"
] | stackoverflow_0002813635_md5_multicore_multithreading_python.txt |
Q:
How can I implement "real time" messaging on Google AppEngine?
I'm creating a web application on Google AppEngine where I want the user to be notified a quickly as possible after certain events occour. The problem is similar to say a chat server in that I need something happening on one connection (someone is writing a message in a chat room) to propagate to a number of other connections (other people in that chat room gets the message). To get speedy updates from the server to the client I'm planning on using long polling with XmlHttpRequest, hoping that AppEngine won't interfere other than possibly restriing the timeout. The real problem however is efficient notification between connections on AppEngine.
Is there any support for this type of cross connection notification on AppEngine that does not involve busy-waiting? The only tools I can think of to do this at all is either using the data storage (slow) or memcache (unreliable), and none of them would let me avoid busy-waiting.
Note: I know about XMPP support on AppEngine. It's related, but I want a browser based solution, sending messages to the users by XMPP is not an option.
A:
Requests on App Engine are limited to 30 seconds execution time, which makes long polling difficult. Further, you need to keep your average execution time low, or you will very quickly run out of instances to execute your queries - App Engine will only provision new instances if your app is reasonably fast. For those reasons, Long Polling is extremely strongly discouraged on App Engine.
If you're prepared to wait a while, however, the roadmap includes "Support for Browser Push (Comet) communication", which is exactly what you're looking for.
A:
The App Engine roadmap has Comet support, otherwise you will have some difficulty achieving this.
A:
You could always use a hosted comet service, such as WebSync On-Demand. That'll let you push events out regardless of what type of server you use for the hosting.
| How can I implement "real time" messaging on Google AppEngine? | I'm creating a web application on Google AppEngine where I want the user to be notified a quickly as possible after certain events occour. The problem is similar to say a chat server in that I need something happening on one connection (someone is writing a message in a chat room) to propagate to a number of other connections (other people in that chat room gets the message). To get speedy updates from the server to the client I'm planning on using long polling with XmlHttpRequest, hoping that AppEngine won't interfere other than possibly restriing the timeout. The real problem however is efficient notification between connections on AppEngine.
Is there any support for this type of cross connection notification on AppEngine that does not involve busy-waiting? The only tools I can think of to do this at all is either using the data storage (slow) or memcache (unreliable), and none of them would let me avoid busy-waiting.
Note: I know about XMPP support on AppEngine. It's related, but I want a browser based solution, sending messages to the users by XMPP is not an option.
| [
"Requests on App Engine are limited to 30 seconds execution time, which makes long polling difficult. Further, you need to keep your average execution time low, or you will very quickly run out of instances to execute your queries - App Engine will only provision new instances if your app is reasonably fast. For those reasons, Long Polling is extremely strongly discouraged on App Engine.\nIf you're prepared to wait a while, however, the roadmap includes \"Support for Browser Push (Comet) communication\", which is exactly what you're looking for.\n",
"The App Engine roadmap has Comet support, otherwise you will have some difficulty achieving this.\n",
"You could always use a hosted comet service, such as WebSync On-Demand. That'll let you push events out regardless of what type of server you use for the hosting.\n"
] | [
4,
1,
1
] | [] | [] | [
"comet",
"google_app_engine",
"javascript",
"python"
] | stackoverflow_0002660316_comet_google_app_engine_javascript_python.txt |
Q:
How to pack python files and its dependencies in a single executable file?
I've got a piece of software which consists of several python sources and a couple of c++ libraries. I'd like to pack them in a executable single file, just like java does with .jar files. Is there a way to do that?
A:
You may want to have a look at py2exe, pyInstaller or others.
A:
Sure is.
A:
You can use python egg files, they are very similar to java jar files.
http://mrtopf.de/blog/python_zope/a-small-introduction-to-python-eggs/
| How to pack python files and its dependencies in a single executable file? | I've got a piece of software which consists of several python sources and a couple of c++ libraries. I'd like to pack them in a executable single file, just like java does with .jar files. Is there a way to do that?
| [
"You may want to have a look at py2exe, pyInstaller or others.\n",
"Sure is.\n",
"You can use python egg files, they are very similar to java jar files.\nhttp://mrtopf.de/blog/python_zope/a-small-introduction-to-python-eggs/\n"
] | [
10,
3,
0
] | [] | [] | [
"archive",
"executable",
"libraries",
"python"
] | stackoverflow_0002813229_archive_executable_libraries_python.txt |
Q:
parsing a string of ascii text into separate variables
I have a piece of text that gets handed to me like:
here is line one\n\nhere is line two\n\nhere is line three
What I would like to do is break this string up into three separate variables.
I'm not quite sure how one would go about accomplishing this in python.
Thanks for any help,
jml
A:
a, b, c = s.split('\n\n')
A:
s1, s2, s3 = that_string_variable.split('\n\n')
Basically, whatever variable you've got that string in, you then .split() on the token you want to use as the separator (in this case, '\n\n'), and that will return a list of strings. You can assign using "unpacking" where you specify multiple variables for each of the elements to go to. An assignment like above says "I know the right hand side will give me three elements, and I want those to go into s1, s2, and s3 in that order.
A:
You can use the split function:
s = 'ab\n\ncd'
tokens = s.split('\n\n')
Then tokens is the array ['ab', 'cd']
EDIT: I assumed you meant that you want your example to be split into 3 strings, but in general to split the string > 3 strings if necessary
A:
To break it into a list with 3 elements:
mystring = "here is line one\n\nhere is line two\n\nhere is line three"
listofthings = mystring.split("\n\n")
Then you can access them with listofthings[0], listofthings[1], and listofthings[2].
To put them in separate actual variables:
mystring = "here is line one\n\nhere is line two\n\nhere is line three"
a,b,c = mystring.split("\n\n")
# a now contains "here is line one", et cetera.
| parsing a string of ascii text into separate variables | I have a piece of text that gets handed to me like:
here is line one\n\nhere is line two\n\nhere is line three
What I would like to do is break this string up into three separate variables.
I'm not quite sure how one would go about accomplishing this in python.
Thanks for any help,
jml
| [
"a, b, c = s.split('\\n\\n')\n\n",
"s1, s2, s3 = that_string_variable.split('\\n\\n')\n\nBasically, whatever variable you've got that string in, you then .split() on the token you want to use as the separator (in this case, '\\n\\n'), and that will return a list of strings. You can assign using \"unpacking\" where you specify multiple variables for each of the elements to go to. An assignment like above says \"I know the right hand side will give me three elements, and I want those to go into s1, s2, and s3 in that order.\n",
"You can use the split function:\ns = 'ab\\n\\ncd'\ntokens = s.split('\\n\\n')\n\nThen tokens is the array ['ab', 'cd']\nEDIT: I assumed you meant that you want your example to be split into 3 strings, but in general to split the string > 3 strings if necessary\n",
"To break it into a list with 3 elements:\nmystring = \"here is line one\\n\\nhere is line two\\n\\nhere is line three\"\nlistofthings = mystring.split(\"\\n\\n\")\n\nThen you can access them with listofthings[0], listofthings[1], and listofthings[2].\nTo put them in separate actual variables:\nmystring = \"here is line one\\n\\nhere is line two\\n\\nhere is line three\"\na,b,c = mystring.split(\"\\n\\n\")\n\n# a now contains \"here is line one\", et cetera.\n\n"
] | [
4,
1,
1,
0
] | [] | [] | [
"parsing",
"python",
"string",
"tokenize"
] | stackoverflow_0002814738_parsing_python_string_tokenize.txt |
Q:
writing pexpect like program in c++ on Linux
Is there any way of writing pexpect like small program which can launch a process and pass the password to that process?
I don't want to install and use pexpect python library but want to know the logic behind it so that using linux system apis I can build something similar.
A:
You could just use "expect". It is very light weight and is made to do what youre describing.
A:
For very simple cases, empty is one option. It's a lightweight C program, and it can be used straight from a shell script and doesn't require Tcl.
For Debian/Ubuntu, the package is empty-expect.
| writing pexpect like program in c++ on Linux | Is there any way of writing pexpect like small program which can launch a process and pass the password to that process?
I don't want to install and use pexpect python library but want to know the logic behind it so that using linux system apis I can build something similar.
| [
"You could just use \"expect\". It is very light weight and is made to do what youre describing.\n",
"For very simple cases, empty is one option. It's a lightweight C program, and it can be used straight from a shell script and doesn't require Tcl.\nFor Debian/Ubuntu, the package is empty-expect.\n"
] | [
2,
0
] | [] | [] | [
"c++",
"linux",
"pexpect",
"python"
] | stackoverflow_0001982788_c++_linux_pexpect_python.txt |
Q:
How can I make the PyDev editor selectively ignore errors?
I'm using PyDev under Eclipse to write some Jython code. I've got numerous instances where I need to do something like this:
import com.work.project.component.client.Interface.ISubInterface as ISubInterface
The problem is that PyDev will always flag this as an error and say "Unresolved import: ISubInterface". The code works just fine, it's just that I'd rather not have these little white/red X-marks next to my code and have my Problems tab littered with these errors.
Is there a way I can add a magic comment or something like that to the end of the line to make PyDev ignore the false error, similar to how you can sprinkle comments like "# pylint: disable-msg=E1101" to make PyLint ignore errors?
Also, there's a possibility I'm just doing it wrong when it comes to using Java interfaces in Jython. In which case a little bit of guidance would be very much appreciated.
A:
You can add a comment
#@UnresolvedImport
#@UnusedVariable
So your import becomes:
import com.work.project.component.client.Interface.ISubInterface as ISubInterface #@UnresolvedImport
That should remove the error/warning. There are other comments you can add as well.
A:
Add the hash character # at the end of the line then with the cursor on the flagged error, press Ctrl-1. One of the options in the menu will be something like @UndefinedVariable. Adding this comment will cause PyDev to ignore the error.
A:
You can make the ignore like the other posts suggest, but the real problem is that Pydev cannot find that class... If you add a .jar that contains that class to your PYTHONPATH it should be able to resolve it (or if you have a Java project that has that class, you should be able to mark that project as a Pydev project and add its bin folder to the project PYTHONPATH -- in which case that class should be found too).
| How can I make the PyDev editor selectively ignore errors? | I'm using PyDev under Eclipse to write some Jython code. I've got numerous instances where I need to do something like this:
import com.work.project.component.client.Interface.ISubInterface as ISubInterface
The problem is that PyDev will always flag this as an error and say "Unresolved import: ISubInterface". The code works just fine, it's just that I'd rather not have these little white/red X-marks next to my code and have my Problems tab littered with these errors.
Is there a way I can add a magic comment or something like that to the end of the line to make PyDev ignore the false error, similar to how you can sprinkle comments like "# pylint: disable-msg=E1101" to make PyLint ignore errors?
Also, there's a possibility I'm just doing it wrong when it comes to using Java interfaces in Jython. In which case a little bit of guidance would be very much appreciated.
| [
"You can add a comment\n#@UnresolvedImport\n#@UnusedVariable\n\nSo your import becomes:\nimport com.work.project.component.client.Interface.ISubInterface as ISubInterface #@UnresolvedImport\n\nThat should remove the error/warning. There are other comments you can add as well.\n",
"Add the hash character # at the end of the line then with the cursor on the flagged error, press Ctrl-1. One of the options in the menu will be something like @UndefinedVariable. Adding this comment will cause PyDev to ignore the error.\n",
"You can make the ignore like the other posts suggest, but the real problem is that Pydev cannot find that class... If you add a .jar that contains that class to your PYTHONPATH it should be able to resolve it (or if you have a Java project that has that class, you should be able to mark that project as a Pydev project and add its bin folder to the project PYTHONPATH -- in which case that class should be found too).\n"
] | [
57,
30,
6
] | [
"It is not a PYTHONPATH issue. It is related to importing/using static class-internal members of a Java class. I am getting the same sort of thing all over the place e.g. when trying to use constants in java.awt.Color:\nimport java.awt.Color as Color\nborderColor = Color.BLACK # get \"Undefined variable from import: BLACK\" error\n\nThere is no way I've found to import Color.BLACK in this case. Thanks to iceman for at least pointing out the #@UndefinedVariable flag. That helps a lot. Note also that this is NOT a jython problem, the code runs just fine. It's just an issue with PyDev.\n"
] | [
-1
] | [
"jython",
"pydev",
"python",
"python_import"
] | stackoverflow_0001702043_jython_pydev_python_python_import.txt |
Q:
parsing a string based on specified identifiers
Let's say that I have the following text:
input = "one aaa and bbb two bbbb er ... // three cccc"
I would like to parse this into a group of variables that contain
criteria = ["one", "two", "three"]
v1,v2,v3 = input.split(criteria)
I know that the example above won't work, but is there some utility in python that would allow me to use this sort of approach? I know what the identifiers will be in advance, so I would think that there has got to be a way to do this...
Thanks for any help,
jml
A:
Not terribly elegant but it works:
>>> s
'one aaa two bbbb three cccc'
>>> re.split(r"\s*(?:one|two|three)\s*", s)
['', 'aaa', 'bbbb', 'cccc']
The ?: keeps it from returning the delimiting identifiers in the results.
A:
So, so ugly, but it should do what you need:
i1 = iter(input.split())
i2 = iter(input.split())
next(i2)
strdict = dict(zip(i1, i2))
print operator.itemgetter(*criteria)(strdict)
| parsing a string based on specified identifiers | Let's say that I have the following text:
input = "one aaa and bbb two bbbb er ... // three cccc"
I would like to parse this into a group of variables that contain
criteria = ["one", "two", "three"]
v1,v2,v3 = input.split(criteria)
I know that the example above won't work, but is there some utility in python that would allow me to use this sort of approach? I know what the identifiers will be in advance, so I would think that there has got to be a way to do this...
Thanks for any help,
jml
| [
"Not terribly elegant but it works:\n>>> s\n'one aaa two bbbb three cccc'\n>>> re.split(r\"\\s*(?:one|two|three)\\s*\", s)\n['', 'aaa', 'bbbb', 'cccc']\n\nThe ?: keeps it from returning the delimiting identifiers in the results.\n",
"So, so ugly, but it should do what you need:\ni1 = iter(input.split())\ni2 = iter(input.split())\nnext(i2)\nstrdict = dict(zip(i1, i2))\nprint operator.itemgetter(*criteria)(strdict)\n\n"
] | [
1,
1
] | [] | [] | [
"parsing",
"python",
"string"
] | stackoverflow_0002814948_parsing_python_string.txt |
Q:
Django site on Nginx+FastCGI goes (504 gateway timeout)
Sometimes my whole Django based site goes into 504 gateway timeout errors so none page can be displayed.
Is it possible to write a shell program and cronjob it run every 5 minutes to detect such errors and restart FastCGI process if needed?
I'm currently using command below to restart FastCGI in case it's crashed but it doesn't work for above situation because when 504 gateway errors occur, the processes are still running.
ps ax | grep -v grep | grep port=8001 > /dev/null || restart_fcgi.sh
A:
Perhaps you should find out why the site starts serving 504 errors first - check the logs (or add logging if you don't have enough information), and fix whatever the problem is. Alternatively, you may find nginx + apache + mod_wsgi a more stable approach - nginx is a fantastic front-end webserver for serving static content, but Apache is excellent for hosting dynamic processes. Try to combine them both. I used to use nginx + fastcgi, but I found the former to be a much more stable approach.
If you are still unable to determine what's causing your problem, you can set up a monitor script that runs locally and checks the response code - if it finds a 5XX it can force restart your fastcgi process. You can use Python + httplib for the script, and os.system running your shell script (plus a suitable kill -9 statement) above.
A:
I think if you are having this problem, then supervisor is your friend. A very good friend. Like daemontools, except easy config , lots of help and non root usage.
You should try to find the problem for sure, but regardless, an hour of prep means that you'll be able to rely on the process restarting after failure for long enough to live your life.
| Django site on Nginx+FastCGI goes (504 gateway timeout) | Sometimes my whole Django based site goes into 504 gateway timeout errors so none page can be displayed.
Is it possible to write a shell program and cronjob it run every 5 minutes to detect such errors and restart FastCGI process if needed?
I'm currently using command below to restart FastCGI in case it's crashed but it doesn't work for above situation because when 504 gateway errors occur, the processes are still running.
ps ax | grep -v grep | grep port=8001 > /dev/null || restart_fcgi.sh
| [
"Perhaps you should find out why the site starts serving 504 errors first - check the logs (or add logging if you don't have enough information), and fix whatever the problem is. Alternatively, you may find nginx + apache + mod_wsgi a more stable approach - nginx is a fantastic front-end webserver for serving static content, but Apache is excellent for hosting dynamic processes. Try to combine them both. I used to use nginx + fastcgi, but I found the former to be a much more stable approach.\nIf you are still unable to determine what's causing your problem, you can set up a monitor script that runs locally and checks the response code - if it finds a 5XX it can force restart your fastcgi process. You can use Python + httplib for the script, and os.system running your shell script (plus a suitable kill -9 statement) above.\n",
"I think if you are having this problem, then supervisor is your friend. A very good friend. Like daemontools, except easy config , lots of help and non root usage. \nYou should try to find the problem for sure, but regardless, an hour of prep means that you'll be able to rely on the process restarting after failure for long enough to live your life.\n"
] | [
3,
0
] | [] | [] | [
"django",
"fastcgi",
"python",
"restart",
"timeout"
] | stackoverflow_0002466963_django_fastcgi_python_restart_timeout.txt |
Q:
Common coding style for Python?
I'm pretty new to Python, and I want to develop my first serious open source project. I want to ask what is the common coding style for python projects. I'll put also what I'm doing right now.
1.- What is the most widely used column width? (the eternal question)
I'm currently sticking to 80 columns (and it's a pain!)
2.- What quotes to use? (I've seen everything and PEP 8 does not mention anything clear)
I'm using single quotes for everything but docstrings, which use triple double quotes.
3.- Where do I put my imports?
I'm putting them at file header in this order.
import sys
import -rest of python modules needed-
import whatever
import -rest of application modules-
<code here>
4.- Can I use "import whatever.function as blah"?
I saw some documents that disregard doing this.
5.- Tabs or spaces for indenting?
Currently using 4 spaces tabs.
6.- Variable naming style?
I'm using lowercase for everything but classes, which I put in camelCase.
Anything you would recommend?
A:
PEP 8 is pretty much "the root" of all common style guides.
Google's Python style guide has some parts that are quite well thought of, but others are idiosyncratic (the two-space indents instead of the popular four-space ones, and the CamelCase style for functions and methods instead of the camel_case style, are pretty major idiosyncrasies).
On to your specific questions:
1.- What is the most widely used column width? (the eternal question)
I'm currently sticking to 80 columns
(and it's a pain!)
80 columns is most popular
2.- What quotes to use? (I've seen everything and PEP 8 does not mention
anything clear) I'm using single
quotes for everything but docstrings,
which use triple double quotes.
I prefer the style you're using, but even Google was not able to reach a consensus about this:-(
3.- Where do I put my imports? I'm putting them at file header in this
order.
import sys import -rest of python
modules needed-
import whatever import -rest of
application modules-
Yes, excellent choice, and popular too.
4.- Can I use "import whatever.function as blah"? I saw some
documents that disregard doing this.
I strongly recommend you always import modules -- not specific names from inside a module. This is not just style -- there are strong advantages e.g. in testability in doing that. The as clause is fine, to shorten a module's name or avoid clashes.
5.- Tabs or spaces for indenting? Currently using 4 spaces tabs.
Overwhelmingly most popular.
6.- Variable naming style? I'm using lowercase for everything but classes,
which I put in camelCase.
Almost everybody names classes with uppercase initial and constants with all-uppercase.
A:
1.- Most everyone has a 16:9 or 16:10 monitor now days. Even if they don't have a wide-screen they have lots of pixels, 80 cols isn't a big practical deal breaker like it was when everyone was hacking at the command line in a remote terminal window on a 4:3 monitor at 320 X 240. I usually end the line when it gets too long, which is subjective. I am at 2048 X 1152 on a 23" Monitor X 2.
2.- Single quotes by default so you don't have to escape Double quotes, Double quotes when you need to embed single quotes, and Triple quotes for strings with embedded newlines.
3.- Put them at the top of the file, sometimes you put them in the main function if they aren't needed globally to the module.
4.- It is a common idiom to rename some modules. A good example is the following.
try:
# for Python 2.6.x
import json
except ImportError:
# for previous Pythons
try:
import simplejson as json
except ImportError:
sys.exit('easy_install simplejson')
but the preferred way to import just a class or function is from module import xxx with the optional as yyy if needed
5.- Always use SPACES! 2 or 4 as long as no TABS
6.- Classes should up UpperCaseCamelStyle, variables are lowercase sometimes lowerCamelCase or sometimes all_lowecase_separated_by_underscores, as are function names. "Constants" should be ALL_UPPER_CASE_SEPARATED_BY_UNDERSCORES
When in doubt refer to the PEP 8, the Python source, existing conventions in a code base. But the most import thing is to be internally consistent as possible. All Python code should look like it was written by the same person when ever possible.
A:
Since I'm really crazy about "styling" I'll write down the guidelines that I currently use in a near 8k SLOC project with about 35 files, most of it matches PEP8.
PEP8 says 79(WTF?), I go with 80 and I'm used to it now. Less eye movement after all!
Docstrings and stuff that spans multiple lines in '''. Everything else in ''. Also I don't like double quotes, I only use single quotes all the time... guess that's because I came form the JavaScript corner, where it's just easier too use '', because that way you don't have to escape all the HTML stuff :O
At the head, built-in before custom application code. But I also go with a "fail early" approach, so if there's something that's version depended(GTK for example) I'd import that first.
Depends, most of the times I go with import foo and from foo import, but there a certain cases(e.G. the name is already defined by another import) were I use from foo import bar as bla too.
4 Spaces. Period. If you really want to use tabs, make sure to convert them to spaces before committing when working with SCM. BUT NEVER(!) MIX TABS AND SPACES!!! It can AND WILL introduce horrible bugs.
some_method or foo_function, a CONSTANT, MyClass.
Also you can argue about indentation in cases where a method call or something spans multiple lines, and you can argue about which line continuation style you will use. Either surround everything with () or do the \ at the end of the line thingy. I do the latter, and I also place operators and other stuff at the start of the next line.
# always insert a newline after a wrapped one
from bla import foo, test, goo, \
another_thing
def some_method_thats_too_long_for_80_columns(foo_argument, bar_argument, bla_argument,
baz_argument):
do_something(test, bla, baz)
value = 123 * foo + ten \
- bla
if test > 20 \
and x < 4:
test_something()
elif foo > 7 \
and bla == 2 \
or me == blaaaaaa:
test_the_megamoth()
Also I have some guidelines for comparison operations, I always use is(not) to check against None True False and I never do an implicit boolean comparison like if foo:, I always do if foo is True:, dynamic typing is nice but in some cases I just want to be sure that the thing does the right thing!
Another thing that I do is to never use empty strings! They are in a constants file, in the rest of the code I have stuff like username == UNSET_USERNAME or label = UNSET_LABEL it's just more descriptive that way!
I also have some strict whitespace guidelines and other crazy stuff, but I like it(because I'm crazy about it), I even wrote a script which checks my code:
http://github.com/BonsaiDen/Atarashii/blob/master/checkstyle
WARNING(!): It will hurt your feelings! Even more than JSLint does...
But that's just my 2 cents.
| Common coding style for Python? | I'm pretty new to Python, and I want to develop my first serious open source project. I want to ask what is the common coding style for python projects. I'll put also what I'm doing right now.
1.- What is the most widely used column width? (the eternal question)
I'm currently sticking to 80 columns (and it's a pain!)
2.- What quotes to use? (I've seen everything and PEP 8 does not mention anything clear)
I'm using single quotes for everything but docstrings, which use triple double quotes.
3.- Where do I put my imports?
I'm putting them at file header in this order.
import sys
import -rest of python modules needed-
import whatever
import -rest of application modules-
<code here>
4.- Can I use "import whatever.function as blah"?
I saw some documents that disregard doing this.
5.- Tabs or spaces for indenting?
Currently using 4 spaces tabs.
6.- Variable naming style?
I'm using lowercase for everything but classes, which I put in camelCase.
Anything you would recommend?
| [
"PEP 8 is pretty much \"the root\" of all common style guides.\nGoogle's Python style guide has some parts that are quite well thought of, but others are idiosyncratic (the two-space indents instead of the popular four-space ones, and the CamelCase style for functions and methods instead of the camel_case style, are pretty major idiosyncrasies).\nOn to your specific questions:\n\n1.- What is the most widely used column width? (the eternal question)\n I'm currently sticking to 80 columns\n (and it's a pain!)\n\n80 columns is most popular\n\n2.- What quotes to use? (I've seen everything and PEP 8 does not mention\n anything clear) I'm using single\n quotes for everything but docstrings,\n which use triple double quotes.\n\nI prefer the style you're using, but even Google was not able to reach a consensus about this:-(\n\n3.- Where do I put my imports? I'm putting them at file header in this\n order.\nimport sys import -rest of python\n modules needed-\nimport whatever import -rest of\n application modules-\n\n\nYes, excellent choice, and popular too.\n\n4.- Can I use \"import whatever.function as blah\"? I saw some\n documents that disregard doing this.\n\nI strongly recommend you always import modules -- not specific names from inside a module. This is not just style -- there are strong advantages e.g. in testability in doing that. The as clause is fine, to shorten a module's name or avoid clashes.\n\n5.- Tabs or spaces for indenting? Currently using 4 spaces tabs.\n\nOverwhelmingly most popular.\n\n6.- Variable naming style? I'm using lowercase for everything but classes,\n which I put in camelCase.\n\nAlmost everybody names classes with uppercase initial and constants with all-uppercase.\n",
"1.- Most everyone has a 16:9 or 16:10 monitor now days. Even if they don't have a wide-screen they have lots of pixels, 80 cols isn't a big practical deal breaker like it was when everyone was hacking at the command line in a remote terminal window on a 4:3 monitor at 320 X 240. I usually end the line when it gets too long, which is subjective. I am at 2048 X 1152 on a 23\" Monitor X 2.\n2.- Single quotes by default so you don't have to escape Double quotes, Double quotes when you need to embed single quotes, and Triple quotes for strings with embedded newlines.\n3.- Put them at the top of the file, sometimes you put them in the main function if they aren't needed globally to the module.\n4.- It is a common idiom to rename some modules. A good example is the following.\ntry:\n # for Python 2.6.x\n import json\nexcept ImportError:\n # for previous Pythons\n try:\n import simplejson as json\n except ImportError:\n sys.exit('easy_install simplejson')\n\nbut the preferred way to import just a class or function is from module import xxx with the optional as yyy if needed\n5.- Always use SPACES! 2 or 4 as long as no TABS\n6.- Classes should up UpperCaseCamelStyle, variables are lowercase sometimes lowerCamelCase or sometimes all_lowecase_separated_by_underscores, as are function names. \"Constants\" should be ALL_UPPER_CASE_SEPARATED_BY_UNDERSCORES\nWhen in doubt refer to the PEP 8, the Python source, existing conventions in a code base. But the most import thing is to be internally consistent as possible. All Python code should look like it was written by the same person when ever possible.\n",
"Since I'm really crazy about \"styling\" I'll write down the guidelines that I currently use in a near 8k SLOC project with about 35 files, most of it matches PEP8.\n\nPEP8 says 79(WTF?), I go with 80 and I'm used to it now. Less eye movement after all!\nDocstrings and stuff that spans multiple lines in '''. Everything else in ''. Also I don't like double quotes, I only use single quotes all the time... guess that's because I came form the JavaScript corner, where it's just easier too use '', because that way you don't have to escape all the HTML stuff :O\nAt the head, built-in before custom application code. But I also go with a \"fail early\" approach, so if there's something that's version depended(GTK for example) I'd import that first.\nDepends, most of the times I go with import foo and from foo import, but there a certain cases(e.G. the name is already defined by another import) were I use from foo import bar as bla too.\n4 Spaces. Period. If you really want to use tabs, make sure to convert them to spaces before committing when working with SCM. BUT NEVER(!) MIX TABS AND SPACES!!! It can AND WILL introduce horrible bugs.\nsome_method or foo_function, a CONSTANT, MyClass.\n\nAlso you can argue about indentation in cases where a method call or something spans multiple lines, and you can argue about which line continuation style you will use. Either surround everything with () or do the \\ at the end of the line thingy. I do the latter, and I also place operators and other stuff at the start of the next line.\n# always insert a newline after a wrapped one\nfrom bla import foo, test, goo, \\\n another_thing\n\ndef some_method_thats_too_long_for_80_columns(foo_argument, bar_argument, bla_argument,\n baz_argument):\n\n do_something(test, bla, baz)\n\n value = 123 * foo + ten \\\n - bla\n\n if test > 20 \\\n and x < 4:\n\n test_something()\n\n elif foo > 7 \\\n and bla == 2 \\\n or me == blaaaaaa:\n\n test_the_megamoth()\n\nAlso I have some guidelines for comparison operations, I always use is(not) to check against None True False and I never do an implicit boolean comparison like if foo:, I always do if foo is True:, dynamic typing is nice but in some cases I just want to be sure that the thing does the right thing! \nAnother thing that I do is to never use empty strings! They are in a constants file, in the rest of the code I have stuff like username == UNSET_USERNAME or label = UNSET_LABEL it's just more descriptive that way!\nI also have some strict whitespace guidelines and other crazy stuff, but I like it(because I'm crazy about it), I even wrote a script which checks my code:\nhttp://github.com/BonsaiDen/Atarashii/blob/master/checkstyle\nWARNING(!): It will hurt your feelings! Even more than JSLint does...\nBut that's just my 2 cents.\n"
] | [
20,
2,
1
] | [] | [] | [
"coding_style",
"column_width",
"indentation",
"naming_conventions",
"python"
] | stackoverflow_0002815272_coding_style_column_width_indentation_naming_conventions_python.txt |
Q:
Given a date range how to calculate the number of weekends partially or wholly within that range?
Given a date range how to calculate the number of weekends partially or wholly within that range?
(A few definitions as requested:
take 'weekend' to mean Saturday and Sunday.
The date range is inclusive i.e. the end date is part of the range
'wholly or partially' means that any part of the weekend falling within the date range means the whole weekend is counted.)
To simplify I imagine you only actually need to know the duration and what day of the week the initial day is...
I darn well now it's going to involve doing integer division by 7 and some logic to add 1 depending on the remainder but I can't quite work out what...
extra points for answers in Python ;-)
Edit
Here's my final code.
Weekends are Friday and Saturday (as we are counting nights stayed) and days are 0-indexed starting from Monday. I used onebyone's algorithm and Tom's code layout. Thanks a lot folks.
def calc_weekends(start_day, duration):
days_until_weekend = [5, 4, 3, 2, 1, 1, 6]
adjusted_duration = duration - days_until_weekend[start_day]
if adjusted_duration < 0:
weekends = 0
else:
weekends = (adjusted_duration/7)+1
if start_day == 5 and duration % 7 == 0: #Saturday to Saturday is an exception
weekends += 1
return weekends
if __name__ == "__main__":
days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
for start_day in range(0,7):
for duration in range(1,16):
print "%s to %s (%s days): %s weekends" % (days[start_day], days[(start_day+duration) % 7], duration, calc_weekends(start_day, duration))
print
A:
General approach for this kind of thing:
For each day of the week, figure out how many days are required before a period starting on that day "contains a weekend". For instance, if "contains a weekend" means "contains both the Saturday and the Sunday", then we have the following table:
Sunday: 8
Monday: 7
Tuesday: 6
Wednesday: 5
Thursday: 4
Friday: 3
Saturday: 2
For "partially or wholly", we have:
Sunday: 1
Monday: 6
Tuesday: 5
Wednesday: 4
Thursday: 3
Friday: 2
Saturday: 1
Obviously this doesn't have to be coded as a table, now that it's obvious what it looks like.
Then, given the day-of-week of the start of your period, subtract[*] the magic value from the length of the period in days (probably start-end+1, to include both fenceposts). If the result is less than 0, it contains 0 weekends. If it is equal to or greater than 0, then it contains (at least) 1 weekend.
Then you have to deal with the remaining days. In the first case this is easy, one extra weekend per full 7 days. This is also true in the second case for every starting day except Sunday, which only requires 6 more days to include another weekend. So in the second case for periods starting on Sunday you could count 1 weekend at the start of the period, then subtract 1 from the length and recalculate from Monday.
More generally, what's happening here for "whole or part" weekends is that we're checking to see whether we start midway through the interesting bit (the "weekend"). If so, we can either:
1) Count one, move the start date to the end of the interesting bit, and recalculate.
2) Move the start date back to the beginning of the interesting bit, and recalculate.
In the case of weekends, there's only one special case which starts midway, so (1) looks good. But if you were getting the date as a date+time in seconds rather than day, or if you were interested in 5-day working weeks rather than 2-day weekends, then (2) might be simpler to understand.
[*] Unless you're using unsigned types, of course.
A:
My general approach for this sort of thing: don't start messing around trying to reimplement your own date logic - it's hard, ie. you'll screw it up for the edge cases and look bad. Hint: if you have mod 7 arithmetic anywhere in your program, or are treating dates as integers anywhere in your program: you fail. If I saw the "accepted solution" anywhere in (or even near) my codebase, someone would need to start over. It beggars the imagination that anyone who considers themselves a programmer would vote that answer up.
Instead, use the built in date/time logic that comes with Python:
First, get a list of all of the days that you're interested in:
from datetime import date, timedelta
FRI = 5; SAT = 6
# a couple of random test dates
now = date.today()
start_date = now - timedelta(57)
end_date = now - timedelta(13)
print start_date, '...', end_date # debug
days = [date.fromordinal(d) for d in
range( start_date.toordinal(),
end_date.toordinal()+1 )]
Next, filter down to just the days which are weekends. In your case you're interested in Friday and Saturday nights, which are 5 and 6. (Notice how I'm not trying to roll this part into the previous list comprehension, since that'd be hard to verify as correct).
weekend_days = [d for d in days if d.weekday() in (FRI,SAT)]
for day in weekend_days: # debug
print day, day.weekday() # debug
Finally, you want to figure out how many weekends are in your list. This is the tricky part, but there are really only four cases to consider, one for each end for either Friday or Saturday. Concrete examples help make it clearer, plus this is really the sort of thing you want documented in your code:
num_weekends = len(weekend_days) // 2
# if we start on Friday and end on Saturday we're ok,
# otherwise add one weekend
#
# F,S|F,S|F,S ==3 and 3we, +0
# F,S|F,S|F ==2 but 3we, +1
# S|F,S|F,S ==2 but 3we, +1
# S|F,S|F ==2 but 3we, +1
ends = (weekend_days[0].weekday(), weekend_days[-1].weekday())
if ends != (FRI, SAT):
num_weekends += 1
print num_weekends # your answer
Shorter, clearer and easier to understand means that you can have more confidence in your code, and can get on with more interesting problems.
A:
To count whole weekends, just adjust the number of days so that you start on a Monday, then divide by seven. (Note that if the start day is a weekday, add days to move to the previous Monday, and if it is on a weekend, subtract days to move to the next Monday since you already missed this weekend.)
days = {"Saturday":-2, "Sunday":-1, "Monday":0, "Tuesday":1, "Wednesday":2, "Thursday":3, "Friday":4}
def n_full_weekends(n_days, start_day):
n_days += days[start_day]
if n_days <= 0:
n_weekends = 0
else:
n_weekends = n_days//7
return n_weekends
if __name__ == "__main__":
tests = [("Tuesday", 10, 1), ("Monday", 7, 1), ("Wednesday", 21, 3), ("Saturday", 1, 0), ("Friday", 1, 0),
("Friday", 3, 1), ("Wednesday", 3, 0), ("Sunday", 8, 1), ("Sunday", 21, 2)]
for start_day, n_days, expected in tests:
print start_day, n_days, expected, n_full_weekends(n_days, start_day)
If you want to know partial weekends (or weeks), just look at the fractional part of the division by seven.
A:
You would need external logic beside raw math. You need to have a calendar library (or if you have a decent amount of time implement it yourself) to define what a weekend, what day of the week you start on, end on, etc.
Take a look at Python's calendar class.
Without a logical definition of days in your code, a pure mathematical methods would fail on corner case, like a interval of 1 day or, I believe, anything lower then a full week (or lower then 6 days if you allowed partials).
| Given a date range how to calculate the number of weekends partially or wholly within that range? | Given a date range how to calculate the number of weekends partially or wholly within that range?
(A few definitions as requested:
take 'weekend' to mean Saturday and Sunday.
The date range is inclusive i.e. the end date is part of the range
'wholly or partially' means that any part of the weekend falling within the date range means the whole weekend is counted.)
To simplify I imagine you only actually need to know the duration and what day of the week the initial day is...
I darn well now it's going to involve doing integer division by 7 and some logic to add 1 depending on the remainder but I can't quite work out what...
extra points for answers in Python ;-)
Edit
Here's my final code.
Weekends are Friday and Saturday (as we are counting nights stayed) and days are 0-indexed starting from Monday. I used onebyone's algorithm and Tom's code layout. Thanks a lot folks.
def calc_weekends(start_day, duration):
days_until_weekend = [5, 4, 3, 2, 1, 1, 6]
adjusted_duration = duration - days_until_weekend[start_day]
if adjusted_duration < 0:
weekends = 0
else:
weekends = (adjusted_duration/7)+1
if start_day == 5 and duration % 7 == 0: #Saturday to Saturday is an exception
weekends += 1
return weekends
if __name__ == "__main__":
days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
for start_day in range(0,7):
for duration in range(1,16):
print "%s to %s (%s days): %s weekends" % (days[start_day], days[(start_day+duration) % 7], duration, calc_weekends(start_day, duration))
print
| [
"General approach for this kind of thing:\nFor each day of the week, figure out how many days are required before a period starting on that day \"contains a weekend\". For instance, if \"contains a weekend\" means \"contains both the Saturday and the Sunday\", then we have the following table:\nSunday: 8\nMonday: 7\nTuesday: 6\nWednesday: 5\nThursday: 4\nFriday: 3\nSaturday: 2\nFor \"partially or wholly\", we have:\nSunday: 1\nMonday: 6\nTuesday: 5\nWednesday: 4\nThursday: 3\nFriday: 2\nSaturday: 1\nObviously this doesn't have to be coded as a table, now that it's obvious what it looks like.\nThen, given the day-of-week of the start of your period, subtract[*] the magic value from the length of the period in days (probably start-end+1, to include both fenceposts). If the result is less than 0, it contains 0 weekends. If it is equal to or greater than 0, then it contains (at least) 1 weekend.\nThen you have to deal with the remaining days. In the first case this is easy, one extra weekend per full 7 days. This is also true in the second case for every starting day except Sunday, which only requires 6 more days to include another weekend. So in the second case for periods starting on Sunday you could count 1 weekend at the start of the period, then subtract 1 from the length and recalculate from Monday.\nMore generally, what's happening here for \"whole or part\" weekends is that we're checking to see whether we start midway through the interesting bit (the \"weekend\"). If so, we can either:\n\n1) Count one, move the start date to the end of the interesting bit, and recalculate.\n2) Move the start date back to the beginning of the interesting bit, and recalculate.\n\nIn the case of weekends, there's only one special case which starts midway, so (1) looks good. But if you were getting the date as a date+time in seconds rather than day, or if you were interested in 5-day working weeks rather than 2-day weekends, then (2) might be simpler to understand.\n[*] Unless you're using unsigned types, of course.\n",
"My general approach for this sort of thing: don't start messing around trying to reimplement your own date logic - it's hard, ie. you'll screw it up for the edge cases and look bad. Hint: if you have mod 7 arithmetic anywhere in your program, or are treating dates as integers anywhere in your program: you fail. If I saw the \"accepted solution\" anywhere in (or even near) my codebase, someone would need to start over. It beggars the imagination that anyone who considers themselves a programmer would vote that answer up.\nInstead, use the built in date/time logic that comes with Python:\nFirst, get a list of all of the days that you're interested in:\nfrom datetime import date, timedelta \nFRI = 5; SAT = 6\n\n# a couple of random test dates\nnow = date.today()\nstart_date = now - timedelta(57)\nend_date = now - timedelta(13)\nprint start_date, '...', end_date # debug\n\ndays = [date.fromordinal(d) for d in \n range( start_date.toordinal(),\n end_date.toordinal()+1 )]\n\nNext, filter down to just the days which are weekends. In your case you're interested in Friday and Saturday nights, which are 5 and 6. (Notice how I'm not trying to roll this part into the previous list comprehension, since that'd be hard to verify as correct).\nweekend_days = [d for d in days if d.weekday() in (FRI,SAT)]\n\nfor day in weekend_days: # debug\n print day, day.weekday() # debug\n\nFinally, you want to figure out how many weekends are in your list. This is the tricky part, but there are really only four cases to consider, one for each end for either Friday or Saturday. Concrete examples help make it clearer, plus this is really the sort of thing you want documented in your code:\nnum_weekends = len(weekend_days) // 2\n\n# if we start on Friday and end on Saturday we're ok,\n# otherwise add one weekend\n# \n# F,S|F,S|F,S ==3 and 3we, +0\n# F,S|F,S|F ==2 but 3we, +1\n# S|F,S|F,S ==2 but 3we, +1\n# S|F,S|F ==2 but 3we, +1\n\nends = (weekend_days[0].weekday(), weekend_days[-1].weekday())\nif ends != (FRI, SAT):\n num_weekends += 1\n\nprint num_weekends # your answer\n\nShorter, clearer and easier to understand means that you can have more confidence in your code, and can get on with more interesting problems.\n",
"To count whole weekends, just adjust the number of days so that you start on a Monday, then divide by seven. (Note that if the start day is a weekday, add days to move to the previous Monday, and if it is on a weekend, subtract days to move to the next Monday since you already missed this weekend.)\ndays = {\"Saturday\":-2, \"Sunday\":-1, \"Monday\":0, \"Tuesday\":1, \"Wednesday\":2, \"Thursday\":3, \"Friday\":4}\n\ndef n_full_weekends(n_days, start_day):\n n_days += days[start_day]\n if n_days <= 0:\n n_weekends = 0\n else:\n n_weekends = n_days//7\n return n_weekends\n\nif __name__ == \"__main__\":\n tests = [(\"Tuesday\", 10, 1), (\"Monday\", 7, 1), (\"Wednesday\", 21, 3), (\"Saturday\", 1, 0), (\"Friday\", 1, 0),\n (\"Friday\", 3, 1), (\"Wednesday\", 3, 0), (\"Sunday\", 8, 1), (\"Sunday\", 21, 2)]\n for start_day, n_days, expected in tests:\n print start_day, n_days, expected, n_full_weekends(n_days, start_day)\n\nIf you want to know partial weekends (or weeks), just look at the fractional part of the division by seven.\n",
"You would need external logic beside raw math. You need to have a calendar library (or if you have a decent amount of time implement it yourself) to define what a weekend, what day of the week you start on, end on, etc.\nTake a look at Python's calendar class.\nWithout a logical definition of days in your code, a pure mathematical methods would fail on corner case, like a interval of 1 day or, I believe, anything lower then a full week (or lower then 6 days if you allowed partials).\n"
] | [
5,
2,
1,
0
] | [] | [] | [
"date",
"date_arithmetic",
"python"
] | stackoverflow_0000883615_date_date_arithmetic_python.txt |
Q:
Having trouble with time.sleep
When I run, for example:
print("[",end=" ")
time.sleep(1)
print("=",end=" ")
time.sleep(1)
print("=",end=" ")
time.sleep(1)
print("=",end=" ")
time.sleep(1)
print("=",end=" ")
time.sleep(1)
print("=",end=" ")
time.sleep(1)
print("=",end=" ")
time.sleep(1)
print("=",end=" ")
time.sleep(1)
print("=",end=" ")
time.sleep(1)
print("=",end=" ")
time.sleep(1)
print("=",end=" ")
time.sleep(1)
print("]",end=" ")
Nothing happens for 10 seconds, then the whole [ = = = = = = = = = = ] appears. How can I prevent that so that it can act as a sort of progress bar?
A:
Try flushing stdout after each print:
import sys
print("=",end=" ")
sys.stdout.flush()
A:
Actually, a progress bar belongs to sys.stderr, which is (very conveniently and not coincidentally at all) not buffered. So I suggest you:
print("=", end=" ", file=sys.stderr)
instead.
PS a synopsis of the standard input, output and error streams in POSIX-conformant operating systems can be found in Wikipedia: Standard streams.
In a few words: stdin is the input to a process; stdout is the useful output of a process, the results; stderr is for warnings, errors and out-of-band (e.g. progress bars) output.
A:
sys.stdout.flush()
A:
You need to flush stdout using sys.stdout.flush() every time you want to write the updates.
| Having trouble with time.sleep | When I run, for example:
print("[",end=" ")
time.sleep(1)
print("=",end=" ")
time.sleep(1)
print("=",end=" ")
time.sleep(1)
print("=",end=" ")
time.sleep(1)
print("=",end=" ")
time.sleep(1)
print("=",end=" ")
time.sleep(1)
print("=",end=" ")
time.sleep(1)
print("=",end=" ")
time.sleep(1)
print("=",end=" ")
time.sleep(1)
print("=",end=" ")
time.sleep(1)
print("=",end=" ")
time.sleep(1)
print("]",end=" ")
Nothing happens for 10 seconds, then the whole [ = = = = = = = = = = ] appears. How can I prevent that so that it can act as a sort of progress bar?
| [
"Try flushing stdout after each print:\nimport sys\n\nprint(\"=\",end=\" \")\nsys.stdout.flush()\n\n",
"Actually, a progress bar belongs to sys.stderr, which is (very conveniently and not coincidentally at all) not buffered. So I suggest you:\nprint(\"=\", end=\" \", file=sys.stderr)\n\ninstead.\nPS a synopsis of the standard input, output and error streams in POSIX-conformant operating systems can be found in Wikipedia: Standard streams.\nIn a few words: stdin is the input to a process; stdout is the useful output of a process, the results; stderr is for warnings, errors and out-of-band (e.g. progress bars) output.\n",
"sys.stdout.flush()\n",
"You need to flush stdout using sys.stdout.flush() every time you want to write the updates.\n"
] | [
5,
3,
0,
0
] | [] | [] | [
"buffering",
"python",
"python_3.x"
] | stackoverflow_0002814933_buffering_python_python_3.x.txt |
Q:
converting a treebank of vertical trees to s-expressions
I have a collection of parse trees, and they are in this ascii representation where indentation determines the structure (and closing brackets are implicit). I need to convert them to s-expressions so that parentheses determine the structure. It's a little bit like python's significant whitespace vs. braces. The input format is a vertical representation of trees, like so:
STA:fcl
=S:np
==DN:pron-dem("tia" <*> <Dem> <Du> <dem> DET P NOM) Tiaj
==H:n("akuzo" <act> <sd> P NOM) akuzoj
=fA:adv("certe") certe
=P:v-fin("dauxri" <va+TEMP> <mv> FUT VFIN) dauxros
.
Should become:
(STA:fcl (S:np (DN:pron-dem Tiaj) (H:n akuzoj)) (fA:adv certe) (P:v-fin dauxros) .)
I have code that almost does it, but not quite. There's always a missing paren somewhere; it's getting very frustrating. Should I use a proper parser, maybe a CFG? The current (messy) code is at http://github.com/andreasvc/eodop/blob/master/arbobanko.py
A:
Focusing only on the example you're giving in this Q, and the Q's title about converting vertical trees to S-expressions, something like...:
import re
import sys
samp='''S
=NP
==(DT +def) the
== (N +ani) man
=VP
==V walks'''.splitlines()
relinelev = re.compile(r'(=*)(.*)')
reclean = re.compile(r'\s*\((\S+)[^)]*\)')
def clean(line):
return reclean.sub(r'\1', line)
def reparse(tree=samp):
stack = [-1]
for line in tree:
equals, rest = relinelev.match(line).groups()
linelev = len(equals)
while linelev < stack[-1]:
sys.stdout.softspace = False
print ')',
curlev = stack.pop()
if linelev == stack[-1]:
sys.stdout.softspace = False
print ')',
else:
stack.append(linelev)
print '(%s' % clean(rest),
while stack[-1] >= 0:
sys.stdout.softspace = False
print ')',
stack.pop()
print
reparse()
seems to work, and outputs
(S (NP (DT the) (N man)) (VP (V walks)))
I realize you're trying to do much more "cleaning" than I'm doing here, but that can be concentrated in the clean function, leaving reparse to deal with the Q's title. If you don't want to print as you go, but rather return the result as a string, the changes are of course quite minor:
def reparse(tree=samp):
stack = [-1]
result = []
for line in tree:
equals, rest = relinelev.match(line).groups()
linelev = len(equals)
while linelev < stack[-1]:
result[-1] += ')'
curlev = stack.pop()
if linelev == stack[-1]:
result[-1] += ')'
else:
stack.append(linelev)
result.append('(%s' % clean(rest))
while stack[-1] >= 0:
result[-1] += ')'
stack.pop()
return ' '.join(result)
| converting a treebank of vertical trees to s-expressions | I have a collection of parse trees, and they are in this ascii representation where indentation determines the structure (and closing brackets are implicit). I need to convert them to s-expressions so that parentheses determine the structure. It's a little bit like python's significant whitespace vs. braces. The input format is a vertical representation of trees, like so:
STA:fcl
=S:np
==DN:pron-dem("tia" <*> <Dem> <Du> <dem> DET P NOM) Tiaj
==H:n("akuzo" <act> <sd> P NOM) akuzoj
=fA:adv("certe") certe
=P:v-fin("dauxri" <va+TEMP> <mv> FUT VFIN) dauxros
.
Should become:
(STA:fcl (S:np (DN:pron-dem Tiaj) (H:n akuzoj)) (fA:adv certe) (P:v-fin dauxros) .)
I have code that almost does it, but not quite. There's always a missing paren somewhere; it's getting very frustrating. Should I use a proper parser, maybe a CFG? The current (messy) code is at http://github.com/andreasvc/eodop/blob/master/arbobanko.py
| [
"Focusing only on the example you're giving in this Q, and the Q's title about converting vertical trees to S-expressions, something like...:\nimport re\nimport sys\n\nsamp='''S\n=NP\n==(DT +def) the\n== (N +ani) man\n=VP\n==V walks'''.splitlines()\n\nrelinelev = re.compile(r'(=*)(.*)')\nreclean = re.compile(r'\\s*\\((\\S+)[^)]*\\)')\n\ndef clean(line):\n return reclean.sub(r'\\1', line)\n\ndef reparse(tree=samp):\n stack = [-1]\n for line in tree:\n equals, rest = relinelev.match(line).groups()\n linelev = len(equals)\n while linelev < stack[-1]:\n sys.stdout.softspace = False\n print ')',\n curlev = stack.pop()\n if linelev == stack[-1]:\n sys.stdout.softspace = False\n print ')',\n else:\n stack.append(linelev)\n print '(%s' % clean(rest),\n while stack[-1] >= 0:\n sys.stdout.softspace = False\n print ')',\n stack.pop()\n print\n\nreparse()\n\nseems to work, and outputs\n(S (NP (DT the) (N man)) (VP (V walks)))\n\nI realize you're trying to do much more \"cleaning\" than I'm doing here, but that can be concentrated in the clean function, leaving reparse to deal with the Q's title. If you don't want to print as you go, but rather return the result as a string, the changes are of course quite minor:\ndef reparse(tree=samp):\n stack = [-1]\n result = []\n for line in tree:\n equals, rest = relinelev.match(line).groups()\n linelev = len(equals)\n while linelev < stack[-1]:\n result[-1] += ')'\n curlev = stack.pop()\n if linelev == stack[-1]:\n result[-1] += ')'\n else:\n stack.append(linelev)\n result.append('(%s' % clean(rest))\n while stack[-1] >= 0:\n result[-1] += ')'\n stack.pop()\n return ' '.join(result)\n\n"
] | [
1
] | [] | [] | [
"corpus",
"python"
] | stackoverflow_0002815020_corpus_python.txt |
Q:
Cleaning up temp folder after long-running subprocess exits
I have a Python script (running inside another application) which generates a bunch of temporary images. I then use subprocess to launch an application to view these.
When the image-viewing process exists, I want to remove the temporary images.
I can't do this from Python, as the Python process may have exited before the subprocess completes. I.e I cannot do the following:
p = subprocess.Popen(["imgviewer", "/example/image1.jpg", "/example/image1.jpg"])
p.communicate()
os.unlink("/example/image1.jpg")
os.unlink("/example/image2.jpg")
..as this blocks the main thread, nor could I check for the pid exiting in a thread etc
The only solution I can think of means I have to use shell=True, which I would rather avoid:
import pipes
import subprocess
cmd = ['imgviewer']
cmd.append("/example/image2.jpg")
for x in cleanup:
cmd.extend(["&&", "rm", pipes.quote(x)])
cmdstr = " ".join(cmd)
subprocess.Popen(cmdstr, shell = True)
This works, but is hardly elegant..
Basically, I have a background subprocess, and want to remove the temp files when it exits, even if the Python process no longer exists.
A:
If you're on any variant of Unix, you could fork your Python program, and have the parent process go on with its life while the child process daemonized, runs the viewer (doesn't matter in the least if that blocks the child process, which has no other job in life anyway;-), and cleans up after it. The original Python process may or may not exist at this point, but the "waiting to clean up" child process of course will (some process or other has to do the clean-up, after all, right?-).
If you're on Windows, or need cross-platform code, then have your Python program "spawn" (i.e., just start with subprocess, then go on with life) another (much smaller) one, which is the one tasked to run the viewer (blocking, who cares) and then do the clean-up. (If on Unix, even in this case you may want to daemonize, otherwise the child process might go away when the parent process does).
| Cleaning up temp folder after long-running subprocess exits | I have a Python script (running inside another application) which generates a bunch of temporary images. I then use subprocess to launch an application to view these.
When the image-viewing process exists, I want to remove the temporary images.
I can't do this from Python, as the Python process may have exited before the subprocess completes. I.e I cannot do the following:
p = subprocess.Popen(["imgviewer", "/example/image1.jpg", "/example/image1.jpg"])
p.communicate()
os.unlink("/example/image1.jpg")
os.unlink("/example/image2.jpg")
..as this blocks the main thread, nor could I check for the pid exiting in a thread etc
The only solution I can think of means I have to use shell=True, which I would rather avoid:
import pipes
import subprocess
cmd = ['imgviewer']
cmd.append("/example/image2.jpg")
for x in cleanup:
cmd.extend(["&&", "rm", pipes.quote(x)])
cmdstr = " ".join(cmd)
subprocess.Popen(cmdstr, shell = True)
This works, but is hardly elegant..
Basically, I have a background subprocess, and want to remove the temp files when it exits, even if the Python process no longer exists.
| [
"If you're on any variant of Unix, you could fork your Python program, and have the parent process go on with its life while the child process daemonized, runs the viewer (doesn't matter in the least if that blocks the child process, which has no other job in life anyway;-), and cleans up after it. The original Python process may or may not exist at this point, but the \"waiting to clean up\" child process of course will (some process or other has to do the clean-up, after all, right?-).\nIf you're on Windows, or need cross-platform code, then have your Python program \"spawn\" (i.e., just start with subprocess, then go on with life) another (much smaller) one, which is the one tasked to run the viewer (blocking, who cares) and then do the clean-up. (If on Unix, even in this case you may want to daemonize, otherwise the child process might go away when the parent process does).\n"
] | [
1
] | [] | [] | [
"python",
"subprocess",
"temporary_files"
] | stackoverflow_0002815665_python_subprocess_temporary_files.txt |
Q:
reloading module, need to re-compile sub modules?
sorry, im sure this is asked a bunch, but i couldnt find it.
in myModule.py:
from myModule.subModule import myClass
i am working on myClass, and want to stay in my ipython session and test it. reload(myModule) doesnt re-compile myClass.
how can i do this?
A:
You need to repeat your imports after reloading the "leafmost" submodule. E.g., given:
$ mkdir myModule
$ touch myModule/__init__.py
$ cat >myModule/subModule.py
class MyClass(object): kind='first'
and then
>>> from myModule.subModule import MyClass
>>> MyClass.kind
'first'
and in another terminal
$ cat >myModule/subModule.py
class MyClass(object): kind='second'
then...:
>>> import sys
>>> reload(sys.modules['myModule.subModule'])
<module 'myModule.subModule' from 'myModule/subModule.py'>
>>> from myModule.subModule import MyClass
>>> MyClass.kind
'second'
You need to go via sys.modules as you don't otherwise have a reference to the submodule, and then you need to repeat the from.
Life is much simpler if you accept the wise advice of always importing a module, never stuff from INSIDE the module, of course - e.g., the Python session would be (with a change to the submodule before the reload):
>>> from myModule import subModule as sm
>>> sm.MyClass.kind
'first'
>>> reload(sm)
<module 'myModule.subModule' from 'myModule/subModule.py'>
>>> sm.MyClass.kind
'second'
If you get into the habit of using qualified names such as sm.MyClass instead of only the barename MyClass, your life will be simpler in many respects (easier reloading is just one of them;-).
| reloading module, need to re-compile sub modules? | sorry, im sure this is asked a bunch, but i couldnt find it.
in myModule.py:
from myModule.subModule import myClass
i am working on myClass, and want to stay in my ipython session and test it. reload(myModule) doesnt re-compile myClass.
how can i do this?
| [
"You need to repeat your imports after reloading the \"leafmost\" submodule. E.g., given:\n$ mkdir myModule\n$ touch myModule/__init__.py\n$ cat >myModule/subModule.py\nclass MyClass(object): kind='first'\n\nand then\n>>> from myModule.subModule import MyClass\n>>> MyClass.kind\n'first'\n\nand in another terminal\n$ cat >myModule/subModule.py\nclass MyClass(object): kind='second'\n\nthen...:\n>>> import sys\n>>> reload(sys.modules['myModule.subModule'])\n<module 'myModule.subModule' from 'myModule/subModule.py'>\n>>> from myModule.subModule import MyClass\n>>> MyClass.kind\n'second'\n\nYou need to go via sys.modules as you don't otherwise have a reference to the submodule, and then you need to repeat the from.\nLife is much simpler if you accept the wise advice of always importing a module, never stuff from INSIDE the module, of course - e.g., the Python session would be (with a change to the submodule before the reload):\n>>> from myModule import subModule as sm\n>>> sm.MyClass.kind\n'first'\n>>> reload(sm)\n<module 'myModule.subModule' from 'myModule/subModule.py'>\n>>> sm.MyClass.kind\n'second'\n\nIf you get into the habit of using qualified names such as sm.MyClass instead of only the barename MyClass, your life will be simpler in many respects (easier reloading is just one of them;-).\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0002814609_python.txt |
Q:
Difference between Python urllib.urlretrieve() and wget
I am trying to retrieve a 500mb file using Python, and I have a script which uses urllib.urlretrieve(). There seems to some network problem between me and the download site, as this call consistently hangs and fails to complete. However, using wget to retrieve the file tends to work without problems. What is the difference between urlretrieve() and wget that could cause this difference?
A:
The answer is quite simple. Python's urllib and urllib2 are nowhere near as mature and robust as they could be. Even better than wget in my experience is cURL. I've written code that downloads gigabytes of files over HTTP with file sizes ranging from 50 KB to over 2 GB. To my knowledge, cURL is the most reliable piece of software on the planet right now for this task. I don't think python, wget, or even most web browsers can match it in terms of correctness and robustness of implementation. On a modern enough python using urllib2 in the exact right way, it can be made pretty reliable, but I still run a curl subprocess and that is absolutely rock solid.
Another way to state this is that cURL does one thing only and it does it better than any other software because it has had much more development and refinement. Python's urllib2 is serviceable and convenient and works well enough for small to average workloads, but cURL is way ahead in terms of reliability.
Also, cURL has numerous options to tune the reliability behavior including retry counts, timeout values, etc.
A:
If you are using:
page = urllib.retrieve('http://example.com/really_big_file.html')
you are creating a 500mb string which may well tax your machine, make it slow, and cause the connection to timeout. If so, you should be using:
(filename, headers) = urllib.retrieve('http://...', 'local_outputfile.html')
which won't tax the interpreter.
It is worth noting urllib.retrieve() uses urllib.urlopen() which is now deprecated.
| Difference between Python urllib.urlretrieve() and wget | I am trying to retrieve a 500mb file using Python, and I have a script which uses urllib.urlretrieve(). There seems to some network problem between me and the download site, as this call consistently hangs and fails to complete. However, using wget to retrieve the file tends to work without problems. What is the difference between urlretrieve() and wget that could cause this difference?
| [
"The answer is quite simple. Python's urllib and urllib2 are nowhere near as mature and robust as they could be. Even better than wget in my experience is cURL. I've written code that downloads gigabytes of files over HTTP with file sizes ranging from 50 KB to over 2 GB. To my knowledge, cURL is the most reliable piece of software on the planet right now for this task. I don't think python, wget, or even most web browsers can match it in terms of correctness and robustness of implementation. On a modern enough python using urllib2 in the exact right way, it can be made pretty reliable, but I still run a curl subprocess and that is absolutely rock solid.\nAnother way to state this is that cURL does one thing only and it does it better than any other software because it has had much more development and refinement. Python's urllib2 is serviceable and convenient and works well enough for small to average workloads, but cURL is way ahead in terms of reliability.\nAlso, cURL has numerous options to tune the reliability behavior including retry counts, timeout values, etc.\n",
"If you are using:\npage = urllib.retrieve('http://example.com/really_big_file.html')\n\nyou are creating a 500mb string which may well tax your machine, make it slow, and cause the connection to timeout. If so, you should be using:\n(filename, headers) = urllib.retrieve('http://...', 'local_outputfile.html')\n\nwhich won't tax the interpreter.\nIt is worth noting urllib.retrieve() uses urllib.urlopen() which is now deprecated.\n"
] | [
17,
2
] | [] | [] | [
"download",
"python",
"urllib",
"wget"
] | stackoverflow_0002777116_download_python_urllib_wget.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.