prefix
stringclasses
1 value
input_text
stringlengths
19
27.3k
target_text
stringlengths
2
24.8k
QA
splitting tuples in python best practice have method in my python code that returns tuple row from sql query let us say it has three fields jobid label username for ease of passing it around between functions have been passing the entire tuple as variable called job eventually however want to get at the bits so have been using code like this jobid label username job have realised however that this is maintenance nightmare because now can never add new fields to the result set without breaking all of my existing code how should have written this here are my two best guesses jobid label username job job job but that does not scale nicely when you have fields or to convert the results from the sql query to dictionary straight away and pass that around do not have control over the fact that it starts life as tuple that is fixed for me
perhaps this is overkill for your case but would be tempted to create job class that takes the tuple as its constructor argument and has respective properties on it would then pass instances of this class around instead
QA
splitting tuples in python best practice have method in my python code that returns tuple row from sql query let us say it has three fields jobid label username for ease of passing it around between functions have been passing the entire tuple as variable called job eventually however want to get at the bits so have been using code like this jobid label username job have realised however that this is maintenance nightmare because now can never add new fields to the result set without breaking all of my existing code how should have written this here are my two best guesses jobid label username job job job but that does not scale nicely when you have fields or to convert the results from the sql query to dictionary straight away and pass that around do not have control over the fact that it starts life as tuple that is fixed for me
would use dictionary you can convert the tuple to dictionary this way values querycode keys jobid label username job dict keys values for in xrange len values this will first create an array jobid val label val username val and then convert that to dictionary if the result order or count changes you just need to change the list of keys to match the new result ps still fresh on python myself so there might be better ways off doing this
QA
is there python module for regex matching in zip files have over million text files compressed into zip files also have list of about model names of phones want to find out the number of times particular model was mentioned in the text files is there any python module which can do regex match on the files without unzipping it is there simple way to solve this problem without unzipping
is not it at least theoretically possible to read in the zip huffman coding and then translate the regexp into the huffman code might this be more efficient than first de compressing the data then running the regexp note know it would not be quite that simple you would also have to deal with other aspects of the zip coding file layout block structures back references but one imagines this could be fairly lightweight edit also note that it is probably much more sensible to just use the zipfile solution
QA
splitting tuples in python best practice have method in my python code that returns tuple row from sql query let us say it has three fields jobid label username for ease of passing it around between functions have been passing the entire tuple as variable called job eventually however want to get at the bits so have been using code like this jobid label username job have realised however that this is maintenance nightmare because now can never add new fields to the result set without breaking all of my existing code how should have written this here are my two best guesses jobid label username job job job but that does not scale nicely when you have fields or to convert the results from the sql query to dictionary straight away and pass that around do not have control over the fact that it starts life as tuple that is fixed for me
staale there is better way job dict zip keys values
QA
how do do monkeypatching in python have had to do some introspection in python and it was not pretty name sys getframe code name os path split name co filename name co firstlineno name co name to get something like foo py bar blah blah in our debugging output would ideally like to prepend anything to stderr with this sort of information is it possible to change the behaviour of print globally within python
the python inspect module makes this lot easier and cleaner
QA
standard way to open folder window in linux want to open folder window in the appropriate file manager from within cross platform windows mac linux python application on osx can open window in the finder with os system open foldername and on windows with os startfile foldername what about unix linux is there standard way to do this or do have to special case gnome kde etc and manually run the appropriate application nautilus konqueror etc this looks like something that could be specified by the freedesktop org folks python module similar to webbrowser would also be nice
this would probably have to be done manually or have as config item since there are many file managers that users may want to use providing way for command options as well there might be an function that launches the defaults for kde or gnome in their respective toolkits but have not had reason to look for them
QA
standard way to open folder window in linux want to open folder window in the appropriate file manager from within cross platform windows mac linux python application on osx can open window in the finder with os system open foldername and on windows with os startfile foldername what about unix linux is there standard way to do this or do have to special case gnome kde etc and manually run the appropriate application nautilus konqueror etc this looks like something that could be specified by the freedesktop org folks python module similar to webbrowser would also be nice
you are going to have to do this based on the running window manager osx and windows have defacto standard way because there is only one choice you should not need to specify the exact filemanager application though this should be possible to do through the wm know gnome does and it is important to do this in kde since there are two possible file managers konqueror dolphin that may be in use agree that this would be good thing for freedesktop org to standardize although doubt it will happen unless someone steps up and volunteers to do it edit was not aware of xdg open good to know
QA
standard way to open folder window in linux want to open folder window in the appropriate file manager from within cross platform windows mac linux python application on osx can open window in the finder with os system open foldername and on windows with os startfile foldername what about unix linux is there standard way to do this or do have to special case gnome kde etc and manually run the appropriate application nautilus konqueror etc this looks like something that could be specified by the freedesktop org folks python module similar to webbrowser would also be nice
os system xdg open foldername xdg open can be used for files urls also
QA
what is tuple useful for am learning python for class now and we just covered tuples as one of the data types read the wikipedia page on it but could not figure out where such data type would be useful in practice can have some examples perhaps in python where an immutable set of numbers would be needed how is this different from list
tuples are used whenever you want to return multiple results from function since they are immutable they can be used as keys for dictionary lists cannot
QA
what is tuple useful for am learning python for class now and we just covered tuples as one of the data types read the wikipedia page on it but could not figure out where such data type would be useful in practice can have some examples perhaps in python where an immutable set of numbers would be needed how is this different from list
find them useful when you always deal with two or more objects as set
QA
what is tuple useful for am learning python for class now and we just covered tuples as one of the data types read the wikipedia page on it but could not figure out where such data type would be useful in practice can have some examples perhaps in python where an immutable set of numbers would be needed how is this different from list
list can always replace tuple with respect to functionality except apparently as keys in dict however tuple can make things go faster the same is true for for example immutable strings in java when will you ever need to be unable to alter your strings never just read decent discussion on limiting what you can do in order to make better programs why why functional programming matters matters
QA
what is tuple useful for am learning python for class now and we just covered tuples as one of the data types read the wikipedia page on it but could not figure out where such data type would be useful in practice can have some examples perhaps in python where an immutable set of numbers would be needed how is this different from list
tuples make good dictionary keys when you need to combine more than one piece of data into your key and do not feel like making class for it bob hello hello en us hi there have used this feature primarily to create dictionary with keys that are coordinates of the vertices of mesh however in my particular case the exact comparison of the floats involved worked fine which might not always be true for your purposes in which case would probably convert your incoming floats to some kind of fixed point integer
QA
what is tuple useful for am learning python for class now and we just covered tuples as one of the data types read the wikipedia page on it but could not figure out where such data type would be useful in practice can have some examples perhaps in python where an immutable set of numbers would be needed how is this different from list
tuple is useful for storing multiple values as you note tuple is just like list that is immutable once created you cannot add remove swap elements one benefit of being immutable is that because the tuple is fixed size it allows the run time to perform certain optimizations this is particularly beneficial when tupple is used in the context of return value or parameter to function
QA
what is tuple useful for am learning python for class now and we just covered tuples as one of the data types read the wikipedia page on it but could not figure out where such data type would be useful in practice can have some examples perhaps in python where an immutable set of numbers would be needed how is this different from list
tuples and lists have the same uses in general immutable data types in general have many benefits mostly about concurrency issues so when you have lists that are not volatile in nature and you need to guarantee that no consumer is altering it you may use tuple typical examples are fixed data in an application like company divisions categories etc if this data change typically single producer rebuilts the tuple
QA
best way to extract text from word doc without using com automation is there reasonable way to extract plain text from word file that does not depend on com automation this is feature for web app deployed on non windows platform that is non negotiable in this case antiword seems like it might be reasonable option but it seems like it might be abandoned python solution would be ideal but does not appear to be available
open office has an api
QA
best way to extract text from word doc without using com automation is there reasonable way to extract plain text from word file that does not depend on com automation this is feature for web app deployed on non windows platform that is non negotiable in this case antiword seems like it might be reasonable option but it seems like it might be abandoned python solution would be ideal but does not appear to be available
if it is word docx you could unzip it and parse the xml files that are contained inside
QA
python deployment and usr bin env portability at the beginning of all my executable python scripts put the shebang line usr bin env python am running these scripts on system where env python yields python environment my scripts quickly fail because have manual check for compatible python version if sys version info raise importerror cannot run with python version do not want to have to change the shebang line on every executable file if it is possible however do not have administrative access to the machine to change the result of env python and do not want to force particular version as in usr bin env python would like to avoid this because system may have newer version than python or may have python but no python what is the elegant solution edit was not specific enough in posing the question would like to let users execute the scripts without manual configuration path alteration or symlinking in bin and ensuring your path has bin before the python path maybe some distribution utility is required to prevent the manual tweaks
pretty hackish solution if your check fails use this function which probably could be significantly improved to determine the best interpreter available determine if it is acceptable and if so relaunch your script with os system or something similar and your sys argv using the new interpreter import os import glob def best python plist for in os getenv path split for in glob glob os path join python plist append os path join plist sort plist reverse if len plist return none return plist
QA
python re sub multiline caret match the python docs say re multiline when specified the pattern character matches at the beginning of the string and at the beginning of each line immediately following each newline by default matches only at the beginning of the string so what is going on when get the following unexpected result import re the quick brown fox jumped over the lazy dog re sub re multiline the quick brown fox jumped over the lazy dog
look at the definition of re sub sub pattern repl string count the th argument is the count you are using re multiline which is as the count not as flag you have to compile your regex if you wish to use flags re sub re compile re multiline flags argument was added in python so the full definition is now re sub pattern repl string count flags which means that re sub flags re multiline works
QA
where can learn more about pypy translation function have been having hard time trying to understand pypy translation it looks like something absolutely revolutionary from simply reading the description however am hard pressed to find good documentation on actually translating real world piece of code to something such as llvm does such thing exist the official pypy documentation on it just skims over the functionality rather than providing anything can try out myself
this document seems to go into quite bit of detail and think complete description is out of scope for stackoverflow answer http codespeak net pypy dist pypy doc translation html the general idea of translating from one language to another is not particularly revolutionary but it has only recently been gaining popularity applicability in real world applications gwt does this with java generating javascript and there is library for translating haskell into various other languages as well called yhc
QA
python deployment and usr bin env portability at the beginning of all my executable python scripts put the shebang line usr bin env python am running these scripts on system where env python yields python environment my scripts quickly fail because have manual check for compatible python version if sys version info raise importerror cannot run with python version do not want to have to change the shebang line on every executable file if it is possible however do not have administrative access to the machine to change the result of env python and do not want to force particular version as in usr bin env python would like to avoid this because system may have newer version than python or may have python but no python what is the elegant solution edit was not specific enough in posing the question would like to let users execute the scripts without manual configuration path alteration or symlinking in bin and ensuring your path has bin before the python path maybe some distribution utility is required to prevent the manual tweaks
morais that is an interesting idea but think maybe we can take it one step farther maybe there is way to use ian bicking virtualenv to see if we are running in an acceptable environment to begin with and if so do nothing check if there exists version specific executable on the path check if python exists for in reverse range if so re run the command with the better interpreter if no better interpreter exists use virtualenv to try and install newer version of python from the older version of python and get any prerequisite packages have no idea if virtualenv is capable of this so will go mess around with it sometime soon
QA
get last day of the month in python is there way using python standard library to easily determine one function call the last day of given month if the standard library does not support that does the dateutil package support this
edit see blair conrad answer for cleaner solution import datetime datetime date datetime timedelta days datetime date
QA
get last day of the month in python is there way using python standard library to easily determine one function call the last day of given month if the standard library does not support that does the dateutil package support this
edit see my other answer it has better implementation than this one which leave here just in case someone is interested in seeing how one might roll your own calculator john millikin gives good answer with the added complication of calculating the first day of the next month the following is not particularly elegant but to figure out the last day of the month that any given date lives in you could try def last day of month date if date month return date replace day return date replace month date month day datetime timedelta days last day of month datetime date datetime date last day of month datetime date datetime date last day of month datetime date datetime date
QA
how can get commit message from bzr post commit hook am trying to write bzr post commit hook for my private bugtracker but am stuck at the function signature of post commit local master old revno old revid new revno mew revid how can extract the commit message for the branch from this with bzrlib in python
and the answer is like so def check commit msg local master old revno old revid new revno new revid branch local or master revision branch repository get revision new revid print revision message local and master are branch objects so once you have revision it is easy to extract the message
QA
best way to extract text from word doc without using com automation is there reasonable way to extract plain text from word file that does not depend on com automation this is feature for web app deployed on non windows platform that is non negotiable in this case antiword seems like it might be reasonable option but it seems like it might be abandoned python solution would be ideal but does not appear to be available
using the openoffice api and python and andrew pitonyak excellent online macro book managed to do this section is the place to start one other tip to make it work without needing the screen at all is to use the hidden property ro propertyvalue readonly true hidden propertyvalue hidden true xdoc desktop loadcomponentfromurl docpath blank ro hidden otherwise the document flicks up on the screen probably on the webserver console when you open it
QA
how to generate urls in django in django template language you can use url viewname args to generate url to specific view with parameters how can you programatically do the same in python code what need is to create list of menu items where each item has name url and an active flag whether it is the current page or not this is because it will be lot cleaner to do this in python than the template language
if you need to use something similar to the url template tag in your code django provides the django core urlresolvers reverse the reverse function has the following signature reverse viewname urlconf none args none kwargs none https docs djangoproject com en dev ref urlresolvers
QA
can write native iphone apps using python using pyobjc you can use python to write cocoa applications for os can write native iphone apps using python and if so how
not currently currently the only languages available to access the iphone sdk are objective and swift there is no technical reason why this could not change in the future but would not hold your breath for this happening in the short term that said objective and swift really are not too scary edit javascript with nativescript framework is available to use now
QA
can write native iphone apps using python using pyobjc you can use python to write cocoa applications for os can write native iphone apps using python and if so how
you can use pyobjc on the iphone as well due to the excellent work by jay freeman saurik see iphone applications in python note that this requires jailbroken iphone at the moment
QA
best way to extract text from word doc without using com automation is there reasonable way to extract plain text from word file that does not depend on com automation this is feature for web app deployed on non windows platform that is non negotiable in this case antiword seems like it might be reasonable option but it seems like it might be abandoned python solution would be ideal but does not appear to be available
use catdoc or antiword for this whatever gives the result that is the easiest to parse have embedded this in python functions so it is easy to use from the parsing system which is written in python import os def doc to text catdoc filename fi fo fe os popen catdoc filename fi close retval fo read erroroutput fe read fo close fe close if not erroroutput return retval else raise oserror executing the command caused an error erroroutput similar doc to text antiword the switch to catdoc turns off line wrapping by the way
QA
python web application framework for tight db gui coupling am firm believer of the heretic thought of tight coupling between the backend and frontend want existing implied knowledge about backend to be automatically made use of when generating user interfaces if varchar column has maximum with of characters there guis should automatically constrain the user from typing more than characters in related form field and have strong antipathy to orms which want to define my database tables or are based on some hack where every table needs to have extra numeric id columns because of the orm have looked bit into python database frameworks and think can conclude the sqlalchemy fits best to my mentality now need to find web application framework which fits naturally with sqlalchemy or an equivalent and perhaps even with my appetite for coupling with web application framework mean products project such as pyhons django turbogears web py etc it should ideally be able to automatically select suitable form widget for data entering given column if told to do so if the column has foreign key to column with different values widget should display the possible values as dropdown auto generate javascript form validation code which gives the end user quick error feedback if string is entered into field which is about to end up in an integer column etc auto generate calendar widget for data which will end up in date column hint not null constraints as javascript which complains about empty or whitespace only data in related input field generate javascript validation code which matches relevant simple check constraints make it easy to avoid sql injection by using prepared statements and or validation of externally derived data make it easy to avoid cross site scripting by automatically escape outgoing strings when appropriate make use of constraint names to generate somewhat user friendly error messages in case constrataint is violated all this should happen dynamically so table adjustments are automatically reflected on the frontend probably with caching mechanism so that all the model introspection would not kill performance in other words do not want to repeat my model definition in an xml file or alike when it has already been carefully been defined in my database does such framework exist for python or for any language for that matter if not which of the several python web application frameworks will be least in the way if were to add parts of the above features myself
you should have look at django and especially its newforms and admin modules the newforms module provides nice possibility to do server side validation with automated generation of error messages pages for the user adding ajax validation is also possible
QA
python web application framework for tight db gui coupling am firm believer of the heretic thought of tight coupling between the backend and frontend want existing implied knowledge about backend to be automatically made use of when generating user interfaces if varchar column has maximum with of characters there guis should automatically constrain the user from typing more than characters in related form field and have strong antipathy to orms which want to define my database tables or are based on some hack where every table needs to have extra numeric id columns because of the orm have looked bit into python database frameworks and think can conclude the sqlalchemy fits best to my mentality now need to find web application framework which fits naturally with sqlalchemy or an equivalent and perhaps even with my appetite for coupling with web application framework mean products project such as pyhons django turbogears web py etc it should ideally be able to automatically select suitable form widget for data entering given column if told to do so if the column has foreign key to column with different values widget should display the possible values as dropdown auto generate javascript form validation code which gives the end user quick error feedback if string is entered into field which is about to end up in an integer column etc auto generate calendar widget for data which will end up in date column hint not null constraints as javascript which complains about empty or whitespace only data in related input field generate javascript validation code which matches relevant simple check constraints make it easy to avoid sql injection by using prepared statements and or validation of externally derived data make it easy to avoid cross site scripting by automatically escape outgoing strings when appropriate make use of constraint names to generate somewhat user friendly error messages in case constrataint is violated all this should happen dynamically so table adjustments are automatically reflected on the frontend probably with caching mechanism so that all the model introspection would not kill performance in other words do not want to repeat my model definition in an xml file or alike when it has already been carefully been defined in my database does such framework exist for python or for any language for that matter if not which of the several python web application frameworks will be least in the way if were to add parts of the above features myself
believe that django models does not support composite primary keys see documentation but perhaps you can use sqlalchemy in django google search indicates that you can have not used django so do not know suggest you take look at toscawidgets dbsprockets including dbmechanic catwalk catwalk is an application for turbogears that uses sqlobject not sqlalchemy also check out this blog post and screencast fastdata also uses sqlobject formalchemy rum do not have any deep knowledge of any of the projects above am just in the process of trying to add something similar to one of my own applications as what the original question mentions the above list is simply list of interesting projects that have stumbled across as to web application frameworks for python recommend turbogears not that have any experience with any of the other frameworks just like turbogears if the original question author finds solution that works well please update or answer this thread
QA
how to find the mime type of file in python let us say you want to save bunch of files somewhere for instance in blobs let us say you want to dish these files out via web page and have the client automatically open the correct application viewer assumption the browser figures out which application viewer to use by the mime type content type header in the http response based on that assumption in addition to the bytes of the file you also want to save the mime type how would you find the mime type of file am currently on mac but this should also work on windows does the browser add this information when posting the file to the web page is there neat python library for finding this information webservice or even better downloadable database
the mimetypes module in the standard library will determine guess the mime type from file extension if users are uploading files the http post will contain the mime type of the file alongside the data for example django makes this data available as an attribute of the uploadedfile object
QA
how to find the mime type of file in python let us say you want to save bunch of files somewhere for instance in blobs let us say you want to dish these files out via web page and have the client automatically open the correct application viewer assumption the browser figures out which application viewer to use by the mime type content type header in the http response based on that assumption in addition to the bytes of the file you also want to save the mime type how would you find the mime type of file am currently on mac but this should also work on windows does the browser add this information when posting the file to the web page is there neat python library for finding this information webservice or even better downloadable database
you did not state what web server you were using but apache has nice little module called mime magic which it uses to determine the type of file when told to do so it reads some of the file content and tries to figure out what type it is based on the characters found and as dave webb mentioned the mimetypes module under python will work provided an extension is handy alternatively if you are sitting on unix box you can use sys popen file filename mode to grab the mime type windows should have an equivalent command but am unsure as to what it is
QA
get last day of the month in python is there way using python standard library to easily determine one function call the last day of given month if the standard library does not support that does the dateutil package support this
did not notice this earlier when was looking at the documentation for the calendar module but method called monthrange provides this information monthrange year month returns weekday of first day of the month and number of days in month for the specified year and month import calendar calendar monthrange calendar monthrange calendar monthrange so calendar monthrange year month seems like the simplest way to go just to be clear monthrange supports leap years as well from calendar import monthrange monthrange my previous answer still works but is clearly suboptimal
QA
pros and cons of different approaches to web programming in python would like to do some server side scripting using python but am kind of lost with the number of ways to do that it starts with the do it yourself cgi approach and it seems to end with some pretty robust frameworks that would basically do all the job themselves and huge lot of stuff in between like web py pyroxide and django what are the pros and cons of the frameworks or approaches that you have worked on what trade offs are there for what kind of projects they do well and for what they do not edit have not got much experience with web programing yet would like to avoid the basic and tedious things like parsing the url for parameters etc on the other hand while the video of blog created in minutes with ruby on rails left me impressed realized that there were hundreds of things hidden from me which is cool if you need to write working webapp in no time but not that great for really understanding the magic and that is what seek now
if you have never done any cgi programming before think it would be worth doing one project perhaps just sample play site just for yourself using the diy approach you will learn lot more about how all the various parts work than you would by using framework this will help in you design and debug and so on all your future web applications however you write them personally now use django the real benefit is very fast application deployment the object relational mapping gets things moving fast and the template library is joy to use also the admin interface gives you basic crud screens for all your objects so you do not need to write any of the boring stuff the downside of using an orm based solution is that if you do want to handcraft some sql say for performance reasons it much harder than it would have been otherwise although still very possible
QA
pros and cons of different approaches to web programming in python would like to do some server side scripting using python but am kind of lost with the number of ways to do that it starts with the do it yourself cgi approach and it seems to end with some pretty robust frameworks that would basically do all the job themselves and huge lot of stuff in between like web py pyroxide and django what are the pros and cons of the frameworks or approaches that you have worked on what trade offs are there for what kind of projects they do well and for what they do not edit have not got much experience with web programing yet would like to avoid the basic and tedious things like parsing the url for parameters etc on the other hand while the video of blog created in minutes with ruby on rails left me impressed realized that there were hundreds of things hidden from me which is cool if you need to write working webapp in no time but not that great for really understanding the magic and that is what seek now
if you decide to go with framework that is wsgi based for instance turbogears would recommend you go through the excellent article another do it yourself framework by ian bicking in the article he builds simple web application framework from scratch also check out the video creating web framework with wsgi by kevin dangoor dangoor is the founder of the turbogears project
QA
pros and cons of different approaches to web programming in python would like to do some server side scripting using python but am kind of lost with the number of ways to do that it starts with the do it yourself cgi approach and it seems to end with some pretty robust frameworks that would basically do all the job themselves and huge lot of stuff in between like web py pyroxide and django what are the pros and cons of the frameworks or approaches that you have worked on what trade offs are there for what kind of projects they do well and for what they do not edit have not got much experience with web programing yet would like to avoid the basic and tedious things like parsing the url for parameters etc on the other hand while the video of blog created in minutes with ruby on rails left me impressed realized that there were hundreds of things hidden from me which is cool if you need to write working webapp in no time but not that great for really understanding the magic and that is what seek now
cgi is great for low traffic websites but it has some performance problems for anything else this is because every time request comes in the server starts the cgi application in its own process this is bad for two reasons starting and stopping process can take time and you cannot cache anything in memory you can go with fastcgi but would argue that you would be better off just writing straight wsgi app if you are going to go that route the way wsgi works really is not whole heck of lot different from cgi other than that your choices are for the most part how much you want the framework to do you can go with an all singing all dancing framework like django or pylons or you can go with mix and match approach use something like cherrypy for the http stuff sqlalchemy for the database stuff paste for deployment etc should also point out that most frameworks will also let you switch different components out for others so these two approaches are not necessarily mutually exclusive personally dislike frameworks that do too much magic for me and prefer the mix and match technique but have been told that am also completely insane how much web programming experience do you have if you are beginner say go with django if you are more experienced say to play around with the different approaches and techniques until you find the right one
QA
modulus operation with negatives values weird thing can you please tell me how much is according to my python interpreter is but do you have wise explanation for this have read that in some languages the result can be machine dependent but am not sure though
your python interpreter is correct one stupid way of calculating modulus is to subtract or add the modulus until the resulting value is between and modulus mod mod mod or in your case mod mod
QA
modulus operation with negatives values weird thing can you please tell me how much is according to my python interpreter is but do you have wise explanation for this have read that in some languages the result can be machine dependent but am not sure though
well divided by would be with remainder of do not believe that should be very platform dependent but have seen stranger things
QA
modulus operation with negatives values weird thing can you please tell me how much is according to my python interpreter is but do you have wise explanation for this have read that in some languages the result can be machine dependent but am not sure though
it is indeed in modular arithmetic modulus is simply the remainder of division and the remainder of divided by is
QA
modulus operation with negatives values weird thing can you please tell me how much is according to my python interpreter is but do you have wise explanation for this have read that in some languages the result can be machine dependent but am not sure though
the result of the modulus operation on negatives seems to be programming language dependent and here is listing http en wikipedia org wiki modulo operation
QA
modulus operation with negatives values weird thing can you please tell me how much is according to my python interpreter is but do you have wise explanation for this have read that in some languages the result can be machine dependent but am not sure though
well should be right should be because that is the next allowed digit going in the reverse direction it cannot be since that is out of range and following along by that logic must be the easiest way to think of how it will work is that you keep adding or subtracting until the number falls between inclusive and exclusive am not sure about machine dependence have never seen an implementation that was but cannot say it is never done
QA
modulus operation with negatives values weird thing can you please tell me how much is according to my python interpreter is but do you have wise explanation for this have read that in some languages the result can be machine dependent but am not sure though
by the way most programming languages would disagree with python and give the result depending on the interpretation of modulus this is correct however the most agreed upon mathematical definition states that the modulus of and is the strictly positive rest of the division of more precisely are by definition
QA
modulus operation with negatives values weird thing can you please tell me how much is according to my python interpreter is but do you have wise explanation for this have read that in some languages the result can be machine dependent but am not sure though
the result depends on the language python returns the sign of the divisor where for example returns the sign of the dividend ie returns in
QA
pros and cons of different approaches to web programming in python would like to do some server side scripting using python but am kind of lost with the number of ways to do that it starts with the do it yourself cgi approach and it seems to end with some pretty robust frameworks that would basically do all the job themselves and huge lot of stuff in between like web py pyroxide and django what are the pros and cons of the frameworks or approaches that you have worked on what trade offs are there for what kind of projects they do well and for what they do not edit have not got much experience with web programing yet would like to avoid the basic and tedious things like parsing the url for parameters etc on the other hand while the video of blog created in minutes with ruby on rails left me impressed realized that there were hundreds of things hidden from me which is cool if you need to write working webapp in no time but not that great for really understanding the magic and that is what seek now
the simplest web program is cgi script which is basically just program whose standard output is redirected to the web browser making the request in this approach every page has its own executable file which must be loaded and parsed on every request this makes it really simple to get something up and running but scales badly both in terms of performance and organization so when need very dynamic page very quickly that will not grow into larger system use cgi script one step up from this is embedding your python code in your html code such as with psp do not think many people use this nowadays since modern template systems have made this pretty obsolete worked with psp for awhile and found that it had basically the same organizational limits as cgi scripts every page has its own file plus some whitespace related annoyances from trying to mix whitespace ignorant html with whitespace sensitive python the next step up is very simple web frameworks such as web py which have also used like cgi scripts it is very simple to get something up and running and you do not need any complex configuration or automatically generated code your own code will be pretty simple to understand so you can see what is happening however it is not as feature rich as other web frameworks last time used it there was no session tracking so had to roll my own it also has too much magic behavior to quote guido upvars bah finally you have feature rich web frameworks such as django these will require bit of work to get simple hello world programs working but every major one has great well written tutorial especially django to walk you through it highly recommend using one of these web frameworks for any real project because of the convenience and features and documentation etc ultimately you will have to decide what you prefer for example frameworks all use template languages special code tags to generate html files some of them such as cheetah templates let you write arbitrary python code so that you can do anything in template others such as django templates are more restrictive and force you to separate your presentation code from your program logic it is all about what you personally prefer another example is url handling some frameworks such as django have you define the urls in your application through regular expressions others such as cherrypy automatically map your functions to urls by your function names again this is personal preference personally use mix of web frameworks by using cherrypy for my web server stuff form parameters session handling url mapping etc and django for my object relational mapping and templates my recommendation is to start with high level web framework work your way through its tutorial then start on small personal project have done this with all of the technologies have mentioned and it is been really beneficial eventually you will get feel for what you prefer and become better web programmer and better programmer in general in the process
QA
modulus operation with negatives values weird thing can you please tell me how much is according to my python interpreter is but do you have wise explanation for this have read that in some languages the result can be machine dependent but am not sure though
one explanation might be that negative numbers are stored using complement when the python interpreter tries to do the modulo operation it converts to unsigned value as such instead of doing it actually computes xffff ffff ffff fffd which is
QA
modulus operation with negatives values weird thing can you please tell me how much is according to my python interpreter is but do you have wise explanation for this have read that in some languages the result can be machine dependent but am not sure though
as explained in other answers there are many choices for modulo operation with negative values in general different languages and different machine architectures will give different result according to the python reference manual the modulo operator always yields result with the same sign as its second operand or zero the absolute value of the result is strictly smaller than the absolute value of the second operand is the choice taken by python basically modulo is defined so that this always holds so it makes sense that
QA
modulus operation with negatives values weird thing can you please tell me how much is according to my python interpreter is but do you have wise explanation for this have read that in some languages the result can be machine dependent but am not sure though
be careful not to rely on this mod behavior in on all oses and architectures if recall correctly tried to rely on code like float to keep in the range from to but negative numbers crept in when would compile on one os but things would work fine on another os this made for an evil time debugging since it only happened half the time
QA
how do document module in python that is it if you want to document function or class you put string just after the definition for instance def foo this function does nothing pass but what about module how can document what file py does
it is easy you just add docstring at the top of the module
QA
how do document module in python that is it if you want to document function or class you put string just after the definition for instance def foo this function does nothing pass but what about module how can document what file py does
for the packages you can document it in init py for the modules you can add docstring simply in the module file all the information is here http www python org dev peps pep
QA
how do document module in python that is it if you want to document function or class you put string just after the definition for instance def foo this function does nothing pass but what about module how can document what file py does
you do it the exact same way put string in as the first statement in the module
QA
iterate over subclasses of given class in given module in python given module and class how can iterate or generate list of all subclasses of that exist in module
here is one way to do it import inspect def get subclasses mod cls yield the classes in module mod that inherit from cls for name obj in inspect getmembers mod if hasattr obj bases and cls in obj bases yield obj
QA
iterate over subclasses of given class in given module in python given module and class how can iterate or generate list of all subclasses of that exist in module
given the module foo py class foo object pass class bar foo pass class baz foo pass class grar exception pass def find subclasses module clazz for name in dir module getattr module name try if issubclass clazz yield name except typeerror pass import foo list foo find subclasses foo foo foo bar class foo bar baz class foo baz foo class foo foo list foo find subclasses foo object bar class foo bar baz class foo baz foo class foo foo grar class foo grar list foo find subclasses foo exception grar class foo grar
QA
how to merge two python dictionaries in single expression have two python dictionaries and want to write single expression that returns these two dictionaries merged the update method would be what need if it returned its result instead of modifying dict in place update print none how can get that final merged dict in not to be extra clear the last one wins conflict handling of dict update is what am looking for as well
wanted something similar but with the ability to specify how the values on duplicate keys were merged so hacked this out but did not heavily test it obviously this is not single expression but it is single function call def merge merge fn lambda merges two dictionaries non destructively combining values on duplicate keys as defined by the optional merge function the default behavior replaces the values in with corresponding values in there is no other generally applicable merge strategy but often you will have homogeneous types in your dicts so specifying merge technique can be valuable examples merge merge lambda result dict for in iteritems if in result result merge fn result else result return result
QA
pros and cons of different approaches to web programming in python would like to do some server side scripting using python but am kind of lost with the number of ways to do that it starts with the do it yourself cgi approach and it seems to end with some pretty robust frameworks that would basically do all the job themselves and huge lot of stuff in between like web py pyroxide and django what are the pros and cons of the frameworks or approaches that you have worked on what trade offs are there for what kind of projects they do well and for what they do not edit have not got much experience with web programing yet would like to avoid the basic and tedious things like parsing the url for parameters etc on the other hand while the video of blog created in minutes with ruby on rails left me impressed realized that there were hundreds of things hidden from me which is cool if you need to write working webapp in no time but not that great for really understanding the magic and that is what seek now
ok rails is actually pretty good but there is just little bit too much magic going on in there from the ruby world would much prefer merb to rails personally use pylons and am pretty darn happy would say compared to django that pylons allows you to interchange ints internal parts easier than django does the downside is that you will have to write more stuff all by youself like the basic crud pros of using framework get stuff done quickly and mean lighning fast once you know the framework everything is compying to standards which is probably not that easy to achieve when rolling your own easier to get something working lots of tutorials without reading gazillion articles and docs cons you learn less harder to replace parts not that much of an issue in pylons more so with django harder to tweak some low level stuff like the above mentioned sqls from that you can probably devise what they are good for since you get all the code it is possible to tweak it to fit even the most bizzare situations pylons supposedly work on the google app engine now
QA
how would you make comma separated string from list what would be your preferred way to concatenate strings from sequence such that between each two consecutive pair comma is added that is how do you map for instance to the cases and should be mapped to and respectively usually end up using something like join map lambda but also feeling somewhat unsatisfied edit am both ashamed and happy that the solution is so simple obviously have hardly clue as to what am doing probably needed simple concatenation in the past and somehow memorised join as shorthand for
mylist would mystring join mylist this will not work if the list contains numbers as ricardo reyes suggested if it contains non string types such as integers floats bools none then do mylist join map str mylist
QA
how would you make comma separated string from list what would be your preferred way to concatenate strings from sequence such that between each two consecutive pair comma is added that is how do you map for instance to the cases and should be mapped to and respectively usually end up using something like join map lambda but also feeling somewhat unsatisfied edit am both ashamed and happy that the solution is so simple obviously have hardly clue as to what am doing probably needed simple concatenation in the past and somehow memorised join as shorthand for
why the map lambda magic does not this work foo print join foo print join print join edit mark biek points out the case for numbers perhaps the list comprehension join str for in foo is more pythonic edit thanks for the suggestions will use the generator rather than the list comprehension in the future join str for in foo
QA
how would you make comma separated string from list what would be your preferred way to concatenate strings from sequence such that between each two consecutive pair comma is added that is how do you map for instance to the cases and should be mapped to and respectively usually end up using something like join map lambda but also feeling somewhat unsatisfied edit am both ashamed and happy that the solution is so simple obviously have hardly clue as to what am doing probably needed simple concatenation in the past and somehow memorised join as shorthand for
do not you just want join obviously it gets more complicated if you need to quote escape commas etc in the values in that case would suggest looking at the csv module in the standard library https docs python org library csv html
QA
how would you make comma separated string from list what would be your preferred way to concatenate strings from sequence such that between each two consecutive pair comma is added that is how do you map for instance to the cases and should be mapped to and respectively usually end up using something like join map lambda but also feeling somewhat unsatisfied edit am both ashamed and happy that the solution is so simple obviously have hardly clue as to what am doing probably needed simple concatenation in the past and somehow memorised join as shorthand for
unless am missing something join foo should do what you are asking for join join join edit and as jmanning points out join str for in foo is safer and quite pythonic though the resulting string will be difficult to parse if the elements can contain commas at that point you need the full power of the csv module as douglas points out in his answer
QA
can someone explain all in python have been using python more and more and keep seeing the variable all set in different init py files can someone explain what this does
it is list of public objects of that module it overrides the default of hiding everything that begins with an underscore
QA
can someone explain all in python have been using python more and more and keep seeing the variable all set in different init py files can someone explain what this does
from an unofficial python reference wiki the public names defined by module are determined by checking the module namespace for variable named all if defined it must be sequence of strings which are names defined or imported by that module the names given in all are all considered public and are required to exist if all is not defined the set of public names includes all names found in the module namespace which do not begin with an underscore character all should contain the entire public api it is intended to avoid accidentally exporting items that are not part of the api such as library modules which were imported and used within the module
QA
how would you make comma separated string from list what would be your preferred way to concatenate strings from sequence such that between each two consecutive pair comma is added that is how do you map for instance to the cases and should be mapped to and respectively usually end up using something like join map lambda but also feeling somewhat unsatisfied edit am both ashamed and happy that the solution is so simple obviously have hardly clue as to what am doing probably needed simple concatenation in the past and somehow memorised join as shorthand for
jmanning using list comprehension has the downside of creating new temporary list the better solution would be using itertools imap which returns an iterator from itertools import imap foo bar join imap str
QA
can the http version or headers affect the visual appearance of web page know would have thought the answer was obviously no as well but am experiencing strange situation where when view my site from our staging server it appears slightly larger than when view it from my local dev server have used charles to confirm that all of the content the html the images the css the javascript everything is the same the only difference in the traffic is that because the local site is served from the django development mode server the response headers look like this http ok server wsgiserver python date thu sep gmt vary cookie content length content type text html charset utf whereas on the staging server where django is running inside apache the headers look like this http ok date thu sep gmt server apache ubuntu mod python python php ubuntu with suhosin patch vary cookie content length content type text html charset utf so as far as can tell the only differences are http vs http the server identifer apache vs wsgiserver and the order of the date server headers to elaborate bit further on the differences in appearance basically it appears as if the version of the site on the staging server is zoomed in by about for example the primary logo which dominates our home page is pixels wide but when server from our staging server shows up as pixels wide everything else on the page other images text spacing etc is also proportionately larger this is all in firefox do not have any other browsers available to test with at the moment has anyone else encountered any bizarre behavior anything like this before am at loss
have you tried view zoom reset on both sites
QA
python packages import by class not file say have the following file structure app app py controllers init py project py plugin py if app controllers project py defines class project app py would import it like this from app controllers project import project would like to just be able to do from app controllers import project how would this be done
you need to put from project import project in controllers init py note that when absolute imports become the default python you will want to add dot before the module name to avoid collisions with top level model named project from project import project
QA
where can find the time and space complexity of the built in sequence types in python have been unable to find source for this information short of looking through the python source code myself to determine how the objects work does anyone know where could find this online
if your asking what think your asking you can find them here page and on it is written around optimization techniques for python it is mostly big notation of time efficiencies not much memory
QA
is there python library for generating ico files am looking to create favicon ico files programatically from python but pil only has support for reading ico files
perhaps the following would work generate your icon image using pil convert the image to ico format using the python interface to imagemagick pythonmagick have not tried this approach the imagemagick convert command line program was able to convert png file to ico format so at least imagemagick supports the ico format
QA
is there python library for generating ico files am looking to create favicon ico files programatically from python but pil only has support for reading ico files
do not know if this applies for all cases but on winxp an ico can be bmp of size or just change the extension to ico from bmp and you are ready to go
QA
where can find the time and space complexity of the built in sequence types in python have been unable to find source for this information short of looking through the python source code myself to determine how the objects work does anyone know where could find this online
raymond hettinger does an excellent talk slides about python built in collections called core python containers under the hood the version saw focussed mainly on set and dict but list was covered too there are also some photos of the pertinent slides from europython in blog here is summary of my notes on list stores items as an array of pointers subscript costs time append costs amortized time insert costs time tries to avoid memcpy when growing by over allocating many small lists will waste lot of space but large lists never waste more than about to overallocation some operations pre size examples given were range map list none and slicing when shrinking the array is realloced only when it is wasting of space pop is cheap
QA
wacom tablet python interface if possible want to catch pressure sensitive input from wacom tablet in python are there any python libraries available that can do this
you could perhaps take look at the software described here it is gnome applet written in python from the web site the gnome wacom applet is small gnome panel applet that shows how much pressure is being applied to your wacom tablet by the current device clicking on the panel icon brings up dialog allowing you to select different device and check what pressure and tilt information is being recieved from it this dialog also contains small drawing test area to give your pen quick test google is your friend
QA
is there python library for generating ico files am looking to create favicon ico files programatically from python but pil only has support for reading ico files
according to wikipedia modern browsers can handle favicons in png format so maybe you could just generate that alternatively the ico article describes the format
QA
analizing mips binaries is there python library for parsing binary data am working on utility which needs to resolve hex addresses to symbolic function name and source code line number within binary the utility will run on linux on though the binaries it analyzes will be for mips based embedded system the mips binaries are in elf format using dwarf for the symbolic debugging information am currently planning to fork objdump passing in list of hex addresses and parsing the output to get function names and source line numbers have compiled an objdump with support for mips binaries and it is working would prefer to have package allowing me to look things up natively from the python code without forking another process can find no mention of libdwarf libelf or libbfd on python org nor any mention of python on dwarfstd org is there suitable module available somewhere
do not know of any but if all else fails you could use ctypes to directly use libdwarf libelf or libbfd
QA
where can find the time and space complexity of the built in sequence types in python have been unable to find source for this information short of looking through the python source code myself to determine how the objects work does anyone know where could find this online
checkout the timecomplexity page on the py dot org wiki it covers set dicts lists etc at least as far as time complexity goes
QA
how to know whether window with given title is already open in tk ve writen little python script that just pops up message box containing the text passed on the command line want to pop it up only when the window resulting from previous call is not open from tkinter import import tkmessagebox root tk root withdraw todo not if window with this title exists tkmessagebox showinfo key you join sys argv any idea how to check that
believe you want if normal root state tkmessagebox showinfo key you join sys argv
QA
how would you make comma separated string from list what would be your preferred way to concatenate strings from sequence such that between each two consecutive pair comma is added that is how do you map for instance to the cases and should be mapped to and respectively usually end up using something like join map lambda but also feeling somewhat unsatisfied edit am both ashamed and happy that the solution is so simple obviously have hardly clue as to what am doing probably needed simple concatenation in the past and somehow memorised join as shorthand for
peter hoffmann using generator expressions has the benefit of also producing an iterator but saves importing itertools furthermore list comprehensions are generally preferred to map thus would expect generator expressions to be preferred to imap foo bar join str bit for bit in foo bar
QA
pylons error mysql server has gone away hope this is not too obscure will ask the newsgroup if nobody knows here am using pylons python framework to serve simple web application but it seems to die from time to time with this in the error log mysql server has gone away did bit of checking and saw that this was because the connections to mysql were not being renewed this should not be problem though because the sqlalchemy pool recycle in the config file should automatically keep it alive the default was but dialed it back to because of this problem it helped bit but should be fine according to the docs the errors still happen semi regularly do not want to lower it too much though and dos my own database maybe something in my mysql config is goofy not sure where to look exactly other relevant details python pylons sql alchemy mysql
think fixed it it is turns out had simple config error my ini file read sqlalchemy default url connection string here sqlalchemy pool recycle the problem is that my environment py file declared that the engine would only map keys with the prefix sqlalchemy default so pool recycle was ignored the solution is to simply change the second line in the ini to sqlalchemy default pool recycle
QA
why java and python garbage collection methods are different python uses the reference count method to handle object life time so an object that has no more use will be immediately destroyed but in java the gc garbage collector destroys objects which are no longer used at specific time why does java choose this strategy and what is the benefit from this is this better than the python approach
reference counting is particularly difficult to do efficiently in multi threaded environment do not know how you would even start to do it without getting into hardware assisted transactions or similar currently unusual atomic instructions reference counting is easy to implement jvms have had lot of money sunk into competing implementations so it should not be surprising that they implement very good solutions to very difficult problems however it is becoming increasingly easy to target your favourite language at the jvm
QA
iterate over subclasses of given class in given module in python given module and class how can iterate or generate list of all subclasses of that exist in module
can suggest that neither of the answers from chris atlee and zacherates fulfill the requirements think this modification to zacerates answer is better def find subclasses module clazz for name in dir module getattr module name try if clazz and issubclass clazz yield name except typeerror pass the reason disagree with the given answers is that the first does not produce classes that are distant subclass of the given class and the second includes the given class
QA
which version of python to use for maximum compatibility if was going to start an open source project using python what version should use to ensure that the vast majority of users can use it on their system am the kind of person who quickly jumps to the next version which will do when python comes out but many people may be more conservative if their current version seems to be working fine what version would hit the sweet spot but still allow me to enjoy the newest and coolest language enhancements
have not seen system with less than installed for some time mostly is installed by default for most os use now is just on an older solaris machine linux distros tend to have as does os iirc has lot of the features does but usable only with from future import
QA
which version of python to use for maximum compatibility if was going to start an open source project using python what version should use to ensure that the vast majority of users can use it on their system am the kind of person who quickly jumps to the next version which will do when python comes out but many people may be more conservative if their current version seems to be working fine what version would hit the sweet spot but still allow me to enjoy the newest and coolest language enhancements
as python is in kind of an transition phase towards python with breaking backward compatibility do not think it is good idea to go python only based on the time line there will be at least one or two following releases of the series after in october beside not having python available on your target platforms it will take some time until important external python libraries will be ported and usable on python so as matthew suggests staying at and keeping the transition plan to python in mind is solid choice
QA
django print url of view without hardcoding the url can print out url admin manage products add of certain view in template here is the rule want to create link for manage products add create object model product post save redirect would like to have manage products add in template without hardcoding it how can do this edit am not using the default admin well am but it is at another url this is my own
if you use named url patterns you can do the follwing in your template url create object
QA
django print url of view without hardcoding the url can print out url admin manage products add of certain view in template here is the rule want to create link for manage products add create object model product post save redirect would like to have manage products add in template without hardcoding it how can do this edit am not using the default admin well am but it is at another url this is my own
the preferred way of creating the url is by adding get absolute url method to your model classes you can hardcode the path there so you at least get closer to following the kiss philosophy you can go further by utilizing the permalink decorator that figures the path based on the urls configuration you can read more in the django documentation here
QA
which version of python to use for maximum compatibility if was going to start an open source project using python what version should use to ensure that the vast majority of users can use it on their system am the kind of person who quickly jumps to the next version which will do when python comes out but many people may be more conservative if their current version seems to be working fine what version would hit the sweet spot but still allow me to enjoy the newest and coolest language enhancements
you can use different versions of python on each machine coding something new would not use anything less than python you can do apt get install python on stock debian stable for windows do not really worry about it it is very easy to install the python msi if the users cannot be bothered to do that you can deploy an executable with py exe so simple and build an installer with inno setup again simple then it will behave like standard windows application and will use its own python dlls so no need to have python installed like peter said keep in mind the transition to but do not build on it yet
QA
how do you set up python wsgi server under iis work in windows environment and would prefer to deploy code to iis at the same time would like to code in python having read that iis can run fastcgi application went to the iis site where it describes in detail how to get php up and running but not much about anything else does anyone have experience getting python framework running under iis using something other that plain old cgi if so can you explain to direct me to some instructions on setting this up
there should not be any need to use fastcgi there exists isapi extension for wsgi
QA
django print url of view without hardcoding the url can print out url admin manage products add of certain view in template here is the rule want to create link for manage products add create object model product post save redirect would like to have manage products add in template without hardcoding it how can do this edit am not using the default admin well am but it is at another url this is my own
you can use get absolute url but that will only work for particular object since your object has not been created yet it will not work in this case you want to use named url patterns here is quick intro change the line in your urls py to manage products add create object model product post save redirect create product then in your template you use this to display the url url create product if you are using django or higher you need this url create product you can do some more powerful things with named url patterns they are very handy note that they are only in the development version and also
QA
is there way to attach debugger to multi threaded python process am trying to debug deadlock in multi threaded python application after it has locked up is there way to attach debugger to inspect the state of the process edit am attempting this on linux but it would be great if there were cross platform solution it is python after all
what platform are you attempting this on most debuggers allow you to attach to running process by using the process id you can either output the process id via logging or using something like task manager once that is achieved it will be possible to inspect individual threads and their call stacks edit do not have any experience with gnu debugger gdb which is cross platform however found this link and it may start you on the right path it explains how to add debug symbols handy for reading stack traces and how to instruct gdb to attach to running python process
QA
generator expressions vs list comprehension when should you use generator expressions and when should you use list comprehensions in python generator expression for in range list comprehension for in range
use list comprehensions when the result needs to be iterated over multiple times or where speed is paramount use generator expressions where the range is large or infinite
QA
generator expressions vs list comprehension when should you use generator expressions and when should you use list comprehensions in python generator expression for in range list comprehension for in range
iterating over the generator expression or the list comprehension will do the same thing however the list comprehension will create the entire list in memory first while the generator expression will create the items on the fly so you are able to use it for very large and also infinite sequences
QA
generator expressions vs list comprehension when should you use generator expressions and when should you use list comprehensions in python generator expression for in range list comprehension for in range
john answer is good that list comprehensions are better when you want to iterate over something multiple times however it is also worth noting that you should use list if you want to use any of the list methods for example the following code will not work def gen return something for something in get some stuff print gen generators do not support indexing or slicing print gen generators cannot be added to lists basically use generator expression if all you are doing is iterating once if you want to store and use the generated results then you are probably better off with list comprehension since performance is the most common reason to choose one over the other my advice is to not worry about it and just pick one if you find that your program is running too slowly then and only then should you go back and worry about tuning your code
QA
what are the advantages of packaging your python library application as an egg file have read some about egg files and have noticed them in my lib directory but what are the advantages disadvantages of using then as developer
from the python enterprise application kit community eggs are to pythons as jars are to java python eggs are way of bundling additional information with python project that allows the project dependencies to be checked and satisfied at runtime as well as allowing projects to provide plugins for other projects there are several binary formats that embody eggs but the most common is egg zipfile format because it is convenient one for distributing projects all of the formats support including package specific data project wide metadata extensions and python code the primary benefits of python eggs are they enable tools like the easy install python package manager egg files are zero installation format for python package no build or install step is required just put them on pythonpath or sys path and use them may require the runtime installed if extensions or data files are used they can include package metadata such as the other eggs they depend on they allow namespace packages packages that just contain other packages to be split into separate distributions zope twisted peak packages can be distributed as separate eggs unlike normal packages which must always be placed under the same parent directory this allows what are now huge monolithic packages to be distributed as separate components they allow applications or libraries to specify the needed version of library so that you can require twisted internet before doing an import twisted internet they are great format for distributing extensions or plugins to extensible applications and frameworks such as trac which uses eggs for plugins as of because the egg runtime provides simple apis to locate eggs and find their advertised entry points similar to eclipse extension point concept there are also other benefits that may come from having standardized format similar to the benefits of java jar format
QA
what are the advantages of packaging your python library application as an egg file have read some about egg files and have noticed them in my lib directory but what are the advantages disadvantages of using then as developer
egg files are basically nice way to deploy your python application you can think of it as something like jar files for java more info here
QA
what are the advantages of packaging your python library application as an egg file have read some about egg files and have noticed them in my lib directory but what are the advantages disadvantages of using then as developer
eggs are pretty good way to distribute python apps think of it as platform independent deb file that will install all dependencies and whatnot the advantage is that it is easy to use for the end user the disadvantage are that it can be cumbersome to package your app up as egg file you should also offer an alternative means of installation in addition to eggs there are some people who do not like using eggs because they do not like the idea of software program installing whatever software it wants these usually tend to be sysadmin types
QA
glade or no glade what is the best way to use pygtk have been learning python for while now with some success even managed to create one or two simple programs using pygtk glade the thing is am not sure if the best way to use gtk with python is by building the interfaces using glade was wondering if the more experienced ones among us remember am just beginner could point out the benefits and caveats of using glade as opposed to creating everything in the code itself assuming that learning the correct gtk bindings would not exactly be problem
use gtkbuilder instead of glade it is integrated into gtk itself instead of separate library the main benefit of glade is that it is much much easier to create the interface it is bit more work to connect signal handlers but have never felt that matters much
QA
which version of python to use for maximum compatibility if was going to start an open source project using python what version should use to ensure that the vast majority of users can use it on their system am the kind of person who quickly jumps to the next version which will do when python comes out but many people may be more conservative if their current version seems to be working fine what version would hit the sweet spot but still allow me to enjoy the newest and coolest language enhancements
python or if you can live without the many modules that were added datetime csv logging optparse zipimport are not using ssl and are willing to add boilerplate for true false added decorators generator expressions reversed sorted and the subprocess and decimal modules although these are all nice it is easy to write pythonic code without them assuming that your project would not make heavy use of them added with relative imports better bit support and quite bit of speed you could live without all of those easily enough is not released although it is very close so while it might appeal to developers it does not have the compatibility you are after take look at the release notes for and the upcoming use http www python org download releases highlights where is the minor version fwiw for spambayes we support and above requires installing the email package separately this is not overly taxing but the additions are useful enough and old enough that we will probably drop before long
QA
embedding remote python she will in an application you can embed the ipython she will inside of your application so that it launches the she will in the foreground is there way to embed telnet server in python app so that you can telnet to certain port and launch remote ipython she will any tips for redirecting the input output streams for ipython or how to hook it up to telnet server library or recommendations for other libraries that could be used to implement this are much appreciated
python includes telnet client but not telnet server you can implement telnet server using twisted here is an example as for hooking these things together that is up to you
QA
how can render tree structure recursive using django template have tree structure in memory that would like to render in html using django template class node name node name children there will be some object root that is node and children is list of nodes root will be passed in the content of the template have found this one discussion of how this might be achieved but the poster suggests this might not be good in production environment does anybody know of better way
django has built in template helper for this exact scenario https docs djangoproject com en dev ref templates builtins unordered list
QA
embedding remote python she will in an application you can embed the ipython she will inside of your application so that it launches the she will in the foreground is there way to embed telnet server in python app so that you can telnet to certain port and launch remote ipython she will any tips for redirecting the input output streams for ipython or how to hook it up to telnet server library or recommendations for other libraries that could be used to implement this are much appreciated
think you should base your server class on the socketserver class from the standard library you will need to write requesthandler to read and echo input but lot of the heavy lifting is already done for you you can use the threadingmixin to make the server multi threaded very easily
QA
python web application framework for tight db gui coupling am firm believer of the heretic thought of tight coupling between the backend and frontend want existing implied knowledge about backend to be automatically made use of when generating user interfaces if varchar column has maximum with of characters there guis should automatically constrain the user from typing more than characters in related form field and have strong antipathy to orms which want to define my database tables or are based on some hack where every table needs to have extra numeric id columns because of the orm have looked bit into python database frameworks and think can conclude the sqlalchemy fits best to my mentality now need to find web application framework which fits naturally with sqlalchemy or an equivalent and perhaps even with my appetite for coupling with web application framework mean products project such as pyhons django turbogears web py etc it should ideally be able to automatically select suitable form widget for data entering given column if told to do so if the column has foreign key to column with different values widget should display the possible values as dropdown auto generate javascript form validation code which gives the end user quick error feedback if string is entered into field which is about to end up in an integer column etc auto generate calendar widget for data which will end up in date column hint not null constraints as javascript which complains about empty or whitespace only data in related input field generate javascript validation code which matches relevant simple check constraints make it easy to avoid sql injection by using prepared statements and or validation of externally derived data make it easy to avoid cross site scripting by automatically escape outgoing strings when appropriate make use of constraint names to generate somewhat user friendly error messages in case constrataint is violated all this should happen dynamically so table adjustments are automatically reflected on the frontend probably with caching mechanism so that all the model introspection would not kill performance in other words do not want to repeat my model definition in an xml file or alike when it has already been carefully been defined in my database does such framework exist for python or for any language for that matter if not which of the several python web application frameworks will be least in the way if were to add parts of the above features myself
turbogears currently uses sqlobject by default but you can use it with sqlalchemy they are saying that the next major release of turbogears will use sqlalchemy by default
QA
what is tuple useful for am learning python for class now and we just covered tuples as one of the data types read the wikipedia page on it but could not figure out where such data type would be useful in practice can have some examples perhaps in python where an immutable set of numbers would be needed how is this different from list
like this explanation basically you should use tuples when there is constant structure the st position always holds one type of value and the second another and so forth and lists should be used for lists of homogeneous values of course there is always exceptions but this is good general guideline
QA
project structure for google app engine started an application in google app engine right when it came out to play with the technology and work on pet project that had been thinking about for long time but never gotten around to starting the result is bowlsk however as it has grown and features have been added it has gotten really difficult to keep things organized mainly due to the fact that this is my first python project and did not know anything about it until started working what have main level contains all py files did not know how to make packages work all html templates for main level pages subdirectories separate folders for css images js etc folders that hold html templates for subdirecty type urls example http www bowlsk com maps to homepage default package template at index html http www bowlsk com games view series html series maps to viewseriespage again default package template at games view series html it is nasty how do restructure had ideas main folder containing appdef indexes main py subfolder for code does this have to be my first package subfolder for templates folder heirarchy would match package heirarchy individual subfolders for css images js etc main folder containing appdef indexes main py subfolder for code templates this way have the handler class right next to the template because in this stage am adding lots of features so modifications to one mean modifications to the other again do have to have this folder name be the first package name for my classes would like the folder to be src but do not want my classes to be src whateverpage is there best practice with django on the horizon is there something can do now to improve my ability to integrate with it when it becomes the official gae templating engine would simply start trying these things and seeing which seems better but pydev refactoring support does not seem to handle package moves very well so it will likely be non trivial task to get all of this working again
am not entirely up to date on the latest best practices et cetera when it comes to code layout but when did my first gae application used something along your second option where the code and templates are next to eachother there was two reasons for this one it kept the code and template nearby and secondly had the directory structure layout mimic that of the website making it for me bit easier too remember where everything was
QA
python web application framework for tight db gui coupling am firm believer of the heretic thought of tight coupling between the backend and frontend want existing implied knowledge about backend to be automatically made use of when generating user interfaces if varchar column has maximum with of characters there guis should automatically constrain the user from typing more than characters in related form field and have strong antipathy to orms which want to define my database tables or are based on some hack where every table needs to have extra numeric id columns because of the orm have looked bit into python database frameworks and think can conclude the sqlalchemy fits best to my mentality now need to find web application framework which fits naturally with sqlalchemy or an equivalent and perhaps even with my appetite for coupling with web application framework mean products project such as pyhons django turbogears web py etc it should ideally be able to automatically select suitable form widget for data entering given column if told to do so if the column has foreign key to column with different values widget should display the possible values as dropdown auto generate javascript form validation code which gives the end user quick error feedback if string is entered into field which is about to end up in an integer column etc auto generate calendar widget for data which will end up in date column hint not null constraints as javascript which complains about empty or whitespace only data in related input field generate javascript validation code which matches relevant simple check constraints make it easy to avoid sql injection by using prepared statements and or validation of externally derived data make it easy to avoid cross site scripting by automatically escape outgoing strings when appropriate make use of constraint names to generate somewhat user friendly error messages in case constrataint is violated all this should happen dynamically so table adjustments are automatically reflected on the frontend probably with caching mechanism so that all the model introspection would not kill performance in other words do not want to repeat my model definition in an xml file or alike when it has already been carefully been defined in my database does such framework exist for python or for any language for that matter if not which of the several python web application frameworks will be least in the way if were to add parts of the above features myself
know that you specificity ask for framework but thought would let you know about what get up to here have just undergone converting my company web application from custom in house orm layer into sqlalchemy so am far from an expert but something that occurred to me was that sqlalchemy has types for all of the attributes it maps from the database so why not use that to help output the right html onto the page so we use sqlalchemy for the back end and cheetah templates for the front end but everything in between is basically our own still we have never managed to find framework that does exactly what we want without compromise and prefer to get all the bits that work right for us and write the glue our selves step for each data type sqlalchemy types integer etc add an extra function tohtml or many maybe tohtmlreadonly tohtmladminedit whatever and just have that return the template for the html now you do not even have to care what data type your displaying if you just want to spit out whole table you can just do as cheetah template or what ever your templating engine is step table tr for field in dbobject th field name th end for tr tr for field in dbobject td field type tohtml field name field value td end for tr table using this basic method and stretching pythons introspection to its potential in an afternoon managed to make create read update and delete code for our whole admin section of out database not yet with the polish of django but more then good enough for my needs step discovered the need for third step just on friday wanted to upload files which as you know needs more then just the varchar data types default text box no sweat just overrode the rows class in my table definition from varchar to filepath varchar where the only difference was filepath had different tohtml method worked flawlessly all that said if there is shrink wrapped one out there that does just what you want use that disclaimer this code was written from memory after midnight and probably will not produce functioning web page
QA
how do implement pre commit hook script in svn that calls dos unix to validate checked in file was wondering if anyone here had some experience writing this type of script and if they could give me some pointers would like to modify this script to validate that the check in file does not have carriage return in the eol formatting the eol format is cr lf in windows and lf in unix when user checks in code with the windows format it does not compile in unix anymore know this can be done on the client side but need to have this validation done on the server side to achieve this need to do the following make sure the file check is not binary do not know how to do this with svnlook should check the mime type of the file the red book does not indicate this clearly or must have not seen it would like to run the dos unix command to validate that the file has the correct eol format would compare the output of the dos unix command against the original file if there is different between both give an error message to the client and cancel the check in would like your comments feedback on this approach
what exactly are you trying to do of course there are numerous places to learn about svn pre commit hooks here here and in the red book but it depends what you are trying to do and what is available on your system can you be more specific