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:
How to convert a measurement displayed in an architectural format to a floating point?
I have a database that was created and is used by an architecture firm. All measurements are stored in a format like this: 15-3/4" and 12' 6-3/4".
Is there a way to convert these types of measurements into floating point in Pyt... | How to convert a measurement displayed in an architectural format to a floating point? | I have a database that was created and is used by an architecture firm. All measurements are stored in a format like this: 15-3/4" and 12' 6-3/4".
Is there a way to convert these types of measurements into floating point in Python? Or is there a library out there that provides this functionality?
Likewise, how would y... | [
"Depending on how regular the patterns are, you can use str.partition to do the parsing:\ndef architectural_to_float(text):\n ''' Convert architectural measurements to inches.\n\n >>> for text in \"\"\"15-3/4\",12' 6-3/4\",3/4\",3/4',15',15\",15.5'\"\"\".split(','):\n ... print text.ljust(10), ... | [
5,
1,
0
] | [] | [] | [
"measurement",
"python",
"regex",
"units_of_measurement"
] | stackoverflow_0008675714_measurement_python_regex_units_of_measurement.txt |
Q:
Django manage.py sqlclear omit some tables
I wrote python script for dropping tables in all Django apps. (using settings.INSTALLED_APP)
https://gist.github.com/1520683
My django project creates 41 tables after running manage.py syncdb, but my script says only 40 tables will be dropped. So, I examined the result of... | Django manage.py sqlclear omit some tables | I wrote python script for dropping tables in all Django apps. (using settings.INSTALLED_APP)
https://gist.github.com/1520683
My django project creates 41 tables after running manage.py syncdb, but my script says only 40 tables will be dropped. So, I examined the result of sqlall and result of sqlclear. And I revealed s... | [
"lqez, I gues this issue related to you local environment, because for Django 1.3.1, Python 2.7.2\nfor models\nfrom django.contrib.auth.models import User\nfrom django.db import models\n\nclass Book(models.Model):\n name = models.CharField(max_length=10)\n\nclass UserBook(models.Model):\n user = models.OneToO... | [
2
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0008633762_django_django_models_python.txt |
Q:
better django model design
Here is my situation:
I have a django model:
class Invoice(models.Model):
invoiceid = models.CharField(max_length=20)
totalamount = models.DecimalField(max_digits=15,decimal_places=2,default=0)
downpayment = models.DecimalField(max_digits=15,decimal_places=2,default=0)
su... | better django model design | Here is my situation:
I have a django model:
class Invoice(models.Model):
invoiceid = models.CharField(max_length=20)
totalamount = models.DecimalField(max_digits=15,decimal_places=2,default=0)
downpayment = models.DecimalField(max_digits=15,decimal_places=2,default=0)
subtotal = models.DecimalField(max... | [
"You could create an abstract base class and have both models inherit from it:\nclass InvoiceAbstract(models.Model):\n invoiceid = models.CharField(max_length=20)\n totalamount = models.DecimalField(max_digits=15,decimal_places=2,default=0)\n downpayment = models.DecimalField(max_digits=15,decimal_places=2... | [
9
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0008676924_django_django_models_python.txt |
Q:
getting 64 bit integer in python
So I am thinking of writing a bitboard in python or lisp. But I don't know how to ensure I would get a 64 bit integer in python. I have been reading documentation and found that mpz library returns a unsigned 32 bit integer. Is this true? If not what should I do?
A:
Python 2 has ... | getting 64 bit integer in python | So I am thinking of writing a bitboard in python or lisp. But I don't know how to ensure I would get a 64 bit integer in python. I have been reading documentation and found that mpz library returns a unsigned 32 bit integer. Is this true? If not what should I do?
| [
"Python 2 has two integer types: int, which is a signed integer whose size equals your machine's word size (but is always at least 32 bits), and long, which is unlimited in size.\nPython 3 has only one integer type, which is called int but is equivalent to a Python 2 long.\n",
"You have a couple of options using ... | [
33,
3
] | [] | [] | [
"bit",
"integer",
"python"
] | stackoverflow_0008676682_bit_integer_python.txt |
Q:
Python - a subprocess writing to stdin so that the main program can read it from the stdin
I have a python program which takes input from stdin. Now, I've to write another program and call it as a sub process so that every time I start this subprocess it should read data from another text file and write it to stdi... | Python - a subprocess writing to stdin so that the main program can read it from the stdin | I have a python program which takes input from stdin. Now, I've to write another program and call it as a sub process so that every time I start this subprocess it should read data from another text file and write it to stdin and then my main program reads it from stdin and uses it.
out.py:
from subprocess import Pope... | [
"The first program should read from a file (or stdin) and write to stdout (not stdin). Similarly, the second program should read from stdin and write to stdout. Now you can glue them together in the command line using the pipe symbol:\npython first.py | python second.py\n\nThat's it! None of the programs has to be ... | [
6
] | [] | [] | [
"python",
"stdin"
] | stackoverflow_0008677246_python_stdin.txt |
Q:
How do I transform every doc in a large Mongodb collection without map/reduce?
Apologies for the longish description.
I want to run a transform on every doc in a large-ish Mongodb collection with 10 million records approx 10G. Specifically I want to apply a geoip transform to the ip field in every doc and either a... | How do I transform every doc in a large Mongodb collection without map/reduce? | Apologies for the longish description.
I want to run a transform on every doc in a large-ish Mongodb collection with 10 million records approx 10G. Specifically I want to apply a geoip transform to the ip field in every doc and either append the result record to that doc or just create a whole other record linked to th... | [
"Since you have to go over \"each record\", you'll do one full table scan anyway, then a simple cursor (find()) + maybe only fetching few fields (_id, ip) should do it. python driver will do the batching under the hood, so maybe you can give a hint on what's the optimal batch size (batch_size) if the default is not... | [
1,
0
] | [] | [] | [
"mapreduce",
"mongodb",
"python"
] | stackoverflow_0008663432_mapreduce_mongodb_python.txt |
Q:
Python Dictionary or Alternative
For instance,
if dict['sample']:
//append values to dict['sample']
else:
// assign new key to the python dictionary
If dict['sample'] is empty, Python will throw errors. Does anyone know a better way to check on this?
All I want is something like that, I will have list of ... | Python Dictionary or Alternative | For instance,
if dict['sample']:
//append values to dict['sample']
else:
// assign new key to the python dictionary
If dict['sample'] is empty, Python will throw errors. Does anyone know a better way to check on this?
All I want is something like that, I will have list of data, let's say a,a,b,c,g,g,g,g,g.
So,... | [
"The old approaches of \"if key in dict\" or \"dict.get\" or \"dict.setdefault\" should all be set aside in favor of the now standard defaultdict:\ndata = \"aabcggggg\"\n\nfrom collections import defaultdict\ndd = defaultdict(list)\nfor c in data:\n dd[c].append(c)\nprint dd\n\ndefaultdict takes care of the chec... | [
13,
5,
4,
2,
0,
0,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0008667326_dictionary_python.txt |
Q:
What is a good way to generate text files from a Makefile?
My build process uses lots of 3rd-party utilities. Many of these utilities require the use of ASCII text files for configuration. I would like to generate these short text files from a Makefile. The only way I know how is to use the echo command to write o... | What is a good way to generate text files from a Makefile? | My build process uses lots of 3rd-party utilities. Many of these utilities require the use of ASCII text files for configuration. I would like to generate these short text files from a Makefile. The only way I know how is to use the echo command to write one line of the text file at a time and then redirect the output ... | [
"If you use python already in your build process, you could write a small python script that takes a template file, a target file and a number of parameters, and generates the target file from the template file, with the appropriate parameters filled in.\n"
] | [
1
] | [] | [] | [
"makefile",
"python"
] | stackoverflow_0008677698_makefile_python.txt |
Q:
Can Pythons HTMLParser edit/change a HTML elements innerText or ONLY read it
I am using the python module HTMLParser.py
I am able to parse HTML correctly but is there an option to change a HTML elements data(innerText)?
Do you know how I can do this with the module HTMLParser?
A:
No, the HTMLParser does just tha... | Can Pythons HTMLParser edit/change a HTML elements innerText or ONLY read it | I am using the python module HTMLParser.py
I am able to parse HTML correctly but is there an option to change a HTML elements data(innerText)?
Do you know how I can do this with the module HTMLParser?
| [
"No, the HTMLParser does just that: it parses through your HTML.\nYou're probably looking for Beautiful Soup. It'll create a ParseTree--a Pythonic tree of objects representing the HTML elements of your document. Then, you can search up the object (element) you want, assign it a new value, and voila!\nStolen shamele... | [
0
] | [] | [] | [
"html",
"html_parsing",
"python"
] | stackoverflow_0007655321_html_html_parsing_python.txt |
Q:
Django model error- "TypeError: 'xxx' is an invalid keyword argument for this function
I get the error:
TypeError: 'person' is an invalid keyword argument for this function
My model is:
class Investment(models.Model):
company = models.ManyToManyField("Company", related_name ="Investments_company")
financial_org ... | Django model error- "TypeError: 'xxx' is an invalid keyword argument for this function | I get the error:
TypeError: 'person' is an invalid keyword argument for this function
My model is:
class Investment(models.Model):
company = models.ManyToManyField("Company", related_name ="Investments_company")
financial_org = models.ManyToManyField("Financial_org", related_name ="Investments_financial_org")
person ... | [
"\nInstanciate your model without many to many, investment1 = Investment()\nSave your model, investment1.save()\nAdd many to many, there are several ways to do it like investment1.person.add(person_model) or investment1.person.create(name='foo')\n\nYou may not use a ManyToMany relation until a model is saved, this ... | [
27
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0008677750_django_django_models_python.txt |
Q:
Draw a weighted complex network with NetworkX
Can the package NetworkX be used to draw complex network with weights given by a distribution, for example a power law? Then can I write a code to draw the weight distribution or strength distribution, or even further to draw the weighted average nearest neighbours deg... | Draw a weighted complex network with NetworkX | Can the package NetworkX be used to draw complex network with weights given by a distribution, for example a power law? Then can I write a code to draw the weight distribution or strength distribution, or even further to draw the weighted average nearest neighbours degree of a node? then coloring each class of similar ... | [
"Edges in networkx can use the special attribute 'weight' which can be used in a number of algorithms requiring weighted edges. You can use networkx drawing commands to take these weights into account (e.g., by the spring force in a spring embedded visualisation). Something like:\n>>> import networkx as nx\n>>> im... | [
3
] | [] | [] | [
"complex_networks",
"networkx",
"python"
] | stackoverflow_0008677376_complex_networks_networkx_python.txt |
Q:
Can't load mysqlclient.18.dylib into python on Mac OS Lion
I want to get MySQL working with the system Python 2.7 in Mac OS X Lion.
I know there are a lot of questions very similar to this out there, and in fact my symptom is identical to mysql-python installation problems (on mac os x lion). However, that answer... | Can't load mysqlclient.18.dylib into python on Mac OS Lion | I want to get MySQL working with the system Python 2.7 in Mac OS X Lion.
I know there are a lot of questions very similar to this out there, and in fact my symptom is identical to mysql-python installation problems (on mac os x lion). However, that answer doesn't seem to apply to my case.
My Mac is a current MacBook P... | [
"Chances are you have set the default execution mode of the Apple-supplied Python to 32-bits, either by using defaults or by setting the VERSIONER_PYTHON_PREFER_32_BIT environment variable; see man python for details. In OS X 10.6 and 10.7 /usr/bin/python is an Apple-supplied wrapper program that determines which ... | [
0
] | [] | [] | [
"mysql",
"osx_lion",
"python"
] | stackoverflow_0008677591_mysql_osx_lion_python.txt |
Q:
Store output as text, not list
I am generating text using this :
for i in xrange(100):
sys.stdout.write(alphabet[bisect.bisect(f_list, random.random()) - 1])
i get output that looks like this:
fnhtlr hhub del tn eleo s d nerowepeldhoantah yf tr e saetenwgkoyears
oenooe urbmhonnrniwc iasseb
and I would li... | Store output as text, not list | I am generating text using this :
for i in xrange(100):
sys.stdout.write(alphabet[bisect.bisect(f_list, random.random()) - 1])
i get output that looks like this:
fnhtlr hhub del tn eleo s d nerowepeldhoantah yf tr e saetenwgkoyears
oenooe urbmhonnrniwc iasseb
and I would like to know how to store the output a... | [
"Try this:\ntext1 = ' '.join([alphabet[bisect.bisect(f_list, random.random())] for i in xrange(300)])\n\nAs to add more detail: ' '.join(list) is the pythonic way of joining a list to a string. The ' '-part says that it should be joined with a whitespace. If you for example would join it with a comma it would be ',... | [
3
] | [] | [] | [
"list",
"python",
"random",
"text"
] | stackoverflow_0008678115_list_python_random_text.txt |
Q:
Transforming data when saving and reading from database
Suppose I have this model (not real code):
class Message(models.Model):
content = models.CharField(...)
mentions = models.ManyToManyField(User)
content can for instance be:
Say hi to @Adam and @Bernard
During the Message model save(), "Adam" and "... | Transforming data when saving and reading from database | Suppose I have this model (not real code):
class Message(models.Model):
content = models.CharField(...)
mentions = models.ManyToManyField(User)
content can for instance be:
Say hi to @Adam and @Bernard
During the Message model save(), "Adam" and "Bernard" are extracted from the text, and their respective us... | [
"\nWrite a custom model field class, that extends CharField, you should overread the documentation first so that you have an idea of what's there,\nthat metaclass = models.SubfieldBase is required for the custom Field to call the custom to_python method\nOverride to_python(), it takes a database value and should re... | [
3
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0008678047_django_django_models_python.txt |
Q:
How I can make an attribute of the child model required, if it is inheriting the User class without saving?
like http://scottbarnham.com/blog/2008/08/21/extending-the-django-user-model-with-inheritance/
but can anyone suggest how I can make an attribute of the child model required, if it is inheriting the User cla... | How I can make an attribute of the child model required, if it is inheriting the User class without saving? | like http://scottbarnham.com/blog/2008/08/21/extending-the-django-user-model-with-inheritance/
but can anyone suggest how I can make an attribute of the child model required, if it is inheriting the User class without saving the user if the instance of the child model is not saved? eg.
class Customer(User):
organizatio... | [
"You're sure you're not adding an User, not a Customer. Here you are not transforming users into customers, just creating a new class. (I misread your post and thought you missed that ; I'll leave that here but anyways).\nYou probably don't want all users to be customers (For instance, you have staff).\nDid you try... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008676729_django_python.txt |
Q:
cx_Freeze/ldap: ImportError: DLL Load Failed %1 is not a valid Win32 application
I am using cx_Freeze to convert my python program to an exe. It all runs fine when it is a .py however when I come to run the exe, I get the following traceback;
Traceback (most recent call last):
File "UCA_Starter.py", line 45, in... | cx_Freeze/ldap: ImportError: DLL Load Failed %1 is not a valid Win32 application | I am using cx_Freeze to convert my python program to an exe. It all runs fine when it is a .py however when I come to run the exe, I get the following traceback;
Traceback (most recent call last):
File "UCA_Starter.py", line 45, in <module>
File "UCA_Starter.py", line 39, in main
File "C:\Python26\Scripts\Client... | [
"Try to install the 32bit version of the cx_Freeze. That worked for me.\n"
] | [
3
] | [] | [] | [
"cx_freeze",
"ldap",
"python"
] | stackoverflow_0008597126_cx_freeze_ldap_python.txt |
Q:
Django - Grouping querysets by a certain field in template
I have a table Events, ordered by a field date.
I want to print out the events in the template, but using a separate div for each date, e.g.:
<div class="content">
<h1>December 30th</h1>
<!-- div for Event 1 from December 30th -->
<!-- div for Event ... | Django - Grouping querysets by a certain field in template | I have a table Events, ordered by a field date.
I want to print out the events in the template, but using a separate div for each date, e.g.:
<div class="content">
<h1>December 30th</h1>
<!-- div for Event 1 from December 30th -->
<!-- div for Event 2 from December 30th -->
</div>
<div class="content">
<h1>Dec... | [
"You're looking for the {% regroup %} tag, which does exactly what you want. It takes a sequence of items (it has to be ordered beforehand, which yours is) and a lookup and groups the sequence by that lookup.\nview:\nevents = Event.objects.select_related.all()\n\ntemplate:\n{% regroup events by date as events_by_da... | [
23
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008678336_django_python.txt |
Q:
How to read a bitmap file and crop it afterwards?
I want to read a bitmap that represents a sprite, and crop a part of it.
Here is an example of an image.
In Matlab I would have done somethings like:
i = imread('myfile.png')
x1 = i(1:64,1:64,:)
How can I do the same in python?
A:
PIL could do that, crop functi... | How to read a bitmap file and crop it afterwards? | I want to read a bitmap that represents a sprite, and crop a part of it.
Here is an example of an image.
In Matlab I would have done somethings like:
i = imread('myfile.png')
x1 = i(1:64,1:64,:)
How can I do the same in python?
| [
"PIL could do that, crop function in particular.\nfrom PIL import Image\n\nimg = Image.open(r'yRc2a.png')\nimg = img.convert('RGBA')\nimg = img.crop((0, 0, 82, 82))\nimg.save(r'out.png')\n\nI'm not sure, seems like your image uses palette? I added convert to RGBA call so output file has transparency. Without conver... | [
3
] | [] | [] | [
"bitmap",
"python",
"windows"
] | stackoverflow_0008678386_bitmap_python_windows.txt |
Q:
What graphics library to use for graphics with Cython?
I'd like to create a chip-8 emulator with Cython, but I'm having trouble finding an openGL graphics library to use. What are my best options?
A:
Kivy is based on Cython (for internals) and OpenGL ES.
A:
You can try http://www.ogre3d.org/
A python wrapper f... | What graphics library to use for graphics with Cython? | I'd like to create a chip-8 emulator with Cython, but I'm having trouble finding an openGL graphics library to use. What are my best options?
| [
"Kivy is based on Cython (for internals) and OpenGL ES.\n",
"You can try http://www.ogre3d.org/\nA python wrapper for the same is here: http://www.ogre3d.org/tikiwiki/PyOgre\n"
] | [
2,
1
] | [] | [] | [
"cython",
"emulation",
"graphics",
"opengl",
"python"
] | stackoverflow_0008676270_cython_emulation_graphics_opengl_python.txt |
Q:
How to translate this Math Formula in Haskell or Python? (Was translated in PHP)
I'm trying to convert a Math Formula into PHP code.
You can see the formula in the accepted answer here: Applying a Math Formula in a more elegant way (maybe a recursive call would do the trick).
I'm not a professional coder so I'm tr... | How to translate this Math Formula in Haskell or Python? (Was translated in PHP) | I'm trying to convert a Math Formula into PHP code.
You can see the formula in the accepted answer here: Applying a Math Formula in a more elegant way (maybe a recursive call would do the trick).
I'm not a professional coder so I'm trying my best to translate it but my skills are limited and I've encountered several pr... | [
"Here you go.\nI place this code into the public domain.\n# Function to make an array of 'width' zeros\nfunction makerow($width){\n $row=array();\n for($x=0;$x<$width;$x++){\n $row[$x]=0;\n }\n return $row;\n}\n\n# Function to make a width*height matrix\nfunction makematrix($width,$height){\n $matrix=array();\n f... | [
14,
0,
0
] | [] | [] | [
"haskell",
"math",
"matrix",
"php",
"python"
] | stackoverflow_0008605183_haskell_math_matrix_php_python.txt |
Q:
Message Box in Python
Is there a UI library to create a message box or input box in python?
A:
Your best bet is the tkMessageBox module, which should work on all systems (as Python will typically come with Tkinter).
If you can restrict yourself to a specific operating system, better choices might be available.
... | Message Box in Python | Is there a UI library to create a message box or input box in python?
| [
"Your best bet is the tkMessageBox module, which should work on all systems (as Python will typically come with Tkinter).\nIf you can restrict yourself to a specific operating system, better choices might be available.\n",
"Simple message boxes and input boxes can be created using EasyGui, a small library using T... | [
11,
3,
2,
1
] | [] | [] | [
"python",
"user_controls",
"user_interface"
] | stackoverflow_0000257398_python_user_controls_user_interface.txt |
Q:
Amazon S3 Programmatically Access Usage Data
Is there a way to programmatically access an Amazon S3 account's usage data?
I'm building an application that will charge end-users for their use of my Amazon S3 bucket. Because I'll be the middleman between AWS and the end user for PUT/DELETE operations, I'll be able t... | Amazon S3 Programmatically Access Usage Data | Is there a way to programmatically access an Amazon S3 account's usage data?
I'm building an application that will charge end-users for their use of my Amazon S3 bucket. Because I'll be the middleman between AWS and the end user for PUT/DELETE operations, I'll be able to keep track of uploads and storage usage, but I'm... | [
"There is no way to get usage statistics with the API. This issue is actively discussed on the AWS forum over the years with no feedback from the AWS team. \nhttps://forums.aws.amazon.com/thread.jspa?messageID=277024 \nThe alternatives would be to turn on Amazon S3 server log and to analyze it yourself. \nAnother o... | [
4,
0
] | [] | [] | [
"amazon_s3",
"amazon_web_services",
"python"
] | stackoverflow_0007302591_amazon_s3_amazon_web_services_python.txt |
Q:
Generate dynamic methods in a class
I want to have a class with dynamic methods.
From these arrays:
prefix = ['android','iphone','blackberry']
method = ['AddToPush','DelFromPush','GetPushMessages']
I want to create a class like:
class MobileManager(object)
def __init__(self):
self.mobileLib = Mobil... | Generate dynamic methods in a class | I want to have a class with dynamic methods.
From these arrays:
prefix = ['android','iphone','blackberry']
method = ['AddToPush','DelFromPush','GetPushMessages']
I want to create a class like:
class MobileManager(object)
def __init__(self):
self.mobileLib = MobileLib()
def androidAddToPush(self, ar... | [
"If your set of prefixes/methods is defined at init time, you can try something like this:\nclass MobileManager(object):\n def __init__(self):\n for prefix_name in prefix:\n for method_name in method:\n func = lambda self, args: getattr(self.mobileLib, method_name)(args, prefix)\... | [
1,
0,
0
] | [] | [] | [
"code_generation",
"python",
"python_2.7"
] | stackoverflow_0008677834_code_generation_python_python_2.7.txt |
Q:
Python dictionary with list keyword
I'm coding a N'th order markov chain.
It goes something like this:
class Chain:
def __init__(self, order):
self.order = order
self.state_table = {}
def train(self, next_state, *prev_states):
if len(prev_states) != self.order: raise ValueError("prev_states does not match ... | Python dictionary with list keyword | I'm coding a N'th order markov chain.
It goes something like this:
class Chain:
def __init__(self, order):
self.order = order
self.state_table = {}
def train(self, next_state, *prev_states):
if len(prev_states) != self.order: raise ValueError("prev_states does not match chain order")
if prev_states in self.st... | [
"Tuples are hashable when their contents are.\n>>> a = {}\n>>> a[(1,2)] = 'foo'\n>>> a[(1,[])]\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: unhashable type: 'list'\n\nAs for collisions, when I try a bunch of very similar tuples, I see them being mapped widely apart:\n>>> ... | [
6,
3
] | [] | [] | [
"dictionary",
"markov_chains",
"python"
] | stackoverflow_0008679198_dictionary_markov_chains_python.txt |
Q:
Is it possible for a round-trip through Python's mktime to fail with 'out of range'?
Given the following code:
value = time.mktime(datetime.fromtimestamp(timestamp).timetuple())
Is it possible for this to produce an OverflowError 'mktime argument out of range' and, if so, what range of timestamps would cause this... | Is it possible for a round-trip through Python's mktime to fail with 'out of range'? | Given the following code:
value = time.mktime(datetime.fromtimestamp(timestamp).timetuple())
Is it possible for this to produce an OverflowError 'mktime argument out of range' and, if so, what range of timestamps would cause this?
| [
"Yes. I'm two hours ahead of UTC and on Windows. I get the error in the last two hours of the int32 range:\n>>> def roundtrip(x):\n... return time.mktime(datetime.datetime.fromtimestamp(x).timetuple())\n...\n>>> roundtrip(2**31-1-7200)\n2147476447.0\n>>> roundtrip(2**31-7200)\nOverflowError: mktime argument out... | [
3,
1
] | [] | [] | [
"datetime",
"python",
"time"
] | stackoverflow_0008499112_datetime_python_time.txt |
Q:
Binding to button is not working as expected
I bound the event <Return> to a Button, thinking that this would cause the command to be run after hitting Enter:
Button(self.f, text="Print", command=self.Printer).pack(side=RIGHT, padx=10, pady=10)
self.button1 = Button(self.f, text="search", command=self.search)
sel... | Binding to button is not working as expected | I bound the event <Return> to a Button, thinking that this would cause the command to be run after hitting Enter:
Button(self.f, text="Print", command=self.Printer).pack(side=RIGHT, padx=10, pady=10)
self.button1 = Button(self.f, text="search", command=self.search)
self.button1.bind('<Return>', self.search)
self.button... | [
"Your code looks fine, but note that the focus must be on the button if you want Return to call self.search(). You can change the focus from widget to widget by pressing Tab. The widget in focus is outlined with a thin black line. You may have to press Tab one or more times to move the focus to the button before pr... | [
13
] | [] | [] | [
"bind",
"button",
"python",
"tkinter"
] | stackoverflow_0008679453_bind_button_python_tkinter.txt |
Q:
accessing to related objects of a parent class
take a look at my models:
class Gallery(models.Model):
HeadImage = models.ImageField(upload_to="gallery",editable=True,blank=True,null=True)
class Image(models.Model):
Image = models.ImageField(upload_to="gallery")
Gallery = models.ForeignKey(Gallery, relate... | accessing to related objects of a parent class | take a look at my models:
class Gallery(models.Model):
HeadImage = models.ImageField(upload_to="gallery",editable=True,blank=True,null=True)
class Image(models.Model):
Image = models.ImageField(upload_to="gallery")
Gallery = models.ForeignKey(Gallery, related_name='images')
class Tour(Gallery):
Category=m... | [
"Trying this in the shell it works fine. Getting all images for a tour object through tour.gallery_ptr.images.all() will yield all image objects. You might have to perform this operation in your view and not in your template.\nAdditionally, when something fails in a template it fails silently. Trying this in yo... | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008679634_django_python.txt |
Q:
Python's use of global vs specifying the module
Was wondering if anyone had any thoughts on the use of Python's global vs. referencing the module itself. While in the past I used global when needed, I've found it somewhat clearer to do the second method (and recently have tended to favor this syntax):
import sys
m... | Python's use of global vs specifying the module | Was wondering if anyone had any thoughts on the use of Python's global vs. referencing the module itself. While in the past I used global when needed, I've found it somewhat clearer to do the second method (and recently have tended to favor this syntax):
import sys
mod = sys.modules[__name__]
counter = 0
def incremen... | [
"Go with global every time. The global keyword is an obvious and readily recognisable pattern for modifying something at module level. Giving a module a reference to itself from sys.modules seems a needlessly convoluted way of going around it, and is likely to confuse the next programmer who looks at it.\n",
"\nP... | [
5,
3
] | [] | [] | [
"global",
"module",
"python",
"python_3.x",
"variables"
] | stackoverflow_0008679849_global_module_python_python_3.x_variables.txt |
Q:
what exactly are built-in types in Python?
I keep hearing "everything is an object" in both Ruby and Python world. Well, what are built-in functions then? Can someone explain that in layperson English?
For example:
file=open(abc.txt)
open is a built-in function. Is it an object? Is it a method? Of what class?
Ho... | what exactly are built-in types in Python? | I keep hearing "everything is an object" in both Ruby and Python world. Well, what are built-in functions then? Can someone explain that in layperson English?
For example:
file=open(abc.txt)
open is a built-in function. Is it an object? Is it a method? Of what class?
How did we even end-up with functions in Python if... | [
"They are all listed here: http://docs.python.org/library/functions.html\nThe function open is an object (all functions are objects) and belongs to the __builtin__ module. They are simply built-in, and available to all objects, since they are automatically imported (something like from __builtin__ import *).\n>>> p... | [
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0008680591_python.txt |
Q:
Where can I learn this Python bracket operator?
I was looking at Flask those days and in their user guide I found a Python snippet as below
@app.route('/')
def show_entries():
cur = g.db.execute('select title, text from entries order by id desc')
entries = [dict(title=row[0], text=row[1]) for row in cur.fe... | Where can I learn this Python bracket operator? | I was looking at Flask those days and in their user guide I found a Python snippet as below
@app.route('/')
def show_entries():
cur = g.db.execute('select title, text from entries order by id desc')
entries = [dict(title=row[0], text=row[1]) for row in cur.fetchall()]
return render_template('show_entries.ht... | [
"The thing is called list comprehension\nI think this should be the official docs: http://docs.python.org/tutorial/datastructures.html#list-comprehensions\n",
"List comprehensions\n",
"Its called a List Comprehension, here is a link to the python documentation. \nhttp://docs.python.org/tutorial/datastructures.h... | [
3,
3,
1,
0,
0
] | [] | [] | [
"flask",
"python"
] | stackoverflow_0008680893_flask_python.txt |
Q:
Incremental instance counters in class instances
I'm writing a program which aims to generate a lot of activity in Active Directory to stress-test another piece of software. To create users, I'm creating a simple class like
class ADUser(object):
def __init__(self):
self.firstname = self.firstname() # returns... | Incremental instance counters in class instances | I'm writing a program which aims to generate a lot of activity in Active Directory to stress-test another piece of software. To create users, I'm creating a simple class like
class ADUser(object):
def __init__(self):
self.firstname = self.firstname() # returns a random name from a big list
self.lastname = sel... | [
"This is the perfect usecase for a static variable.\nclass ADUser(object):\n numEmployees = 0\n def __init__(self):\n self.firstname = self.firstname() # returns a random name from a big list\n self.lastname = self.lastname() # returns a random name from a big list\n self.fullname = sel... | [
6
] | [] | [] | [
"class",
"instance",
"python"
] | stackoverflow_0008681052_class_instance_python.txt |
Q:
How to extract parent html tag in Python by matching the string
I need to extract the parent tags in html by matching the string in html.
(i.e)
I have many raw html sources. Each source contains the text value "VIN:*"** with some characters. This text value(VIN:*) is placed in various formats in each source like ... | How to extract parent html tag in Python by matching the string | I need to extract the parent tags in html by matching the string in html.
(i.e)
I have many raw html sources. Each source contains the text value "VIN:*"** with some characters. This text value(VIN:*) is placed in various formats in each source like "< ul >" , "< div >".etc..
Then I need to extract all values along wi... | [
"I would strongly recommend going with BeautifulSoup on this; it provides some incredibly convenient functionality for parsing HTML. Here, for example, is how I would go about finding every text node that contains \"VIN\" in either case:\nsoup = your_html_here\nvins = soup.findAll(text = lambda(x): x.lower.index('v... | [
3,
1,
0
] | [] | [] | [
"html",
"lxml",
"pattern_matching",
"python",
"regex"
] | stackoverflow_0008678187_html_lxml_pattern_matching_python_regex.txt |
Q:
Does what 'page source' looks like affect performance
Possible Duplicate:
How to minify php page html output?
Any reason not to strip whitespace in HTML
I viewed some page sources and found some difference between them - some with indents some doesn't. The first screen capture is google's page source, and the se... | Does what 'page source' looks like affect performance |
Possible Duplicate:
How to minify php page html output?
Any reason not to strip whitespace in HTML
I viewed some page sources and found some difference between them - some with indents some doesn't. The first screen capture is google's page source, and the second SO's.
I want to know whether eliminating those space... | [
"This is called \"minification\". Most of the savings are in the bandwidth of not needing to transmit all of the extra whitespace, etc. - though even this is minimal overhead if GZip compression is used (transparently supported by all major web browsers and web servers). There may also be very slight performance ... | [
3,
1,
1,
0
] | [] | [] | [
"html",
"pagespeed",
"php",
"python"
] | stackoverflow_0008681187_html_pagespeed_php_python.txt |
Q:
Customized web2py registration
I am new to web2py. I want to make an application that has one admin (super user)
account. I want to restrict 'only admin can register user'. So that
once Admin logs into the app, he will see different menus like 'Home',
'Setting', and 'Register User'. I am done with other options bu... | Customized web2py registration | I am new to web2py. I want to make an application that has one admin (super user)
account. I want to restrict 'only admin can register user'. So that
once Admin logs into the app, he will see different menus like 'Home',
'Setting', and 'Register User'. I am done with other options but I am
getting problems in 'Register... | [
"If you want to take advantage of the built-in Auth register() function, you can hack it a bit as follows:\n@auth.requires_membership('admin')\ndef register()\n admin_auth = session.auth\n auth.is_logged_in = lambda: False\n def post_register(form):\n session.auth = admin_auth\n auth.user = s... | [
6
] | [] | [] | [
"authentication",
"python",
"web2py"
] | stackoverflow_0008678624_authentication_python_web2py.txt |
Q:
Python BeautifulSoup Loop
Thanks to this board I have managed to retrieve the name and the price of the item I want using this code:
import urllib2
from BeautifulSoup import BeautifulSoup
import re
html = urllib2.urlopen('http://www.toolventure.co.uk/hand-tools/saws/').read()
soup = BeautifulSoup(html)
item = ... | Python BeautifulSoup Loop | Thanks to this board I have managed to retrieve the name and the price of the item I want using this code:
import urllib2
from BeautifulSoup import BeautifulSoup
import re
html = urllib2.urlopen('http://www.toolventure.co.uk/hand-tools/saws/').read()
soup = BeautifulSoup(html)
item = re.sub('\s+', ' ', soup.h2.a.te... | [
"I'd use findAll for this:\nsoup = BeautifulSoup(html)\n\nmostwant = {'class': 'productlist_mostwanted_item '}\ngriditem = {'class': 'productlist_grid_item '}\n\ndivs = soup.findAll(attrs = mostwant) + soup.findAll(attrs = griditem)\n\nfor product in divs:\n item = product.h2.a.text.strip()\n price = re.searc... | [
4
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0008680905_beautifulsoup_python.txt |
Q:
How can I call a python instance using php?
I have a PHP program, and a Python program. You can think that the Python program is like a robot or machine. Typically, it will use a database, do some analysis and return result for you. It is a plain text console application.
I would like to let the user use the prog... | How can I call a python instance using php? | I have a PHP program, and a Python program. You can think that the Python program is like a robot or machine. Typically, it will use a database, do some analysis and return result for you. It is a plain text console application.
I would like to let the user use the program via a web interface. So, I would like to use ... | [
"You might want to check exec function. You can pass the input from user as parameters to the python script and get back the output from it.\n",
"Take a look into http://www.csh.rit.edu/~jon/projects/pip/\n"
] | [
2,
0
] | [] | [] | [
"cross_language",
"php",
"python"
] | stackoverflow_0008681420_cross_language_php_python.txt |
Q:
pyqt webkit + divx web player
I know this is probably impossible, but let's try asking anyway: what I would like to do is using the divx web player plugin within a page rendered by pythoh qt4 webkit widget. I mean: in page.html I put the standard divx web player embed code, then I load it with webkit pyqt and (mag... | pyqt webkit + divx web player | I know this is probably impossible, but let's try asking anyway: what I would like to do is using the divx web player plugin within a page rendered by pythoh qt4 webkit widget. I mean: in page.html I put the standard divx web player embed code, then I load it with webkit pyqt and (magic) it works and plays my video. Do... | [
"You'll probably need to set it to enabled using the QWebSettings, according to the documentation.\nI'd try something like\nQWebSettings.globalSettings().setAttribute(QWebSettings.PluginsEnabled, True)\n\nand see if it enables the plugins.\n"
] | [
1
] | [] | [] | [
"divx",
"pyqt",
"python",
"web",
"webkit"
] | stackoverflow_0008498440_divx_pyqt_python_web_webkit.txt |
Q:
Get object at point? wxpython
Is it possible to get what object is at point (x,y) with wxpython?
buton=wx.Button(self, id=wx.ID_ANY, label='object',pos=(10,10), size=(175, 28))
print GetObjectAtPoint(10,10) # this function does not exist
If there is anything similar to the above, that would be nice or if there ... | Get object at point? wxpython | Is it possible to get what object is at point (x,y) with wxpython?
buton=wx.Button(self, id=wx.ID_ANY, label='object',pos=(10,10), size=(175, 28))
print GetObjectAtPoint(10,10) # this function does not exist
If there is anything similar to the above, that would be nice or if there is suggestions on what I should do.... | [
"Have you tried FindWindowsAtPoint()? That's about the only thing I can think of that does something like that. You might also take a look at the Widget Inspection Tool to find out how it grabs information about widgets when you click on them.\n",
"There is\n\nwx.FindWindowAtPoint(pt)\n\nAlso\n\nGenericFindWindow... | [
2,
2
] | [] | [] | [
"python",
"wxpython",
"wxwidgets"
] | stackoverflow_0008681171_python_wxpython_wxwidgets.txt |
Q:
Django - ModelChoiceField - TypeError - __init__() takes at least 2 arguments (1 given)
I'm on Django 1.2. I'm trying to use the ModelChoiceField in a form. Why are these failing with the above error message? I'm at a loss :-(
class QueueForm(forms.Form):
queue = forms.ModelChoiceField(query_set=Order.objec... | Django - ModelChoiceField - TypeError - __init__() takes at least 2 arguments (1 given) | I'm on Django 1.2. I'm trying to use the ModelChoiceField in a form. Why are these failing with the above error message? I'm at a loss :-(
class QueueForm(forms.Form):
queue = forms.ModelChoiceField(query_set=Order.objects.all())
I also tried this:
class QueueForm(forms.Form):
queue = forms.ModelChoiceField... | [
"You're setting the wrong variable name in the constructor, it needs to be queryset and not query_set. Try this:\nclass QueueForm(forms.Form):\nqueue = forms.ModelChoiceField(queryset=Order.objects.all())\n\n"
] | [
7
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0008681298_django_django_forms_python.txt |
Q:
How to get current url of a parsed HTML page in Python with lxml?
In Python I'm parsing various URLs to find some elements in the body of the returned document. I'm using lxml for this, like so:
import lxml.html as html
url = 'http://www.linktowebsite.com'
data = html.parse(url)
for d in data.xpath('body'):
... | How to get current url of a parsed HTML page in Python with lxml? | In Python I'm parsing various URLs to find some elements in the body of the returned document. I'm using lxml for this, like so:
import lxml.html as html
url = 'http://www.linktowebsite.com'
data = html.parse(url)
for d in data.xpath('body'):
code code code
Some urls however redirect to a different page and I wa... | [
"Use data.docinfo.URL documentation\nExample:\nIn [22]: data = html.parse('http://httpbin.org/redirect/2')\n\nIn [23]: data.docinfo.URL\nOut[23]: u'http://httpbin.org/get'\n\n"
] | [
4
] | [] | [] | [
"lxml",
"parsing",
"python",
"url"
] | stackoverflow_0008681237_lxml_parsing_python_url.txt |
Q:
xlwt - How to add page breaks to an Excel File?
I'm trying to add page breaks whenever a column's value changes in Excel using Python and xlwt.
Does anyone know how to do this?
I found one example but they don't really say if their code works, and they don't say what the numbers mean in the tuple:
ws.horz_page_bre... | xlwt - How to add page breaks to an Excel File? | I'm trying to add page breaks whenever a column's value changes in Excel using Python and xlwt.
Does anyone know how to do this?
I found one example but they don't really say if their code works, and they don't say what the numbers mean in the tuple:
ws.horz_page_breaks = [(54, 0, 255), (108, 0, 255)]
| [
"Doing some web research I found this OpenOffice.org document describing Excel's format and BIFF records. It seems for horizontal breaks (pag. 181), each tuple represents:\n\nIndex to first row BELOW the page break\nIndex to first column of the page break\nIndex to last column of the page break\n\nSo, for the examp... | [
5,
2
] | [] | [] | [
"excel",
"python",
"xlwt"
] | stackoverflow_0008590741_excel_python_xlwt.txt |
Q:
FFT in Matlab and numpy / scipy give different results
I am trying to re-implement one of the matlab toolboxes.
they use fft over there.
when i perform same operation on the same data i get different results to those from matlab.
Just take a look:
MATLAB:
Msig =
0 0 0 0
0 0 0 0
0 ... | FFT in Matlab and numpy / scipy give different results | I am trying to re-implement one of the matlab toolboxes.
they use fft over there.
when i perform same operation on the same data i get different results to those from matlab.
Just take a look:
MATLAB:
Msig =
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 1 0 0
0 ... | [
"Matlab applies the fft over the columns of the matrix, numpy applies the fft over the last axis (the rows) by default. You want:\n>>> np.fft.fft(Msig.T, axis=0)\narray([[ 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j, 0.+0.j],\n [ 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.-1.j, 0.+0.j],\n [ 0.+0.j, 0.+0.j,... | [
16
] | [] | [] | [
"fft",
"matlab",
"numpy",
"python",
"scipy"
] | stackoverflow_0008680909_fft_matlab_numpy_python_scipy.txt |
Q:
Is there a way to make my Python program run a lot faster?
I have written a computer program in python but it runs a lot slower than I want it to.
Here is the code:
from gzip import GzipFile
from cStringIO import StringIO
import re
import webbrowser
import time
from difflib import SequenceMatcher
import os
import... | Is there a way to make my Python program run a lot faster? | I have written a computer program in python but it runs a lot slower than I want it to.
Here is the code:
from gzip import GzipFile
from cStringIO import StringIO
import re
import webbrowser
import time
from difflib import SequenceMatcher
import os
import sys
from BeautifulSoup import BeautifulSoup
import eventlet
fro... | [
"The first step to speeding up any program is to understand why it's slow -- i.e., where is the time going? The tool programmers use to do this is called a profiler. Standard Python includes several of these: you can learn about them here. \nOnce you've learned to use a profiler, run it on your program to identify ... | [
6,
2
] | [] | [] | [
"performance",
"python"
] | stackoverflow_0008681766_performance_python.txt |
Q:
Python language support for pipes
I would like to implement in python something like this:
def producer():
while True:
sys.stdout.write("this is my data\n")
def consumer():
while True:
data = sys.stdin.read()
print data
producer | consumer
The pipe actually needs to create two pr... | Python language support for pipes | I would like to implement in python something like this:
def producer():
while True:
sys.stdout.write("this is my data\n")
def consumer():
while True:
data = sys.stdin.read()
print data
producer | consumer
The pipe actually needs to create two processes, connect stdout and stdin, and ... | [
"You can use the pipes module:\n\nThe pipes module defines a class to abstract the concept of a pipeline — a sequence of converters from one file to another.\n\nSure, the syntax won't be the same as a shell pipe, but why reinvent the wheel?\n",
"You may be thinking of coroutines. Check out this very interesting ... | [
2,
1
] | [] | [] | [
"multiprocessing",
"pipe",
"python"
] | stackoverflow_0008680880_multiprocessing_pipe_python.txt |
Q:
How do I assign a variable to an object name?
Tried the following, where "objectname" contains a string name, to be assigned on creation of an object.
for record in result:
objectname = 'Customer' + str(record[0])
print objectname
customername = str(record[1])
objectname = Customer(customername)
W... | How do I assign a variable to an object name? | Tried the following, where "objectname" contains a string name, to be assigned on creation of an object.
for record in result:
objectname = 'Customer' + str(record[0])
print objectname
customername = str(record[1])
objectname = Customer(customername)
Where Customer is a class.
In my test, this loop run... | [
"Instead of using a new variable for each customer you could store your object in a Python dictionary:\nd = dict()\n\nfor record in result:\n objectname = 'Customer' + str(record[0])\n customername = str(record[1])\n d[objectname] = Customer(customername)\n\nprint d\n\nAn example of objects stored in dicti... | [
6,
6,
1
] | [] | [] | [
"python"
] | stackoverflow_0008682336_python.txt |
Q:
do not understand this use of sys module
Here is code from a tutorial in A Byte of Python:
import sys
filename = 'poem.txt'
def readfile(filename):
#Print a file to standard output
f = file(filename)
while True:
line = f.readline()
if len(line) == 0:
break
print li... | do not understand this use of sys module | Here is code from a tutorial in A Byte of Python:
import sys
filename = 'poem.txt'
def readfile(filename):
#Print a file to standard output
f = file(filename)
while True:
line = f.readline()
if len(line) == 0:
break
print line,
f.close()
if len(sys.argv) < 2:
p... | [
"It's telling you that sys.exit() has executed on line 17 of your program.\nThe entry for for sys.exit in the Python documentation tells you that this exits your program.\nThere's no way this line can execute without producing other output, so I think there's something missing in the question.\n",
"If you're usin... | [
3,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0008681840_python.txt |
Q:
Import .txt file and use in markov model
I am using this code to generate random text :
from collections import defaultdict, Counter
from itertools import ifilter
from random import choice, randrange
def pairwise(iterable):
it = iter(iterable)
last = next(it)
for curr in it:
yield last, curr
... | Import .txt file and use in markov model | I am using this code to generate random text :
from collections import defaultdict, Counter
from itertools import ifilter
from random import choice, randrange
def pairwise(iterable):
it = iter(iterable)
last = next(it)
for curr in it:
yield last, curr
last = curr
valid = set('abcdefghijklm... | [
"Open the file, read it in, use it. I'd use the with statement which will guarantee the file gets closed afterwards.\nwith open(my_file, 'r') as f:\n text = f.read()\nmodel = make_markov(text)\n\nFor quick and dirty code you can do it all in one go.\nmodel = make_markov(open(my_file, 'r').read())\n\n",
"Your p... | [
2,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0008682077_python.txt |
Q:
Understanding "runwithfriends" facebook-app sample code
this is my first web-programming experience so I hope my questions doesn't sound very dumb. I have been stucked on this for many days.
I am trying to understand a sample code:
https://github.com/facebook/runwithfriends
However I am not understanding very wel... | Understanding "runwithfriends" facebook-app sample code | this is my first web-programming experience so I hope my questions doesn't sound very dumb. I have been stucked on this for many days.
I am trying to understand a sample code:
https://github.com/facebook/runwithfriends
However I am not understanding very well how the information flow works and how can I modify that sa... | [
"The python \"SDK\" for facebook I use I took from https://gist.github.com/1190267\nand combined it with the code from the example app to achieve the functionality I wanted both for a canvas app and for website usage. \nIt depends whether you're using facebook with websites or a canvas application. For a canvas app... | [
1
] | [] | [] | [
"facebook_apps",
"google_app_engine",
"python"
] | stackoverflow_0008675810_facebook_apps_google_app_engine_python.txt |
Q:
Python: variables scope and profile.run
I want to call profile.run within my function, i.e.:
def g():
...
def f():
x = ...
run.profile('g(x)')
However, it says 'x is not defined' when calling run.profile. As far as I understand, I have to supply import statement before calling g(x) inside string argum... | Python: variables scope and profile.run | I want to call profile.run within my function, i.e.:
def g():
...
def f():
x = ...
run.profile('g(x)')
However, it says 'x is not defined' when calling run.profile. As far as I understand, I have to supply import statement before calling g(x) inside string argument to run.profile, and I could do this with ... | [
"Instead of using run() use runctx() which allows you to supply locals and globals. For example:\n>>> import cProfile\n>>> def g(x):\n... print \"g(%d)\" % x\n... \n>>> x=100\n>>> cProfile.runctx('g(x)', {'x': x, 'g': g}, {})\ng(100)\n 3 function calls in 0.000 CPU seconds\n\n Ordered by: standard name\... | [
20,
2
] | [] | [] | [
"profile",
"python",
"scope",
"variables"
] | stackoverflow_0008682716_profile_python_scope_variables.txt |
Q:
Define a dictionary name within a function
I am writing a function that will take a parameter and, among other things, make a dictionary. I would like the dictionary's name to be based off the name of the input file. Say ht input file is input.xml , i would like the name of the dictionary to be input. Ideally I wo... | Define a dictionary name within a function | I am writing a function that will take a parameter and, among other things, make a dictionary. I would like the dictionary's name to be based off the name of the input file. Say ht input file is input.xml , i would like the name of the dictionary to be input. Ideally I would use something like this:
def function(input)... | [
"The thing about named variables is that you can call them whatever you like. It's best to name them specific to the context you're using them with.\nIt would be a better move to simply return a dictionary from your method, instead.\n",
"The other respondents are legitimately concerned about why you would want to... | [
4,
1
] | [
"def make_name(input):\n return = input.split('.')[0]\n\ndef function(input):\n \"\"\"Note: this function is incomplete and assumes additional parameters are in your original script\n \"\"\"\n for x in y: list(get value)\n dict_name[key] = [value]\n return dict_name\n\ndef make_dict(input): \n... | [
-1
] | [
"python"
] | stackoverflow_0008682607_python.txt |
Q:
What is the best way to create multiple bullets in Python using Pygame?
I just started studying Python two days ago, so my code is sloppy...But I'm just trying to get something that works. I'm working on a simple shmup. I'm trying to get bullets to fire by holding down on the Z key...The problem I'm facing at th... | What is the best way to create multiple bullets in Python using Pygame? | I just started studying Python two days ago, so my code is sloppy...But I'm just trying to get something that works. I'm working on a simple shmup. I'm trying to get bullets to fire by holding down on the Z key...The problem I'm facing at the moment is getting multiple bullets to work correctly. No matter what I do,... | [
"Your code was a little hard to follow for me -- I'm fairly new to programming myself. However, I do have a few suggestions that might help a little.\nFirst, you seem to be hardcoding in the coordinates of your bullets (ie bullet1, bullet2, and bX1, bY1 etc.). Because you seem to be unable to fire more then 5 bul... | [
2
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0008675268_pygame_python.txt |
Q:
Python (Django) Class that aliases/overloads list index behavior to attributes
I have a class that stores information about a week:
from django.db import models
#A django model, so can't subclass list (at least not easily)
class MyWeek(models.Model):
sunday = "foo"
monday = "foo"
tuesday = "fo... | Python (Django) Class that aliases/overloads list index behavior to attributes | I have a class that stores information about a week:
from django.db import models
#A django model, so can't subclass list (at least not easily)
class MyWeek(models.Model):
sunday = "foo"
monday = "foo"
tuesday = "foo"
wednesday = "foo"
thursday = "foo"
friday = "foo"
saturday =... | [
"To create a list-like object in python you need to create the following methods:\n__len__, __getitem__, __setitem__, __delitem__, __iter__, and __contains__\nLink to explanatory example.\n"
] | [
4
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0008683009_django_django_models_python.txt |
Q:
what is a commandline argument?
I am a newcomer to python (also very sorry if this is a newb question but) i have no idea what a command line argument is. when sys.argv is called, what exactly are the arguments? Any help with understanding this would be a great service.
A:
Try running this program:
import sys
pr... | what is a commandline argument? | I am a newcomer to python (also very sorry if this is a newb question but) i have no idea what a command line argument is. when sys.argv is called, what exactly are the arguments? Any help with understanding this would be a great service.
| [
"Try running this program:\nimport sys\nprint(sys.argv)\n\nYou should see results similar to this:\n% test.py\n['/home/unutbu/pybin/test.py']\n% test.py foo\n['/home/unutbu/pybin/test.py', 'foo']\n% test.py foo bar\n['/home/unutbu/pybin/test.py', 'foo', 'bar']\n% python test.py foo\n['test.py', 'foo']\n\nSo, you se... | [
7,
6,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0008681973_python.txt |
Q:
jinja2 macros vs jsp2.0 tags
I am a java programmer learning python/jinja.
My biggest beef with jinja2 macros is the limitation of having a single caller().
for example, i could do the following in jsp2 tags:
tag def:
<% attribute name="title" fragment="true">
<div class='title'>${title}</div>
<div class='body'>... | jinja2 macros vs jsp2.0 tags | I am a java programmer learning python/jinja.
My biggest beef with jinja2 macros is the limitation of having a single caller().
for example, i could do the following in jsp2 tags:
tag def:
<% attribute name="title" fragment="true">
<div class='title'>${title}</div>
<div class='body'><jsp:doBody/></div>
usage:
<myTag... | [
"So in fact this is a core feature of Mako Templates for Python. It's not as widely used of a feature but it's important to me, as it's pretty critical in custom template tags as you mention, so it's there:\nhttp://www.makotemplates.org/docs/defs.html#calling-a-def-with-embedded-content-and-or-other-defs\nJSP is ... | [
5,
5,
3,
0
] | [] | [] | [
"java",
"jinja2",
"jsp",
"python"
] | stackoverflow_0007745900_java_jinja2_jsp_python.txt |
Q:
Do you use any client-side javascript library or jQuery plugin for WebSockets?
I need to deal with breaking connections and other standard things which are not handled by WebSockets yet. Something tells me that there must be plenty of plugins to do this. Do you use anything like that or write your own routines?
I ... | Do you use any client-side javascript library or jQuery plugin for WebSockets? | I need to deal with breaking connections and other standard things which are not handled by WebSockets yet. Something tells me that there must be plenty of plugins to do this. Do you use anything like that or write your own routines?
I need it for the client side, since I use Sinatra on the server side.
| [
"There are two common issues at hand: supporting older browsers that don't natively support WebSockets and automatic reconnect (in case of breaking connections).\nOlder browsers are supported by several vendors and products through emulation using different transports - what you need to look at is how good the emul... | [
1
] | [] | [] | [
"javascript",
"jquery",
"python",
"ruby",
"websocket"
] | stackoverflow_0008662272_javascript_jquery_python_ruby_websocket.txt |
Q:
Chained method calls indentation style in Python
From reading PEP-8, I get it that you should put the closing parenthesis on the same line as the last argument in function calls:
ShortName.objects.distinct().filter(
product__photo__stockitem__isnull=False)
Probably, long expressions are best to avoid at all. ... | Chained method calls indentation style in Python | From reading PEP-8, I get it that you should put the closing parenthesis on the same line as the last argument in function calls:
ShortName.objects.distinct().filter(
product__photo__stockitem__isnull=False)
Probably, long expressions are best to avoid at all. But if it's undesirable, how would you go about multip... | [
"This is a case where a line continuation character is preferred to open parentheses.\nShortName.objects.distinct() \\\n .filter().values() # looks better\n\nThe need for this style becomes more obvious as method names get longer and as methods start taking arguments:\nreturn some_collection.get_object... | [
245,
92
] | [] | [] | [
"coding_style",
"django",
"pep8",
"python"
] | stackoverflow_0008683178_coding_style_django_pep8_python.txt |
Q:
CSRF token missing or incorrect even though I have {% csrf_token %}
I have been getting this error referring to this method in my views.py file:
def AddNewUser(request):
a=AMI()
if(request.method == "POST"):
print(request.POST)
# print(request['newUser'])
# print(request['password'])
... | CSRF token missing or incorrect even though I have {% csrf_token %} | I have been getting this error referring to this method in my views.py file:
def AddNewUser(request):
a=AMI()
if(request.method == "POST"):
print(request.POST)
# print(request['newUser'])
# print(request['password'])
return render_to_response("ac/AddNewUser.html", {})
But my other fun... | [
"You have to use a RequestContext object to get the context, then pass the results in to your render_to_response() function. RequestContext adds in a required CSRF token.\nfrom django.template import RequestContext\nfrom django.shortcuts import render_to_response\n\ncsrfContext = RequestContext(request)\nreturn ren... | [
13,
2
] | [] | [] | [
"django",
"html",
"python"
] | stackoverflow_0005922773_django_html_python.txt |
Q:
Too Many Write Ops
I'm developing a directory app on app-engine (python) and I've run into trouble with too many write ops. The first issue is that I have a .NET script that goes through an excel file and posts the data to a page in my app. When I ran it, it got through around 700 records and I had already used 75... | Too Many Write Ops | I'm developing a directory app on app-engine (python) and I've run into trouble with too many write ops. The first issue is that I have a .NET script that goes through an excel file and posts the data to a page in my app. When I ran it, it got through around 700 records and I had already used 75% of my write ops quota.... | [
"Unless you target a property in a search (or use it for ordering), making them unindexed saves index writes. Each property is indexed twice (once ascending, once descending) unless either the property type is inherently unindexed, or you set indexed=False.\nSee http://code.google.com/appengine/docs/python/datastor... | [
3
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0008683035_google_app_engine_google_cloud_datastore_python.txt |
Q:
How this logging way can be corrected
My logging module: MyLog.py
import logging
class MyLogC(logging.Filterer):
def __init__(self):
self.myLogger = logging.getLogger('')
self.myLogger.setLevel(logging.DEBUG)
self.myLogFile = logging.FileHandler("./ex.log","w")
self.m... | How this logging way can be corrected | My logging module: MyLog.py
import logging
class MyLogC(logging.Filterer):
def __init__(self):
self.myLogger = logging.getLogger('')
self.myLogger.setLevel(logging.DEBUG)
self.myLogFile = logging.FileHandler("./ex.log","w")
self.myLogger.addHandler(self.myLogFile)
... | [
"You are expecting self.logger to be a logger instance, but currently MyLog.MyLogC is a class, and the MyLogger is a method on that class.\nTry self.logger = MyLog.MyLogC().MyLogger() (note the parens).\nThis first creates a MyLogC object, then invokes the MyLogger method on it to get the actual logger instance.\n"... | [
2
] | [] | [] | [
"logging",
"python"
] | stackoverflow_0008683594_logging_python.txt |
Q:
Understanding NLTK collocation scoring for bigrams and trigrams
Background:
I am trying to compare pairs of words to see which pair is "more likely to occur" in US English than another pair. My plan is/was to use the collocation facilities in NLTK to score word pairs, with the higher scoring pair being the most l... | Understanding NLTK collocation scoring for bigrams and trigrams | Background:
I am trying to compare pairs of words to see which pair is "more likely to occur" in US English than another pair. My plan is/was to use the collocation facilities in NLTK to score word pairs, with the higher scoring pair being the most likely.
Approach:
I coded the following in Python using NLTK (several ... | [
"The NLTK collocations document seems pretty good to me. http://www.nltk.org/howto/collocations.html\nYou need to give the scorer some actual sizable corpus to work with. Here is a working example using the Brown corpus built into NLTK. It takes about 30 seconds to run.\nimport nltk.collocations\nimport nltk.cor... | [
34
] | [] | [] | [
"nlp",
"nltk",
"python"
] | stackoverflow_0008683588_nlp_nltk_python.txt |
Q:
Split up SubElements in `for` loop using Python and XML
My code is nearly finished but I'm having trouble with splitting up the SubElements in my for loop (?) How can I get each element into its own within the xml root node?
import csv
import sys
from xml.etree import ElementTree
from xml.etree.ElementTree impor... | Split up SubElements in `for` loop using Python and XML | My code is nearly finished but I'm having trouble with splitting up the SubElements in my for loop (?) How can I get each element into its own within the xml root node?
import csv
import sys
from xml.etree import ElementTree
from xml.etree.ElementTree import Element, SubElement, Comment, tostring
from xml.dom import... | [
"Like this?\nimport csv\nimport sys\n\nfrom xml.etree import ElementTree\nfrom xml.etree.ElementTree import Element, SubElement, Comment, tostring\n\nfrom xml.dom import minidom\n\ndef prettify(doctype, elem):\n \"\"\"Return a pretty-printed XML string for the Element.\n \"\"\"\n rough_string = doctype + E... | [
2
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0008683777_python_xml.txt |
Q:
How to write a function to map points on a canvas to points on the real plane
I'm writing a simple Mandelbrot visualiser in Python onto a pygame Screen. For each pixel on the 600 by 600 Screen, I am plotting whether or not this pixel, (x, y) as a complex number, is in the Mandelbrot set or not.
The problem being t... | How to write a function to map points on a canvas to points on the real plane | I'm writing a simple Mandelbrot visualiser in Python onto a pygame Screen. For each pixel on the 600 by 600 Screen, I am plotting whether or not this pixel, (x, y) as a complex number, is in the Mandelbrot set or not.
The problem being that I start at (0, 0) and iterate through to (600, 600), most of which is outside t... | [
"You want a window for your data. You know it is 600 pixels wide and 600 pixels tall. The pixel coordinates are (0, 0) - (600, 600). You can do this:\nPoint coordFromPixelLocation (pixelX, pixelY, pixelWidth, pixelHeight, minCoordX, maxCoordX, minCoordY, maxCoordY)\n{\n xPercent = pixelX / pixelWidth;\n yPer... | [
2,
1,
1
] | [] | [] | [
"complex_numbers",
"fractals",
"pygame",
"python"
] | stackoverflow_0008683353_complex_numbers_fractals_pygame_python.txt |
Q:
Pythons subprocess with WSGI + Apache mpm-worker: IOError 4
I have a strange problem here which solution I can't figure out by searching the net :/
After switching Apache from mpm-prefork to mpm-worker, using subprocess in my (Django) Python WSGI application raises the following exception after hanging for a coupl... | Pythons subprocess with WSGI + Apache mpm-worker: IOError 4 | I have a strange problem here which solution I can't figure out by searching the net :/
After switching Apache from mpm-prefork to mpm-worker, using subprocess in my (Django) Python WSGI application raises the following exception after hanging for a couple of time:
IOError at /
[Errno 4] Interrupted system call
The ca... | [
"Python 2.7.2 has a bug in it which causes fork in sub interpreters to fail. Try setting:\nWSGIApplicationGroup %{GLOBAL}\n\nin Apache configuration for that WSGI application, to force use of main interpreter.\nThe Python bug report for the underlying issues is:\nhttp://bugs.python.org/issue13156\n"
] | [
0
] | [] | [] | [
"apache",
"python",
"subprocess",
"worker",
"wsgi"
] | stackoverflow_0008678897_apache_python_subprocess_worker_wsgi.txt |
Q:
Calculating combinations of length k from a list of length n using recursion
I need to generate all the combinations with length k from a list of length n, and I must do it using recursion.
For Example:
INPUT: choose_sets([1,2,3,4],3)
OUTPUT: [[1,2,3],[1,2,4],[1,3,4],[2,3,4]]
INPUT: choose_sets([1,2,3,4],2)
OUT... | Calculating combinations of length k from a list of length n using recursion | I need to generate all the combinations with length k from a list of length n, and I must do it using recursion.
For Example:
INPUT: choose_sets([1,2,3,4],3)
OUTPUT: [[1,2,3],[1,2,4],[1,3,4],[2,3,4]]
INPUT: choose_sets([1,2,3,4],2)
OUTPUT: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
I'm stuck implementing this in code, s... | [
"You can get solution from Generator for permutations, combinations, selections of a sequence (Python recipe)\ndef xuniqueCombinations(items, n):\n if n==0: yield []\n else:\n for i in xrange(len(items)):\n for cc in xuniqueCombinations(items[i+1:],n-1):\n yield [items[i]]+cc\... | [
7,
0,
0,
0,
0
] | [] | [] | [
"permutation",
"python",
"recursion"
] | stackoverflow_0008683092_permutation_python_recursion.txt |
Q:
how can i request an html page in an "HTTP request", and asking only for some regex or specific html tag in it?
is there any header or method in http protocol which allows you to get specific tag from an html resource for example i would like to get all the tag in this python request, instead of all the html page... | how can i request an html page in an "HTTP request", and asking only for some regex or specific html tag in it? | is there any header or method in http protocol which allows you to get specific tag from an html resource for example i would like to get all the tag in this python request, instead of all the html page. is there any thing i can do while setting the request which is supported by the http protocol 1.1v or 1.0v ?
import... | [
"No, you have to get the entire page. The HTTP protocol does not provide a means of downloading a partial page by HTML element.\n",
"Although you can't make such a request via http, you can use BeautifulSoup, a python module that will parse the html for you.\n",
"The HTTP headers let you specify that you want h... | [
1,
1,
1
] | [] | [] | [
"html",
"http",
"httpwebrequest",
"python"
] | stackoverflow_0008684051_html_http_httpwebrequest_python.txt |
Q:
How does sleekxmpp components work?
This may sound dumb but I followed this tutorial:
https://github.com/fritzy/SleekXMPP/wiki/Creating-a-SleekXMPP-Plugin
and here's the component at the end that uses the XEP-0077 plugin that was created:
import sleekxmpp.componentxmpp
class Example(sleekxmpp.componentxmpp.Compon... | How does sleekxmpp components work? | This may sound dumb but I followed this tutorial:
https://github.com/fritzy/SleekXMPP/wiki/Creating-a-SleekXMPP-Plugin
and here's the component at the end that uses the XEP-0077 plugin that was created:
import sleekxmpp.componentxmpp
class Example(sleekxmpp.componentxmpp.ComponentXMPP):
def __init__(self, jid, pa... | [
"Check out\nhttp://louizatakk.fedorapeople.org/sleekxmpp-1.0-Beta2-0/examples/config_component.py\nIt will answer all of your questions. If not, post a comment with with the follow-up questions below.\n"
] | [
1
] | [] | [] | [
"ejabberd",
"python",
"xmpp"
] | stackoverflow_0005174710_ejabberd_python_xmpp.txt |
Q:
Why does raw_input create an infinite loop in this Learn Python the Hard Way exercise variant?
I'm trying to work my way through Learn Python the Hard Way, and trying to mess around where I can to further my education. I thought this would work: set up raw_input to set a limit for a while loop, then let the while ... | Why does raw_input create an infinite loop in this Learn Python the Hard Way exercise variant? | I'm trying to work my way through Learn Python the Hard Way, and trying to mess around where I can to further my education. I thought this would work: set up raw_input to set a limit for a while loop, then let the while loop execute to the limit I establish with the variable "frequency".
It, uh, doesn't. Instead, it s... | [
"raw_input will give you a string object, not an integer. Try to make frequency = int(frequency) before the loop, it will make the comparison valuable.\n",
">>> 3 < '2'\n0: True\n\nThat's your hint.\n",
"Because raw_input results in a string.\n>>> frequency = \"10\"\n>>> i = 0\n>>> while i < frequency:\n... ... | [
6,
2,
1,
1
] | [] | [] | [
"python",
"while_loop"
] | stackoverflow_0008684502_python_while_loop.txt |
Q:
Write XML filename based of CSV cell Python
Trying to save output from this script to a file based on a cell within the csv. I am able to call the variable {file_root_name} to write into the xml file but not as a variable to write the file name. How can I use the variable file_root_name as a variable to generate a... | Write XML filename based of CSV cell Python | Trying to save output from this script to a file based on a cell within the csv. I am able to call the variable {file_root_name} to write into the xml file but not as a variable to write the file name. How can I use the variable file_root_name as a variable to generate a file name?
import csv
import sys
from xml.etree... | [
"I'm not sure that I follow, but if the line\n attrs = {'src': (\"mp4:soundcheck/{year}/{id}/{file_root_name}_{suffix}.mp4\"\n .format(suffix=str(suffix), **row)),\n 'system-bitrate': str(bitrate),\n }\n\nworks then \"file_root_name\" must be a st... | [
1
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0008684557_csv_python.txt |
Q:
Python ljust(): difference in console and Browser
kt = 'B'
urk = '1234567'
code = kt+urk.ljust(15)+'me'
In pycharm console code seems:
B1234567 me
But with printing code in django template as {{ code }} seems like B1234567 me .
How can I modify 'code' for seems like console.
Thanks in advance
A:
Use <pr... | Python ljust(): difference in console and Browser | kt = 'B'
urk = '1234567'
code = kt+urk.ljust(15)+'me'
In pycharm console code seems:
B1234567 me
But with printing code in django template as {{ code }} seems like B1234567 me .
How can I modify 'code' for seems like console.
Thanks in advance
| [
"Use <pre>{{ code }}</pre> for pre-formatted text.\n"
] | [
2
] | [] | [] | [
"django_templates",
"html",
"python"
] | stackoverflow_0008677850_django_templates_html_python.txt |
Q:
Using code generated by Py++ as a Python extension
I have a need to wrap an existing C++ library for use in Python. After reading through this answer on choosing an appropriate method to wrap C++ for use in Python, I decided to go with Py++.
I walked through the tutorial for Py++, using the tutorial files, and I g... | Using code generated by Py++ as a Python extension | I have a need to wrap an existing C++ library for use in Python. After reading through this answer on choosing an appropriate method to wrap C++ for use in Python, I decided to go with Py++.
I walked through the tutorial for Py++, using the tutorial files, and I got the expected output in generated.cpp, but I haven't f... | [
"Py++ generates you syntax you use along with boost::python to generate python entry points in your app.\nAssuming everything went well with Py++ you need to download the Boost framework, and add the boost include directory and the boost::python lib to your project then compile with the Py++ generated cpp.\nYou can... | [
6,
4,
1
] | [] | [] | [
"c++",
"py++",
"python",
"word_wrap"
] | stackoverflow_0002169948_c++_py++_python_word_wrap.txt |
Q:
Tkinter's mainloop() Calling Button Function Automatically
I'm pretty new to Tkinter but starting to try to put more complex GUI's in my scripts. So this must be pretty basic but I can't figure out what's going wrong.
What I want is pretty simple, a bunch of data entry options and at the bottom an exit and submit ... | Tkinter's mainloop() Calling Button Function Automatically | I'm pretty new to Tkinter but starting to try to put more complex GUI's in my scripts. So this must be pretty basic but I can't figure out what's going wrong.
What I want is pretty simple, a bunch of data entry options and at the bottom an exit and submit buttons. It seems though that mainloop() or something else keeps... | [
"Change\ncommand = root.destroy()\n\nto \ncommand = root.destroy\n\nThe reason is this: The parentheses call the method, and method arguments are evaluated before being passed to the method. This is why your program is exiting too early.\nWithout the parentheses, you are referencing the method as an object which ca... | [
3
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0008684601_python_tkinter.txt |
Q:
Is there any regular expression engine that does Just-In-Time compiling?
My Questions is
Is there any regular expression engine that does Just-In-Time compiling during regex pattern parsing and use when matching / replacing the texts? Or where can I learn JIT for i386 or x64 architecture?
Why I need it
I was recen... | Is there any regular expression engine that does Just-In-Time compiling? | My Questions is
Is there any regular expression engine that does Just-In-Time compiling during regex pattern parsing and use when matching / replacing the texts? Or where can I learn JIT for i386 or x64 architecture?
Why I need it
I was recently trying to benchmark Python’s built-in regex engine compared with normal C ... | [
"PCRE has a JIT compiler since 8.20. You can read about here: http://sljit.sourceforge.net/pcre.html\n",
"The only regex engine that I know that can compile regular expressions into executable code is the one in .NET when you pass RegexOptions.Compiled. That causes the Regex class to emit MSIL which can then be ... | [
5,
3,
2,
2,
2,
2,
2,
1,
1
] | [] | [] | [
"c",
"c++",
"jit",
"python",
"regex"
] | stackoverflow_0001769023_c_c++_jit_python_regex.txt |
Q:
Write file to directory based on variable in Python
The script will generate multiple files using the year and id variable. These files need to be placed into a folder matching year and id. How do I write them to the correct folders?
file_root_name = row["file_root_name"]
year = row["year"]
id = row["id"]
path = y... | Write file to directory based on variable in Python | The script will generate multiple files using the year and id variable. These files need to be placed into a folder matching year and id. How do I write them to the correct folders?
file_root_name = row["file_root_name"]
year = row["year"]
id = row["id"]
path = year+'-'+id
try:
os.makedirs(path)
except:
pass
ou... | [
"If I understand your question correctly, you want to do this:\nimport os.path\nfile_name = row['file_root_name']+'.smil'\nfull_path = os.path.join(path, file_name)\noutput = open(full_path, 'w')\n\nPlease note that it's not very common in Python to use the + operator for string concatenation. Although not in your ... | [
2
] | [] | [] | [
"filesystems",
"python"
] | stackoverflow_0008684933_filesystems_python.txt |
Q:
please explain lambda workings
Possible Duplicate:
What is a lambda and what is an example implementation?
Here is the code for a lambda (from Byte of Python):
def make_repeater(n):
return lambda s: s * n
twice = make_repeater(2)
print twice('word')
print twice(5)
The output is this:
wordword
10
Can some... | please explain lambda workings |
Possible Duplicate:
What is a lambda and what is an example implementation?
Here is the code for a lambda (from Byte of Python):
def make_repeater(n):
return lambda s: s * n
twice = make_repeater(2)
print twice('word')
print twice(5)
The output is this:
wordword
10
Can someone please explain how the lambda w... | [
"As Jake described already, your make_repeater returns another function with n being bound to 2 (this is called a closure). So your code is roughly equivalent to:\ntwice = lambda s: s * 2\n\nprint twice('word')\nprint twice(5)\n\nWhich is in turn roughly equivalent to:\ndef twice(s):\n return s * 2\n\nprint twic... | [
4,
1
] | [] | [] | [
"lambda",
"python"
] | stackoverflow_0008685071_lambda_python.txt |
Q:
Syntax-highlight Python in a vim fold line
I have found that code-folding helps me organize my files better. Thus, at the bottom of my ~/.vimrc, I enable vim code folding by default:
""Folding
set foldmethod=indent
set foldnestmax=2
nnoremap <space> za
vnoremap <space> zf
"set nofoldenable "set this to disab... | Syntax-highlight Python in a vim fold line | I have found that code-folding helps me organize my files better. Thus, at the bottom of my ~/.vimrc, I enable vim code folding by default:
""Folding
set foldmethod=indent
set foldnestmax=2
nnoremap <space> za
vnoremap <space> zf
"set nofoldenable "set this to disable folding on file open
This has the advantages... | [
"This question was asked previously and the answer was that it's not possible since the fold headline is not actually part of the file, thus never gets scanned by the highlighter. :(\n"
] | [
4
] | [] | [] | [
"folding",
"ide",
"python",
"syntax_highlighting",
"vim"
] | stackoverflow_0008655799_folding_ide_python_syntax_highlighting_vim.txt |
Q:
Django 1.1 - comments - 'render_comment_form' returns TemplateSyntaxError
I want to simply render a built-in comment form in a template, using Django's builtin commenting module, but this returns a TemplateSyntaxError Exception.
I need help debugging this error, please, because after googling and using the Django ... | Django 1.1 - comments - 'render_comment_form' returns TemplateSyntaxError | I want to simply render a built-in comment form in a template, using Django's builtin commenting module, but this returns a TemplateSyntaxError Exception.
I need help debugging this error, please, because after googling and using the Django API reference, I'm still not getting any farther.
Info:
This is the template '_... | [
"I had the same exact problem, render_comment_form template tag was triggering it.\nThe issue is certainly with your URL config, you had it set the same way i did:\n(r'^comments/$', include('django.contrib.comments.urls'))\n\nThe correct way is to remove the '$' after 'comments/':\n(r'^comments/', include('django.c... | [
6,
1,
1,
1
] | [] | [] | [
"django",
"django_comments",
"django_templates",
"exception",
"python"
] | stackoverflow_0001877940_django_django_comments_django_templates_exception_python.txt |
Q:
python/webapp2: Violating DRY all over the place in webform-based calculator ... how do I fix it?
I have a webform-based macroeconomics model here that takes parameters and inputs and solves a system of linear equations.
webapp2 handler:
class Islm(webapp2.RequestHandler):
def get(self):
a = self.reque... | python/webapp2: Violating DRY all over the place in webform-based calculator ... how do I fix it? | I have a webform-based macroeconomics model here that takes parameters and inputs and solves a system of linear equations.
webapp2 handler:
class Islm(webapp2.RequestHandler):
def get(self):
a = self.request.get('a')
b = self.request.get('b')
c = self.request.get('c')
d = self.reques... | [
"\nYou can start by making tuples of all of your inputs and outputs:\ninput_vars = ('a', 'b', 'c', 'd', 'A', 'G', 'T', 'M', 'P')\noutput_vars = ('Y', 'E', 'r')\n\nYou can also just leave template_values with a few values in it and populate the rest dynamically:\ntemplate_values = {\n 'url': url,\n 'url_linkte... | [
2
] | [] | [] | [
"dry",
"python",
"webapp2"
] | stackoverflow_0008685462_dry_python_webapp2.txt |
Q:
Very weird Python variable scope behaviour
I'm having a problem with Python 2.7 that is driving me insane.
I'm passing an array to some functions and altough that variable is suposed to be local, in the end the value of the variable inside main is changed.
I'm a bit new to Python, but this goes against any common ... | Very weird Python variable scope behaviour | I'm having a problem with Python 2.7 that is driving me insane.
I'm passing an array to some functions and altough that variable is suposed to be local, in the end the value of the variable inside main is changed.
I'm a bit new to Python, but this goes against any common sense I got.
Any ideas of what I'm doing wrong?
... | [
"The problem you are having is stemming from the fact that arrays and dictionaries in python are passed by reference. This means that instead of a fresh copy being created by the def and used locally you are getting a pointer to your array in memory...\nx = [1,2,3,4]\n\ndef mystery(someArray):\n someArray.appen... | [
2,
1,
0
] | [] | [] | [
"arrays",
"function",
"python",
"scope"
] | stackoverflow_0008685493_arrays_function_python_scope.txt |
Q:
Comparing 2 dates with python
I need to compare 2 dates with a IF, but for some strange (:P) reason, I can't do it.
My code
date1 = strftime("%Y-%m-%d")
d2 = os.path.getmtime('/tmp/file')
date2 = datetime.date.fromtimestamp(d2)
if date1 == date2 :
print 'same date'
else:
print 'different date'
I don't kno... | Comparing 2 dates with python | I need to compare 2 dates with a IF, but for some strange (:P) reason, I can't do it.
My code
date1 = strftime("%Y-%m-%d")
d2 = os.path.getmtime('/tmp/file')
date2 = datetime.date.fromtimestamp(d2)
if date1 == date2 :
print 'same date'
else:
print 'different date'
I don't know why, show with a print the same d... | [
"date1 is a string, and date2 is a datetime.date. Perhaps you meant date1 = datetime.date.today().\n",
"\ntime.strftime returns an object of type str (a \"string\")\ndatetime.date.fromtimestamp returns an object of type datetime.date\n\nSo date1 and date2 will be objects of different types.\nComparing to objects ... | [
5,
2
] | [] | [] | [
"datetimepicker",
"python"
] | stackoverflow_0008685604_datetimepicker_python.txt |
Q:
How do I run long term (infinite) Python processes?
I've recently started experimenting with using Python for web development. So far I've had some success using Apache with mod_wsgi and the Django web framework for Python 2.7. However I have run into some issues with having processes constantly running, updating ... | How do I run long term (infinite) Python processes? | I've recently started experimenting with using Python for web development. So far I've had some success using Apache with mod_wsgi and the Django web framework for Python 2.7. However I have run into some issues with having processes constantly running, updating information and such.
I have written a script I call "dae... | [
"I'll open by stating that this is one way to manage a long running process (LRP) -- not de facto by any stretch.\nIn my experience, the best possible product comes from concentrating on the specific problem you're dealing with, while delegating supporting tech to other libraries. In this case, I'm referring to the... | [
40,
3,
2
] | [] | [] | [
"apache",
"daemon",
"infinite_loop",
"python"
] | stackoverflow_0008685695_apache_daemon_infinite_loop_python.txt |
Q:
Exchange position of 2 array elements in Python
Is there any easy way to exchange the position of 2 elements - or better yet, n elements - in an array?
I came up with some code, but it looks quite ugly and the performance should be a bit bad:
chromo = [[1,2], [3,4], [5,6]]
gene1Pos = random.randrange(0, len(chrom... | Exchange position of 2 array elements in Python | Is there any easy way to exchange the position of 2 elements - or better yet, n elements - in an array?
I came up with some code, but it looks quite ugly and the performance should be a bit bad:
chromo = [[1,2], [3,4], [5,6]]
gene1Pos = random.randrange(0, len(chromo)-1, 1)
gene2Pos = random.randrange(0, len(chromo)-1... | [
"try\n>>> chromo[gene1Pos], chromo[gene2Pos] = chromo[gene2Pos], chromo[gene1Pos]\n\nSo you just need to make sure you have the right genXPos\n",
"Just combine the normal mechanism for swapping variables in Python with slicing/slice assignment.\n>>> a = [1, 2, 3, 4, 5]\n>>> a[2:3], a[4:5] = a[4:5], a[2:3]\n>>> a\... | [
6,
1
] | [
"There's nothing wrong with what you're doing. You can simplify it by removing one of the temp variables though. To swap a and b, all you need is this:\ntmp = a\na = b\nb = tmp\n\n"
] | [
-1
] | [
"arrays",
"python",
"random",
"shuffle"
] | stackoverflow_0008685842_arrays_python_random_shuffle.txt |
Q:
Python, hstack column numpy arrays (column vectors) of different types
I currently have a numpy multi-dimensional array (of type float) and a numpy column array (of type int). I want to combine the two into a mutli-dimensional numpy array.
import numpy
>> dates.shape
(1251,)
>> data.shape
(1251,10)
>> test = n... | Python, hstack column numpy arrays (column vectors) of different types | I currently have a numpy multi-dimensional array (of type float) and a numpy column array (of type int). I want to combine the two into a mutli-dimensional numpy array.
import numpy
>> dates.shape
(1251,)
>> data.shape
(1251,10)
>> test = numpy.hstack((dates, data))
ValueError: all the input arrays must have same n... | [
"import numpy as np\n\nnp.column_stack((dates, data))\n\nThe types are cast automatically to the most precise, so your int array will be converted to float.\n",
"The types don't matter, you should reshape dates to be (1251, 1) before using hstack.\nPs. The ints will be cast to float.\n",
"test = numpy.hstack((d... | [
11,
1,
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0008685994_numpy_python.txt |
Q:
Choosing the right database system for a Django web application
I am currently in the planning stages of building a simple Django web app (for learning proposes). Basically, teacher’s can login, input student grades, and then the students can login and view their grades. Each class has a group number.
Here is a te... | Choosing the right database system for a Django web application | I am currently in the planning stages of building a simple Django web app (for learning proposes). Basically, teacher’s can login, input student grades, and then the students can login and view their grades. Each class has a group number.
Here is a template of a user:
Username: Johny098
Password: Y98uj*?877!(
Name: Joh... | [
"For learning purposes I'd recommend SQLite: no setup, no background daemons running, everything is bundled with Python, it's SQL (so it maps well with Django ORM), and it's a very simple DBMS. In fact, some people use SQLite for prototyping and then switch to MySQL/PostgreSQL in production.\nAs for NoSQL, I would ... | [
6,
2,
0
] | [] | [] | [
"database",
"django",
"python"
] | stackoverflow_0008686112_database_django_python.txt |
Q:
Set global hotkey with Python 2.6
I wanna setup a global hotkey in python 2.6 that listens to the keyboard shortcut ctrl + D or ctrl+ alt+ D on windows, please help me
A:
Tim Golden's python/win32 site is a useful resource for win32 related programming in python. In particular, this example should help:
Catch ... | Set global hotkey with Python 2.6 | I wanna setup a global hotkey in python 2.6 that listens to the keyboard shortcut ctrl + D or ctrl+ alt+ D on windows, please help me
| [
"Tim Golden's python/win32 site is a useful resource for win32 related programming in python. In particular, this example should help:\n\nCatch system-wide hotkeys\n\n",
"I suggest pyhk. It allows for global wide hotkey registration in python and comes with examples and documentation. Pyhk builds on pyhook.\nHot... | [
9,
6,
3,
0
] | [] | [] | [
"hotkeys",
"keyboard",
"keyboard_shortcuts",
"python",
"wxpython"
] | stackoverflow_0003337973_hotkeys_keyboard_keyboard_shortcuts_python_wxpython.txt |
Q:
Remove XML Version Tag from ElementTree using Python
I've needed to manually add my xml version as a string so I need to remove the xml version generated by ElementTree. How do I remove the duplicate xml version node on line 3?
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE smil PUBLIC "-//W3C//DTD SMIL 2.0//EN"... | Remove XML Version Tag from ElementTree using Python | I've needed to manually add my xml version as a string so I need to remove the xml version generated by ElementTree. How do I remove the duplicate xml version node on line 3?
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE smil PUBLIC "-//W3C//DTD SMIL 2.0//EN" "http://www.w3.org/2001/SMIL20/SMIL20.dtd">
<?xml version... | [
"Keep the xml processing instruction generated by ElemenTtree, and insert a doctype node into the minidom document:\ndef prettify(elem, doctype=None):\n \"\"\"Return a pretty-printed XML string for the Element.\n \"\"\"\n rough_string = ElementTree.tostring(elem, 'utf-8')\n reparsed = minidom.parseStrin... | [
1
] | [] | [] | [
"elementtree",
"python",
"xml"
] | stackoverflow_0008685272_elementtree_python_xml.txt |
Q:
How to implement a submethod in a Python-class?
I appologize, if I didn't express my self clearly. What I want to do is this:
class someClass(object):
def aMethod(self, argument):
return some_data #for example a list or a more complex datastructure
def aMethod_max(self, argument):
var = sel... | How to implement a submethod in a Python-class? | I appologize, if I didn't express my self clearly. What I want to do is this:
class someClass(object):
def aMethod(self, argument):
return some_data #for example a list or a more complex datastructure
def aMethod_max(self, argument):
var = self.aMethod(argument)
#do someting with var
... | [
"Let's compare the existing solutions already given in your question (e.g. the ones you call \"complicated\" and \"inelegant\") with your proposed alternative.\nThe existing solutions mean you will be able to write:\nfoo.subMethod() # foo.someMethod() is called internally\n\nbut your proposed alternative means you ... | [
3,
1,
1,
1,
0
] | [] | [] | [
"class",
"methods",
"python"
] | stackoverflow_0008685054_class_methods_python.txt |
Q:
How to display value on pygame window?
I'm trying to get my game to open a separate window that displays the players score after the quit out of the main game. I can't figure out how to have the text display the value of s + s2. So far i have:
import pygame, sys
from pygame.locals import *
pygame.init()
import tim... | How to display value on pygame window? | I'm trying to get my game to open a separate window that displays the players score after the quit out of the main game. I can't figure out how to have the text display the value of s + s2. So far i have:
import pygame, sys
from pygame.locals import *
pygame.init()
import time
red = (255,0,0)
green = (0,255,0)
blue = ... | [
"Pygame cannot open multiple windows at the same time. This is because of the design of the underlying SDL library.\nYour best bet is to dedicate some corner of the main window as the \"HUD\" which displays this information.\nDevelopment versions of SDL do support multiple windows (SDL 1.3) and there are developmen... | [
2
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0008685254_pygame_python.txt |
Q:
Converting a Python regular expression to C#
I have this regular expression in python:
'<input type="hidden" name="GALX" value="(?P<galx>[a-zA-Z0-9_]+)">'
I want an equivalent regular expression string for C#. This string gives a parsing error in c#. Thanks in advance.
I've tried this:
Regex rc = new Regex("<... | Converting a Python regular expression to C# | I have this regular expression in python:
'<input type="hidden" name="GALX" value="(?P<galx>[a-zA-Z0-9_]+)">'
I want an equivalent regular expression string for C#. This string gives a parsing error in c#. Thanks in advance.
I've tried this:
Regex rc = new Regex("<input type=\"hidden\" name=\"GALX\" value=\"(?P<ga... | [
"If you remove the \"P\" so that the \"<\" is right after the \"?\" it parses fine.\nNote .NET grouping syntax.\n"
] | [
0
] | [] | [] | [
"c#",
"python",
"regex"
] | stackoverflow_0008686761_c#_python_regex.txt |
Q:
How to create every permutation of a character set in every order -Python
I'm very new to python (just started yesterday), and I'm trying to create permutations of a character set e.g. ascii_lowercase for use in a crypto program. I'm currently using the following:
...function definitions etc
while i <= num:
for ... | How to create every permutation of a character set in every order -Python | I'm very new to python (just started yesterday), and I'm trying to create permutations of a character set e.g. ascii_lowercase for use in a crypto program. I'm currently using the following:
...function definitions etc
while i <= num:
for k in itertools.combinations_with_replacement(charset, i):
nhash = str(''.jo... | [
"Its seems you need itertools.product rather than itertools.combinations_with_replacement\nAnd here is the implementation with itertools.product\ncharset='ABC'\nprint '\\n'.join(''.join(p) for i in xrange(1,len(charset)+1) \n for p in itertools.product(charset, repeat=i))\n\nA\nB\nC\nAA\nAB\nAC\nBA\n... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0008686708_python.txt |
Q:
How to define category in yapsy plugin?
I use yapsy in this struct:
script.py
plugins
|-equipments
| |-eq1.py
| |-eq1.yapsy-plugin
|-tasks
|-tsk1.py
|-tsk1.yapsy-plugin
script.py
from yapsy.PluginManager import PluginManager
# Load the plugins from the plugin directory.
manager = PluginManager()
mana... | How to define category in yapsy plugin? | I use yapsy in this struct:
script.py
plugins
|-equipments
| |-eq1.py
| |-eq1.yapsy-plugin
|-tasks
|-tsk1.py
|-tsk1.yapsy-plugin
script.py
from yapsy.PluginManager import PluginManager
# Load the plugins from the plugin directory.
manager = PluginManager()
manager.setPluginPlaces(["plugins"])
manager.coll... | [
"Categories in yapsy are not detected by directories but via the class inherited by each plugin instance.\nFor instance, with your application, you could have your \"equipment\" plugins inherit an IEquipementPlugin class, and your \"task\" plugins inherit an ITaskPlugin .\nThen, when configuring your plugin manager... | [
2
] | [] | [] | [
"plugins",
"python"
] | stackoverflow_0008642146_plugins_python.txt |
Q:
What are the Python networking alternatives for this example?
I have an environment with up to 10 workstations and one server all sitting in the same physical location. They will be running some proprietary Python scripts that will need to talk to each other:
server script on server with client scripts on worksta... | What are the Python networking alternatives for this example? | I have an environment with up to 10 workstations and one server all sitting in the same physical location. They will be running some proprietary Python scripts that will need to talk to each other:
server script on server with client scripts on workstations;
server script on workstation with client scripts on other wo... | [
"I would look into RabbitMQ (www.rabbitmq.com). This would allow you to setup your server as a RabbitMQ messaging server and use the message queue protocol to communicate between your servers and workstations. The biggest advantage here is you don't really have to worry about the networking at all.\nOtherwise, I ... | [
2
] | [] | [] | [
"networking",
"python"
] | stackoverflow_0008687111_networking_python.txt |
Q:
What is the benefit of having many different data types?
What is the benefit of using many different data types in a language? I have been working with pyqt and pyqwt recently and I keep finding myself typing lines like this:
grid.setPen(Qt.QPen(Qt.Qt.gray, 0, Qt.Qt.DotLine))
curve.setSymbol(Qwt.QwtSymbol(Qwt.QwtS... | What is the benefit of having many different data types? | What is the benefit of using many different data types in a language? I have been working with pyqt and pyqwt recently and I keep finding myself typing lines like this:
grid.setPen(Qt.QPen(Qt.Qt.gray, 0, Qt.Qt.DotLine))
curve.setSymbol(Qwt.QwtSymbol(Qwt.QwtSymbol.Ellipse,
Qt.QBrush(),
... | [
"There are a few benefits:\n\nType safe languages (like C++) have the advantage that many errors are found at compile time (as opposed to run-time). That means using Qt.grey (note the e) would fail to compile because the type is not defined.\nBetter performance and less memory. Behind the scenes Qt.gray is a number... | [
4,
3,
1,
1,
0
] | [] | [] | [
"pyqt",
"python",
"qwt",
"types"
] | stackoverflow_0008687248_pyqt_python_qwt_types.txt |
Q:
How to replace two things at once in a string?
Say I have a string, "ab".
I want to replace "a" with "b" and "b" with "a" in one swoop.
So in the end, the string should be "ba" and not "aa" or "bb" and not use more than one line. Is this doable?
A:
When you need to swap variables, say x and y, a common pattern i... | How to replace two things at once in a string? | Say I have a string, "ab".
I want to replace "a" with "b" and "b" with "a" in one swoop.
So in the end, the string should be "ba" and not "aa" or "bb" and not use more than one line. Is this doable?
| [
"When you need to swap variables, say x and y, a common pattern is to introduce a temporary variable t to help with the swap: t = x; x = y; y = t.\nThe same pattern can also be used with strings:\n>>> # swap a with b\n>>> 'obama'.replace('a', '%temp%').replace('b', 'a').replace('%temp%', 'b')\n'oabmb'\n\nThis tech... | [
50,
26,
7,
2,
2,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0008687018_python_string.txt |
Q:
Append or remove some text in a file at a specific line in Python
I want to edit an Apache2 config file within a python script. I want to add or remove a domain name to the ServerAlias directive so the script needs to edit a specific file and search for a line that starts with "ServerAlias" and append or remove a ... | Append or remove some text in a file at a specific line in Python | I want to edit an Apache2 config file within a python script. I want to add or remove a domain name to the ServerAlias directive so the script needs to edit a specific file and search for a line that starts with "ServerAlias" and append or remove a specific domain name to that line.
I'm not sure how to do it, any hint ... | [
"you can use fileinput.input with inplace mode:\nimport fileinput\n\nfor line in fileinput.input(\"mifile\", inplace=True):\n if line.startswith(\"ServerAlias\"):\n line = doherewhatyouwant(line)\n print line,\n\nfrom docs:\n\nif the keyword argument inplace=True is passed to fileinput.input() or\n to... | [
1,
0
] | [] | [] | [
"file",
"python",
"text",
"unix"
] | stackoverflow_0008686941_file_python_text_unix.txt |
Q:
How do you pass in the username from the login page and make it appear on the sidebar
I'm trying to incorporate the user userID on the sidebar.
So the sidebar will show "Welcome username"
I've tried the cookie method but it doesn't seem to work.
This is my cookie receiving my username:
def login_user(request):
... | How do you pass in the username from the login page and make it appear on the sidebar | I'm trying to incorporate the user userID on the sidebar.
So the sidebar will show "Welcome username"
I've tried the cookie method but it doesn't seem to work.
This is my cookie receiving my username:
def login_user(request):
state = "Please log in below..."
username = password = ''
if request.POST:
... | [
"Why so complicated? \nYou can check if user is logged in directly in template:\n{% if user.is_authenticated %}\n Hello {{ user.username }}\n{% else %}\n Please log in\n{% endif %}\n\nAnd check that in settings.py in TEMPLATE_CONTEXT_PROCESSORS have 'django.contrib.auth.context_processors.auth'. Here is some d... | [
6
] | [] | [] | [
"django",
"html",
"python"
] | stackoverflow_0008687507_django_html_python.txt |
Q:
How to use 2 different change_list.html for 2 applications in the same django project
I have 2 applications in the django project. I want to add different widgets in the change_list.html for the 2 different applications. In settings.py, after adding the change_list.html in the admin directory of the templates in b... | How to use 2 different change_list.html for 2 applications in the same django project | I have 2 applications in the django project. I want to add different widgets in the change_list.html for the 2 different applications. In settings.py, after adding the change_list.html in the admin directory of the templates in both the applications respectively as,
TEMPLATE_DIRS = (
"/home/path/project/application1/t... | [
"Read the section on overriding admin templates: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#overriding-admin-templates (more specifically https://docs.djangoproject.com/en/dev/ref/contrib/admin/#templates-which-may-be-overridden-per-app-or-model)\nPlace your change_list.html in admin/application1 in o... | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008686362_django_python.txt |
Q:
How to write a tuple of tuples to a CSV file using Python
I have a tuple of tuples
import csv
A = (('Max', 3 ,' M'),('bob',5,'M'),('jane',6,'F'))
result = open("newfile.csv",'wb')
writer = csv.writer(result, dialect = 'excel')
writer.writerow(A)
result.close
This writes a CSV file with rows with A[0], A[1] and A[... | How to write a tuple of tuples to a CSV file using Python | I have a tuple of tuples
import csv
A = (('Max', 3 ,' M'),('bob',5,'M'),('jane',6,'F'))
result = open("newfile.csv",'wb')
writer = csv.writer(result, dialect = 'excel')
writer.writerow(A)
result.close
This writes a CSV file with rows with A[0], A[1] and A[2] .
What i want is a row with name, age and gender , which ha... | [
"Write all rows at once:\nwriter.writerows(A)\n\ninstead of\nwriter.writerow(A)\n\nFile newfile.csv looks now like this:\nMax,3, M\nbob,5,M\njane,6,F\n\nAlso, add () to your last line, it is a function call: result.close().\nIf you are on Python 2.6 or newer, you can use this form:\nimport csv\nA = (('Max', 3, 'M')... | [
11,
0
] | [] | [] | [
"csv",
"python",
"tuples"
] | stackoverflow_0008687568_csv_python_tuples.txt |
Q:
Allocate items according to an approximate ratio in Python
See update below...
I'm writing a Python simulation that assigns an arbitrary number of imaginary players one goal from an arbitrary pool of goals. The goals have two different levels or proportions of scarcity, prop_high and prop_low, at approximately a 3... | Allocate items according to an approximate ratio in Python | See update below...
I'm writing a Python simulation that assigns an arbitrary number of imaginary players one goal from an arbitrary pool of goals. The goals have two different levels or proportions of scarcity, prop_high and prop_low, at approximately a 3:1 ratio.
For example, if there are 16 players and 4 goals, or ... | [
"Some time ago (okay, two and a half years) I asked a question that I think would be relevant here. Here's how I think you could use this: first, build a list of the priorities assigned to each goal. In your example, where the first half of the goal pool (rounded down) gets priority 3 and the rest get priority 1, o... | [
3,
3
] | [] | [] | [
"algorithm",
"python"
] | stackoverflow_0008685308_algorithm_python.txt |
Q:
PyQt:How do I display a image properly?
I want to display an image in pyqt so,i used a label and the pixmap option,and the scaledContents but the image is distorted.Should I use another widget or do something else? Thanks.
This is the code:
from PyQt4 import QtCore, QtGui
self.label.setPixmap(QtGui.QPixmap(_fromUt... | PyQt:How do I display a image properly? | I want to display an image in pyqt so,i used a label and the pixmap option,and the scaledContents but the image is distorted.Should I use another widget or do something else? Thanks.
This is the code:
from PyQt4 import QtCore, QtGui
self.label.setPixmap(QtGui.QPixmap(_fromUtf8('image.jpg')))
self.label.setScaledContent... | [
"Use the scaled(const QSize, Qt::AspectRatioMode, Qt::TransformationMode) method of the pixmap, it has an option Qt::KeepAspectRatio that does not deform the image. The default is to ignore the aspect ratio\nAlso, note that the scaled method returns the scaled pixmap, so it must be used this way:\nmyPixmap = QtGui.... | [
14,
0
] | [] | [] | [
"pyqt",
"python"
] | stackoverflow_0008687723_pyqt_python.txt |
Q:
Circular referenced objects not getting garbage collected
I have a small handy class that I use a lot in my code which is the following:
class Structure(dict):
def __init__(self, **kwargs):
dict.__init__(self, **kwargs)
self.__dict__ = self
The nice thing about it is that you can either access... | Circular referenced objects not getting garbage collected | I have a small handy class that I use a lot in my code which is the following:
class Structure(dict):
def __init__(self, **kwargs):
dict.__init__(self, **kwargs)
self.__dict__ = self
The nice thing about it is that you can either access the attributes using dictionary key syntax or usual object sty... | [
"You can more straightforwardly implement your Structure class by using __getattr__ and __setattr__ to allow attribute access to go to the underlying dict.\nclass Structure(dict):\n def __getattr__(self, k):\n return self[k]\n def __setattr__(self, k, v):\n self[k] = v\n\nCycles are garbage coll... | [
3
] | [] | [] | [
"garbage_collection",
"python"
] | stackoverflow_0008687904_garbage_collection_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.