prefix
stringclasses 1
value | input_text
stringlengths 19
27.3k
⌀ | target_text
stringlengths 2
24.8k
⌀ |
---|---|---|
QA
|
setup python enviroment on windows how do setup python enviroment on windows computer so can start writing and running python scripts is there an install bundle also which database should use thanks sorry should of mentioned that am using this for web based applications does it require apache or does it use another http server what is the standard setup for python running web apps
|
bundle go with activestate python which bundles many useful win related libraries it has no version yet but most code you will find online refers to and lower anyway database any of the popular open source dbs are simple to configure but as john already suggested for simple beginning stuff just use sqlite which already comes bundled with python web server depends on the scale you can configure apache yes but for trying simple things the following is quite complete web server in python that will also serve cgi scripts writte in python import cgihttpserver import basehttpserver class handler cgihttpserver cgihttprequesthandler cgi directories cgi port httpd basehttpserver httpserver port handler print serving at port port httpd serve forever
|
QA
|
setup python enviroment on windows how do setup python enviroment on windows computer so can start writing and running python scripts is there an install bundle also which database should use thanks sorry should of mentioned that am using this for web based applications does it require apache or does it use another http server what is the standard setup for python running web apps
|
strongly recommend activestate python for python on windows development it comes with win com and various other goodies has mature and clean installer chm version of the docs and works really well use this all of the time as for database activestate comes with odbc support which plays very nicely with sql server have also had it working with sybase and db although the connection strings for the latter tend to be rather convoluted for oracle recommend cx oracle as the best interface library native drivers for most proprietary and open source databases such as mysql and postgresql also exist recent versions of python from onwards iirc come with sqlite bundled as standard
|
QA
|
how do watch file for changes using python have log file being written by another process which want to watch for changes each time change occurrs would like to read the new data in to do some processing on it what is the best way to do this was hoping there would be some sort of hook from the pywin library have found the win file findnextchangenotification function but have no idea how to ask it to watch specific file if anyone done anything like this would be really grateful to hear how edit should have mentioned that was after solution that does not require polling edit curses it seems this does not work over mapped network drive am guessing windows does not hear any updates to the file the way it does on local disk
|
check my answer to similar question you could try the same loop in python this page suggests import time while where file tell line file readline if not line time sleep file seek where else print line already has newline also see the question tail file with python
|
QA
|
how do watch file for changes using python have log file being written by another process which want to watch for changes each time change occurrs would like to read the new data in to do some processing on it what is the best way to do this was hoping there would be some sort of hook from the pywin library have found the win file findnextchangenotification function but have no idea how to ask it to watch specific file if anyone done anything like this would be really grateful to hear how edit should have mentioned that was after solution that does not require polling edit curses it seems this does not work over mapped network drive am guessing windows does not hear any updates to the file the way it does on local disk
|
have you already looked at the documentation available on http timgolden me uk python win how do watch directory for changes html if you only need it to work under windows the nd example seems to be exactly what you want if you exchange the path of the directory with the one of the file you want to watch otherwise polling will probably be the only really platform independent option note have not tried any of these solutions
|
QA
|
how do watch file for changes using python have log file being written by another process which want to watch for changes each time change occurrs would like to read the new data in to do some processing on it what is the best way to do this was hoping there would be some sort of hook from the pywin library have found the win file findnextchangenotification function but have no idea how to ask it to watch specific file if anyone done anything like this would be really grateful to hear how edit should have mentioned that was after solution that does not require polling edit curses it seems this does not work over mapped network drive am guessing windows does not hear any updates to the file the way it does on local disk
|
if polling is good enough for you would just watch if the modified time file stat changes to read it os stat filename st mtime also note that the windows native change event solution does not work in all circumstances on network drives import os class monkey object def init self self cached stamp self filename path to file def ook self stamp os stat self filename st mtime if stamp self cached stamp self cached stamp stamp file has changed so do something
|
QA
|
what do need to import to gain access to my models would like to run script to populate my database would like to access it through the django database api the only problem is that do not know what would need to import to gain access to this how can this be achieved
|
in addition to your own models files you need to import your settings module as well
|
QA
|
os path can you explain this behavior love python because it comes batteries included and use built in functions lot to do the dirty job for me have always been using happily the os path module to deal with file path but recently ended up with unexpected results on python under ubuntu linux while dealing with string that represent windows file paths filepath ttemp filepa exe print os path basename filepath ttemp filepa exe print os path splitdrive filepath ttemp filepa exe wtf it ends up the same way with filepath you ttemp filepa exe and filepath ttemp filepa exe do you have clue ubuntu use utf but do not feel like it has something to do with it maybe my python install is messed up but did not perform any particular tweak on it that can remember
|
from os path documentation os path splitdrive path split the pathname path into pair drive tail where drive is either drive specification or the empty string on systems which do not use drive specifications drive will always be the empty string in all cases drive tail will be the same as path if you running this on unix it does not use drive specifications hence drive will be empty string if you want to solve windows paths on any platform you can just use simple regexp import re drive tail re compile za match filepath groups drive will be drive letter followed by eg you or none and tail the whole rest
|
QA
|
os path can you explain this behavior love python because it comes batteries included and use built in functions lot to do the dirty job for me have always been using happily the os path module to deal with file path but recently ended up with unexpected results on python under ubuntu linux while dealing with string that represent windows file paths filepath ttemp filepa exe print os path basename filepath ttemp filepa exe print os path splitdrive filepath ttemp filepa exe wtf it ends up the same way with filepath you ttemp filepa exe and filepath ttemp filepa exe do you have clue ubuntu use utf but do not feel like it has something to do with it maybe my python install is messed up but did not perform any particular tweak on it that can remember
|
see the documentation here specifically splitdrive split pathname into drive and path on posix drive is always empty so this will not work on linux box
|
QA
|
how do watch file for changes using python have log file being written by another process which want to watch for changes each time change occurrs would like to read the new data in to do some processing on it what is the best way to do this was hoping there would be some sort of hook from the pywin library have found the win file findnextchangenotification function but have no idea how to ask it to watch specific file if anyone done anything like this would be really grateful to hear how edit should have mentioned that was after solution that does not require polling edit curses it seems this does not work over mapped network drive am guessing windows does not hear any updates to the file the way it does on local disk
|
as you can see in tim golden article pointed by horst gutmann win is relatively complex and watches directories not single file would like to suggest you look into ironpython which is net python implementation with ironpython you can use all the net functionality including system io filesystemwatcher which handles single files with simple event interface
|
QA
|
what do need to import to gain access to my models would like to run script to populate my database would like to access it through the django database api the only problem is that do not know what would need to import to gain access to this how can this be achieved
|
import your settings module too import os os environ django settings module mysite settings from mysite polls models import poll choice should do the trick
|
QA
|
os path can you explain this behavior love python because it comes batteries included and use built in functions lot to do the dirty job for me have always been using happily the os path module to deal with file path but recently ended up with unexpected results on python under ubuntu linux while dealing with string that represent windows file paths filepath ttemp filepa exe print os path basename filepath ttemp filepa exe print os path splitdrive filepath ttemp filepa exe wtf it ends up the same way with filepath you ttemp filepa exe and filepath ttemp filepa exe do you have clue ubuntu use utf but do not feel like it has something to do with it maybe my python install is messed up but did not perform any particular tweak on it that can remember
|
if you want to manipulate windows paths on linux you should use the ntpath module this is the module that is imported as os path on windows posixpath is imported as os path on linux import ntpath filepath ttemp filepa exe print ntpath basename filepath filepa exe print ntpath splitdrive filepath ttemp filepa exe
|
QA
|
how do watch file for changes using python have log file being written by another process which want to watch for changes each time change occurrs would like to read the new data in to do some processing on it what is the best way to do this was hoping there would be some sort of hook from the pywin library have found the win file findnextchangenotification function but have no idea how to ask it to watch specific file if anyone done anything like this would be really grateful to hear how edit should have mentioned that was after solution that does not require polling edit curses it seems this does not work over mapped network drive am guessing windows does not hear any updates to the file the way it does on local disk
|
well since you are using python you can just open file and keep reading lines from it open file log if the line read is not empty you process it line readline if line do what you want with the line you may be missing that it is ok to keep calling readline at the eof it will just keep returning an empty string in this case and when something is appended to the log file the reading will continue from where it stopped as you need if you are looking for solution that uses events or particular library please specify this in your question otherwise think this solution is just fine
|
QA
|
what do need to import to gain access to my models would like to run script to populate my database would like to access it through the django database api the only problem is that do not know what would need to import to gain access to this how can this be achieved
|
if you use the she will argument to the manage py script in your project directory you do not have to import the settings manually cd mysite manage py she will python jun gcc apple inc build on darwin type help copyright credits or license for more information from myapp models import for non interactive use you could implement custom command and run it with manage py
|
QA
|
setup python enviroment on windows how do setup python enviroment on windows computer so can start writing and running python scripts is there an install bundle also which database should use thanks sorry should of mentioned that am using this for web based applications does it require apache or does it use another http server what is the standard setup for python running web apps
|
might suggest taking look at karrigell it is really nice python web framework if you do not require everything django and turbogears offers it might be easier for you to work with web frameworks until you get comfortable with them for development recommend downloading the latest spe ide it should provide you nearly all the tools you will need plus it includes wxglade for gui development
|
QA
|
applying common font scheme to multiple objects in wxpython many times will use the same font scheme for static text in wxpython application currently am making setfont call for each static text object but that seems like lot of unnecessary work however the wxpython demo and wxpython in action book do not discuss this is there way to easily apply the same setfont method to all these text objects without making separate calls each time
|
if all widgets have already been created you can apply setfont recursively for example with the following function def changefontinchildren win font set font in given window and all its descendants type win wx window type font wx font try win setfont font except pass do not require all objects to support setfont for child in win getchildren changefontinchildren child font an example usage that causes all text in frame to become default font with italic style newfont wx systemsettings getfont wx sys default gui font newfont setstyle wx fontstyle italic changefontinchildren frame newfont
|
QA
|
how do watch file for changes using python have log file being written by another process which want to watch for changes each time change occurrs would like to read the new data in to do some processing on it what is the best way to do this was hoping there would be some sort of hook from the pywin library have found the win file findnextchangenotification function but have no idea how to ask it to watch specific file if anyone done anything like this would be really grateful to hear how edit should have mentioned that was after solution that does not require polling edit curses it seems this does not work over mapped network drive am guessing windows does not hear any updates to the file the way it does on local disk
|
well after bit of hacking of tim golden script have the following which seems to work quite well import os import win file import win con path to watch look at the current directory file to watch test txt look for changes to file called test txt def processnewdata newdata print text added newdata set up the bits we will need for output actions created deleted updated renamed from something renamed to something file list directory hdir win file createfile path to watch file list directory win con file share read win con file share write none win con open existing win con file flag backup semantics none open the file we are interested in open file to watch throw away any exising log data read wait for new data and call processnewdata for each new chunk that is written while wait for change to occur results win file readdirectorychangesw hdir false win con file notify change last write none none for each change check to see if it is updating the file we are interested in for action file in results full filename os path join path to watch file print file actions get action unknown if file file to watch newtext read if newtext processnewdata newtext it could probably do with load more error checking but for simply watching log file and doing some processing on it before spitting it out to the screen this works well thanks everyone for your input great stuff
|
QA
|
python style multiple line conditions in ifs sometimes break long conditions in ifs to several lines the most obvious way to do this is if cond val and cond val and cond val and cond val do something is not very very appealing visually because the action blends with the conditions however it is the natural way using correct python indentation of spaces for the moment am using if cond val and cond val and cond val and cond val do something but this is not very pretty can you recommend an alternative way
|
someone has to champion use of vertical whitespace here if cond val and cond val and cond val do stuff this makes each condition clearly visible it also allows cleaner expression of more complex conditions if cond val or cond val and cond val and cond bad do more stuff yes we are trading off bit of vertical real estate for clarity well worth it am going to
|
QA
|
is this the best way to get unique version of filename python still diving in to python and want to make sure am not overlooking something wrote script that extracts files from several zip files and saves the extracted files together in one directory to prevent duplicate filenames from being over written wrote this little function and am just wondering if there is better way to do this thanks def unique filename file name counter file name parts os path splitext file name returns path file ext while os path isfile file name file name file name parts str counter file name parts counter return file name really do require the files to be in single directory and numbering duplicates is definitely acceptable in my case so am not looking for more robust method though suppose any pointers are welcome but just to make sure that what this accomplishes is getting done the right way
|
if you want readable names this looks like good solution there are routines to return unique file names for eg temp files but they produce long random looking names
|
QA
|
is this the best way to get unique version of filename python still diving in to python and want to make sure am not overlooking something wrote script that extracts files from several zip files and saves the extracted files together in one directory to prevent duplicate filenames from being over written wrote this little function and am just wondering if there is better way to do this thanks def unique filename file name counter file name parts os path splitext file name returns path file ext while os path isfile file name file name file name parts str counter file name parts counter return file name really do require the files to be in single directory and numbering duplicates is definitely acceptable in my case so am not looking for more robust method though suppose any pointers are welcome but just to make sure that what this accomplishes is getting done the right way
|
two small changes base name ext os path splitext file name you get two results with distinct meaning give them distinct names file name base name str counter ext it is not faster or significantly shorter but when you want to change your file name pattern the pattern is on one place and slightly easier to work with
|
QA
|
is this the best way to get unique version of filename python still diving in to python and want to make sure am not overlooking something wrote script that extracts files from several zip files and saves the extracted files together in one directory to prevent duplicate filenames from being over written wrote this little function and am just wondering if there is better way to do this thanks def unique filename file name counter file name parts os path splitext file name returns path file ext while os path isfile file name file name file name parts str counter file name parts counter return file name really do require the files to be in single directory and numbering duplicates is definitely acceptable in my case so am not looking for more robust method though suppose any pointers are welcome but just to make sure that what this accomplishes is getting done the right way
|
yes this is good strategy for readable but unique filenames one important change you should replace os path isfile with os path lexists as it is written right now if there is directory named foo bar baz your program will try to overwrite that with the new file which will not work since isfile only checks for files and not directories lexists checks for directories symlinks etc basically if there is any reason that filename could not be created edit brian gave better answer which is more secure and robust in terms of race conditions
|
QA
|
when to use the python debugger since python is dynamic interpreted language you do not have to compile your code before running it hence it is very easy to simply write your code run it see what problems occur and fix them using hotkeys or macros can make this incredibly quick so because it is so easy to immediately see the output of your program and any errors that may occur have not uses debugger tool yet what situations may call for using real debugger vs the method currently use would like to know before get into situation and get frustrated because do not know how to fix the problem
|
find it very useful to drop into debugger in failing test case add import pdb pdb set trace just before the failure point of the test the test runs building up potentially quite large context importing database fixture or constructing an http request when the test reaches the pdb set trace line it drops into the interactive debugger and can inspect the context in which the failure occurs with the usual pdb commands looking for clues as to the because
|
QA
|
is this the best way to get unique version of filename python still diving in to python and want to make sure am not overlooking something wrote script that extracts files from several zip files and saves the extracted files together in one directory to prevent duplicate filenames from being over written wrote this little function and am just wondering if there is better way to do this thanks def unique filename file name counter file name parts os path splitext file name returns path file ext while os path isfile file name file name file name parts str counter file name parts counter return file name really do require the files to be in single directory and numbering duplicates is definitely acceptable in my case so am not looking for more robust method though suppose any pointers are welcome but just to make sure that what this accomplishes is getting done the right way
|
one issue is that there is race condition in your above code since there is gap between testing for existance and creating the file there may be security implications to this think about someone maliciously inserting symlink to sensitive file which they would not be able to overwrite but your program running with higher privilege could attacks like these are why things like os tempnam are deprecated to get around it the best approach is to actually try create the file in such way that you will get an exception if it fails and on success return the actually opened file object this can be done with the lower level os open functions by passing both the os creat and os excl flags once opened return the actual file and optionally filename you create eg here is your code modified to use this approach returning file filename tuple def unique file file name counter file name parts os path splitext file name returns path file ext while try fd os open file name os creat os excl os rdrw return os fdopen fd file name except oserror pass file name file name parts str counter file name parts counter edit actually better way which will handle the above issues for you is probably to use the tempfile module though you may lose some control over the naming here is an example of using it keeping similar interface def unique file file name dirname filename os path split file name prefix suffix os path splitext filename fd filename tempfile mkstemp suffix prefix dirname return os fdopen fd filename filename unique file home some dir foo txt print filename home some dir foo txt the only downside with this approach is that you will always get filename with some random characters in it as there is no attempt to create an unmodified file home some dir foo txt first you may also want to look at tempfile temporaryfile and namedtemporaryfile which will do the above and also automatically delete from disk when closed
|
QA
|
how do write to log from mod python under apache seem to only be able to write to the apache error log via stderr anyone know of more structured logging architecture that could use from my python web project like commons
|
concur with blair conrad post about the python logging module the standard log handlers sometimes drop messages however it is worth using the logging module sockethandler and building receiver to listen for messages and write them to file here is mine example sockethandler receiver
|
QA
|
in python what is the difference between and when used for division is there benefit to using one over the other they both seem to return the same results
|
is floor division it will always give you the integer floor of the result the other is regular division
|
QA
|
in python what is the difference between and when used for division is there benefit to using one over the other they both seem to return the same results
|
the double slash is floor division
|
QA
|
in python what is the difference between and when used for division is there benefit to using one over the other they both seem to return the same results
|
implements floor division regardless of your type so will give but both and will give see https docs python org whatsnew html pep changing the division operator for details
|
QA
|
in python what is the difference between and when used for division is there benefit to using one over the other they both seem to return the same results
|
in python will return and will return the former is floating point division and the latter is floor division sometimes also called integer division in python or later in the line there is no difference for integers unless you perform from future import division which causes python to adopt the behavior of regardless of the future import will return since that is the floor division result of the operation you can find detailed description at https docs python org whatsnew html pep changing the division operator
|
QA
|
python style multiple line conditions in ifs sometimes break long conditions in ifs to several lines the most obvious way to do this is if cond val and cond val and cond val and cond val do something is not very very appealing visually because the action blends with the conditions however it is the natural way using correct python indentation of spaces for the moment am using if cond val and cond val and cond val and cond val do something but this is not very pretty can you recommend an alternative way
|
just few other random ideas for completeness sake if they work for you use them otherwise you are probably better off trying something else you could also do this with dictionary cond val cond val cond val cond val true this option is more complicated but you may also find it useful class klass object def init self some vars initialize conditions here def nonzero self return self cond val and self cond val and self cond val and self cond val foo klass if foo print foo is true else print foo is false do not know if that works for you but it is another option to consider here is one more way class klass object def init self initialize conditions here def eq self return self cond val and self cond val and self cond val and self cond val klass some values klass some other values if print else print the last two have not tested but the concepts should be enough to get you going if that is what you want to go with and for the record if this is just one time thing you are probably just better off using the method you presented at first if you are doing the comparison in lots of places these methods may enhance readability enough to make you not feel so bad about the fact that they are kind of hacky
|
QA
|
framework language for new web sites and know will get thousand depends on what you are trying to do answers but seriously there really is no solid information about this online yet here are my assumptions think they are similar for alot of people right now it is now october want to start writing an application for january am willing to use beta code and such but by january would like site that does not have strange problems with that said if language is simply slower than another do not care about those things as long as the issue is linear my main concern is developer productivity will be using linux apache mysql for the application want the power to do things like run scp and ftp client functions with stable libraries only picked those two because they are not web related but at the same time represent pretty common network protocols that any larger app might use technologies like openid and oauth will be used as well experienced web developers are readily available do not have to find people from financial companies and such whatever the choice is is common and will be around for while here is kicker would like to be able to use advanced presentation layer tools languages similar to haml sass definitively want to use jquery will be creating facebook app and at some point doing things like dealing with sms messages iphone apps etc at this point the choices for language are php cake symfony zend python django ruby merb am really between django and merb at this point mostly because everybody else seems to be going that way please do not put any technologies in here that are not made for mainstream know merb is untested mostly but their stated goal is solid platform and it has alot of momentum behind it so am confident that it is workable please do not answer with how great perl is or net for future references these choices were already made debian lenny for converting cpu cycles into something useful trac for project management gliffy for wireframes and such google docs apps for documentation hosted email etc amazon ec for hosting storage cheers adam
|
would go with django if you are comfortable with python solution it is at version now and is maturing nicely with large user base and many contributors integrating jquery is no problem and have done it without any issues the only thing is as far as can tell ruby is much more popular for web development nowadays so it is easier to find ruby developers get this impression from browsing recent job advertisements there are not that many for python or django do not know much about merb so cannot give fair comparison have done enough php to not recommend starting new project with it
|
QA
|
framework language for new web sites and know will get thousand depends on what you are trying to do answers but seriously there really is no solid information about this online yet here are my assumptions think they are similar for alot of people right now it is now october want to start writing an application for january am willing to use beta code and such but by january would like site that does not have strange problems with that said if language is simply slower than another do not care about those things as long as the issue is linear my main concern is developer productivity will be using linux apache mysql for the application want the power to do things like run scp and ftp client functions with stable libraries only picked those two because they are not web related but at the same time represent pretty common network protocols that any larger app might use technologies like openid and oauth will be used as well experienced web developers are readily available do not have to find people from financial companies and such whatever the choice is is common and will be around for while here is kicker would like to be able to use advanced presentation layer tools languages similar to haml sass definitively want to use jquery will be creating facebook app and at some point doing things like dealing with sms messages iphone apps etc at this point the choices for language are php cake symfony zend python django ruby merb am really between django and merb at this point mostly because everybody else seems to be going that way please do not put any technologies in here that are not made for mainstream know merb is untested mostly but their stated goal is solid platform and it has alot of momentum behind it so am confident that it is workable please do not answer with how great perl is or net for future references these choices were already made debian lenny for converting cpu cycles into something useful trac for project management gliffy for wireframes and such google docs apps for documentation hosted email etc amazon ec for hosting storage cheers adam
|
based in your reasons would go with ruby see that you want some administration tools scp ftp client and ruby has it net sftp and net ftp libraries also there are great gems like god for monitoring your system vlad the deployer for deploying etc and lot of alternatives in merb field just use whatever you find it is better for your needs thin mongrel ebb etc
|
QA
|
how do check out file from perforce in python would like to write some scripts in python that do some automated changes to source code if the script determines it needs to change the file would like to first check it out of perforce do not care about checking in because will always want to build and test first
|
here is what came up with import os def createnewchangelist description create new changelist and returns the changelist number as string in out os popen changelist in write change new in write description description in close changelist out readline split return changelist def openfileforedit file changelist open file for edit if changelist is passed in then open it in that list cmd edit if changelist cmd changelist ret os popen cmd file readline strip if not ret endswith opened for edit print could not open file for edit print ret raise valueerror
|
QA
|
how do check out file from perforce in python would like to write some scripts in python that do some automated changes to source code if the script determines it needs to change the file would like to first check it out of perforce do not care about checking in because will always want to build and test first
|
you may want to check out the python module it is available on the perforce site and it makes things very simple
|
QA
|
framework language for new web sites and know will get thousand depends on what you are trying to do answers but seriously there really is no solid information about this online yet here are my assumptions think they are similar for alot of people right now it is now october want to start writing an application for january am willing to use beta code and such but by january would like site that does not have strange problems with that said if language is simply slower than another do not care about those things as long as the issue is linear my main concern is developer productivity will be using linux apache mysql for the application want the power to do things like run scp and ftp client functions with stable libraries only picked those two because they are not web related but at the same time represent pretty common network protocols that any larger app might use technologies like openid and oauth will be used as well experienced web developers are readily available do not have to find people from financial companies and such whatever the choice is is common and will be around for while here is kicker would like to be able to use advanced presentation layer tools languages similar to haml sass definitively want to use jquery will be creating facebook app and at some point doing things like dealing with sms messages iphone apps etc at this point the choices for language are php cake symfony zend python django ruby merb am really between django and merb at this point mostly because everybody else seems to be going that way please do not put any technologies in here that are not made for mainstream know merb is untested mostly but their stated goal is solid platform and it has alot of momentum behind it so am confident that it is workable please do not answer with how great perl is or net for future references these choices were already made debian lenny for converting cpu cycles into something useful trac for project management gliffy for wireframes and such google docs apps for documentation hosted email etc amazon ec for hosting storage cheers adam
|
sorry but your question is wrong people are probably going to vote me down for this one but want to say it anyway would not expect to get an objective answer why that is simple all ruby advocates will tell to use ruby all python advocates will tell to use python all php advocates will tell to use php insert additional languages here got the idea recommend you to try each of the languages you mentioned for yourself at least few days each afterwards you should have much better foundation to make your final decision that said would choose ruby because am ruby advocate
|
QA
|
framework language for new web sites and know will get thousand depends on what you are trying to do answers but seriously there really is no solid information about this online yet here are my assumptions think they are similar for alot of people right now it is now october want to start writing an application for january am willing to use beta code and such but by january would like site that does not have strange problems with that said if language is simply slower than another do not care about those things as long as the issue is linear my main concern is developer productivity will be using linux apache mysql for the application want the power to do things like run scp and ftp client functions with stable libraries only picked those two because they are not web related but at the same time represent pretty common network protocols that any larger app might use technologies like openid and oauth will be used as well experienced web developers are readily available do not have to find people from financial companies and such whatever the choice is is common and will be around for while here is kicker would like to be able to use advanced presentation layer tools languages similar to haml sass definitively want to use jquery will be creating facebook app and at some point doing things like dealing with sms messages iphone apps etc at this point the choices for language are php cake symfony zend python django ruby merb am really between django and merb at this point mostly because everybody else seems to be going that way please do not put any technologies in here that are not made for mainstream know merb is untested mostly but their stated goal is solid platform and it has alot of momentum behind it so am confident that it is workable please do not answer with how great perl is or net for future references these choices were already made debian lenny for converting cpu cycles into something useful trac for project management gliffy for wireframes and such google docs apps for documentation hosted email etc amazon ec for hosting storage cheers adam
|
django look up the djangocon talks on google youtube especially reusable apps www youtube com watch tqppga have been using django for some time after starting with ruby rails found the django community easier to get into nicer the language documented with excellent examples and it is modularity is awesome especially if you are wanting to throw custom components into the mix and not be forced to use certain things here and there am sure there are probably ways to be just as flexible with rails or some such but highly encourage you to take long look at the django introductions etc at http www djangoproject com eugene mentioned it is now at and therefore will remain stable and backward compatible codebase well through january also the automatic admin interfaces it builds are production ready and extremely flexible
|
QA
|
how do check out file from perforce in python would like to write some scripts in python that do some automated changes to source code if the script determines it needs to change the file would like to first check it out of perforce do not care about checking in because will always want to build and test first
|
perforce has python wrappers around their tools available in binary form for windows and source for other platforms http www perforce com perforce loadsupp html api you will find their documentation of the scripting api to be helpful http www perforce com perforce doc current manuals script script pdf use of the python api is quite similar to the command line client pythonwin may msc bit intel on win portions copyright mark hammond see help about pythonwin for further copyright information import connect connect to the default server with the default clientspec desc description my new changelist description change new input desc run changelist change created will verify it from the command line changelist perforce change specification change the change number new on new changelist date the date this specification was last modified client the client on which the changelist was created read only user the user who created the changelist status either pending or submitted read only description comments about the changelist required jobs what opened jobs are to be closed by this changelist you may delete jobs from this list new changelists only files what opened files from the default changelist are to be added to this changelist you may delete files from this list new changelists only change date client mycomputer dt user myusername status pending description my new changelist description
|
QA
|
framework language for new web sites and know will get thousand depends on what you are trying to do answers but seriously there really is no solid information about this online yet here are my assumptions think they are similar for alot of people right now it is now october want to start writing an application for january am willing to use beta code and such but by january would like site that does not have strange problems with that said if language is simply slower than another do not care about those things as long as the issue is linear my main concern is developer productivity will be using linux apache mysql for the application want the power to do things like run scp and ftp client functions with stable libraries only picked those two because they are not web related but at the same time represent pretty common network protocols that any larger app might use technologies like openid and oauth will be used as well experienced web developers are readily available do not have to find people from financial companies and such whatever the choice is is common and will be around for while here is kicker would like to be able to use advanced presentation layer tools languages similar to haml sass definitively want to use jquery will be creating facebook app and at some point doing things like dealing with sms messages iphone apps etc at this point the choices for language are php cake symfony zend python django ruby merb am really between django and merb at this point mostly because everybody else seems to be going that way please do not put any technologies in here that are not made for mainstream know merb is untested mostly but their stated goal is solid platform and it has alot of momentum behind it so am confident that it is workable please do not answer with how great perl is or net for future references these choices were already made debian lenny for converting cpu cycles into something useful trac for project management gliffy for wireframes and such google docs apps for documentation hosted email etc amazon ec for hosting storage cheers adam
|
it depends php symfony is great framework downsides php wordy and directory heavy propel gets annoying to use upsides php is everywhere and labor is cheap well done framework and good support lots of plugins to make your life easier python django is also great framework downsides python programmers can be harder to find django even harder changing your db schema can be somewhat difficult since there are no official migrations does not quite do mvc like you would expect upsides does everything you need and has the great python std library and community behind it ruby have never used merb so will address rails upsides there is plugin gem or recipe for almost anything you could want to do easy to use downsides those plugins gems and recipes sometimes fail to work in mysterious ways monkey patching is often evil the community is vocal opinionated software and sometimes those opinions are wrong lack of foreign keys rails itself seems like tower of cards waiting to explode and take hours of your life away with all of that said am freelance php symfony and ruby rails developer have worked on several projects in both languages and frameworks my latest project is in rails solely because of activemerchant have been looking for reason to develop django app for while if there were an activemerchant like library for django probably would have used it
|
QA
|
applying common font scheme to multiple objects in wxpython many times will use the same font scheme for static text in wxpython application currently am making setfont call for each static text object but that seems like lot of unnecessary work however the wxpython demo and wxpython in action book do not discuss this is there way to easily apply the same setfont method to all these text objects without making separate calls each time
|
you can do this by calling setfont on the parent window frame dialog etc before adding any widgets the child widgets will inherit the font
|
QA
|
code to verify updates from the google safe browsing api in order to verify the data coming from the google safe browsing api you can calculate message authentication code mac for each update the instructions to do this from google are the mac is computed from an md digest over the following information client key separator table data separator client key the separator is the string coolgoog that is colon followed by coolgoog followed by colon the resulting bit md digest is websafe base encoded there is also example data to check against client key eirwn ktwczgwa hxtarq response goog black hash update mac dralftu bxwuhlk ncgjtq bdf ad ef fa bc ac bbbd cbb ec ed bc note that there are tabs at the end of each line am unable to get match please either point out where am going wrong or just write the couple of lines of python code necessary to do this fwiw expected to be able to do something like this bdf ad ef fa bc ac bbbd cbb ec ed bc eirwn ktwczgwa hxtarq hashlib md coolgoog coolgoog digest encode base qfb mxphrs ytofpkceg but as you can see qfb mxphrs ytofpkceg dralftu bxwuhlk ncgjtq
|
anders answer gives the necessary information but is not that clear the client key needs to be decoded before it is combined the example above is also missing newline at the end of the final table data so the working code is bdf ad ef fa bc ac bbbd cbb ec ed bc eirwn ktwczgwa hxtarq decode base hashlib md coolgoog coolgoog digest encode base dralftu bxwuhlk ncgjtq
|
QA
|
how do convert list of ascii values to string in python have got list in python program that contains series of numbers which are themselves ascii values how do convert this into regular string that can echo to the screen
|
import array def list return array array list tostring from python patterns an optimization anecdote
|
QA
|
what do need to import to gain access to my models would like to run script to populate my database would like to access it through the django database api the only problem is that do not know what would need to import to gain access to this how can this be achieved
|
this is what have at the top of one my data loading scripts import string import sys try import settings assumed to be in the same directory settings disable transaction management true except importerror sys stderr write error cannot find the file settings py in the directory containing it appears you have customized things nyou ll have to run django admin py passing it your settings module if the file settings py does indeed exist it is causing an importerror somehow file sys exit setup the django environment with the settings module import django import django core management django core management setup environ settings from django db import transaction this should all execute before you do much else in your script another method is to use fixtures and manage py though if you are just trying to accomplish bulk data load to initialize database this should work fine also depending on what you are doing you may or may not want to do it all in one transaction uncomment the transaction line above and structure your code similar to this transaction enter transaction management try do some stuff transaction commit finally transaction rollback pass transaction leave transaction management
|
QA
|
regular expression to match start of filename and filename extension what is the regular expression to match strings in this case file names that start with run and have filename extension of py the regular expression should match any of the following runfoo py runbar py run py it should not match myrunfoo py runbar py run txt the sql equivalent of what am looking for is like run py
|
this probably does not fully comply with file naming standards but here it goes run py
|
QA
|
regular expression to match start of filename and filename extension what is the regular expression to match strings in this case file names that start with run and have filename extension of py the regular expression should match any of the following runfoo py runbar py run py it should not match myrunfoo py runbar py run txt the sql equivalent of what am looking for is like run py
|
run py or in python specifically import re re match run py stringtocheck this will match runfoobar py but not runfoobar py to make it case insensitive instead use re match run py stringtocheck re
|
QA
|
regular expression to match start of filename and filename extension what is the regular expression to match strings in this case file names that start with run and have filename extension of py the regular expression should match any of the following runfoo py runbar py run py it should not match myrunfoo py runbar py run txt the sql equivalent of what am looking for is like run py
|
mabye run py just quick try
|
QA
|
regular expression to match start of filename and filename extension what is the regular expression to match strings in this case file names that start with run and have filename extension of py the regular expression should match any of the following runfoo py runbar py run py it should not match myrunfoo py runbar py run txt the sql equivalent of what am looking for is like run py
|
for regular expression you would use re match run py quick explanation means match any character means match any repetition of the previous character hence means any sequence of chars is an escape to escape the explicit dot indicates end of the string so we do not match run foo py txt however for this task you are probably better off using simple string methods ie filename startswith run and filename endswith py note if you want case insensitivity ie matching run py as well as run py use the re option to the regular expression or convert to specific case eg filename lower before using string methods
|
QA
|
mvc model structure in python am having problems structuring classes in the model part of an mvc pattern in my python app no matter how turn things keep running into circular imports here is what have model init should hold all model class names so can do from model import user from controller or unit test case model database py holds database class needs to import all model classes to do orm initialization should be performed on first module import no extra init calls or instantiations all methods on database class are classmethods model user py contains user model class needs access to database class to do queries should inherit from base class common to all model classes to share functionality database persistency methods parameter validation code etc have yet to see real world python app employing mvc so my approach is probably un pythonic and possibly language agnostic mess on top of that any suggestions on how to solve this thanks simon
|
generally we put it all in one file this is not java or start with single file until you get some more experience with python unless your files are gargantuan it will work fine for example django encourages this style so copy their formula for success one module for the model module for each application each application imports common model your database and superclass stuff can be in your init py file since it applies to the entire package that may reduce some of the circularity
|
QA
|
regular expression to match start of filename and filename extension what is the regular expression to match strings in this case file names that start with run and have filename extension of py the regular expression should match any of the following runfoo py runbar py run py it should not match myrunfoo py runbar py run txt the sql equivalent of what am looking for is like run py
|
warning jobscry answer run py is incorrect will not match run py for example orlandu answer run py will not match runfoo bar py do not have enough reputation to comment sorry
|
QA
|
mvc model structure in python am having problems structuring classes in the model part of an mvc pattern in my python app no matter how turn things keep running into circular imports here is what have model init should hold all model class names so can do from model import user from controller or unit test case model database py holds database class needs to import all model classes to do orm initialization should be performed on first module import no extra init calls or instantiations all methods on database class are classmethods model user py contains user model class needs access to database class to do queries should inherit from base class common to all model classes to share functionality database persistency methods parameter validation code etc have yet to see real world python app employing mvc so my approach is probably un pythonic and possibly language agnostic mess on top of that any suggestions on how to solve this thanks simon
|
think you have one issue that should be straightened circular references often result from failure to achieve separation of concerns in my opinion the database and model modules should not know much about each other working against an api instead in this case the database should not directly reference any specific model classes but instead provide the functionality the model classes will need to function the model in turn should get database reference injected or requested that it would use to query and persist itself
|
QA
|
how do perform an imap search in python using gmail and imaplib in gmail have bunch of labeled messages would like to use an imap client to get those messages but am not sure what the search incantation is imaplib imap ssl imap gmail com list ok hasnochildren gm search am not finding many examples for this sort of thing
|
have been pretty surprised that imaplib does not do lot of the response parsing and it seems that responses were crafted to be hard to parse fwiw to answer my own question search none gm have no idea what the hasnochildren part is about
|
QA
|
are there any other good alternatives to zc buildout and or virtualenv for installing non python dependencies am member of team that is about to launch beta of python django specifically based web site and accompanying suite of backend tools the team itself has doubled in size from to over the past few weeks and we expect continued growth for the next couple of months at least one issue that has started to plague us is getting everyone up to speed in terms of getting their development environment configured and having all the right eggs installed etc am looking for ways to simplify this process and make it less error prone both zc buildout and virtualenv look like they would be good tools for addressing this problem but both seem to concentrate primarily on the python specific issues we have couple of small subprojects in other languages java and ruby specifically as well as numerous python extensions that have to be compiled natively lxml mysql drivers etc in fact one of the biggest thorns in our side has been getting some of these extensions compiled against appropriate versions of the shared libraries so as to avoid segfaults malloc errors and all sorts of similar issues it does not help that out of people we have different development environments leopard on ppc leopard on intel ubuntu and windows ultimately what would be ideal would be something that works roughly like this from the dos unix prompt git clone repository url python setup env py that then does what zc buildout virtualenv does copy symlink the python interpreter provide clean space to install eggs then installs all required eggs including installing any native shared library dependencies installs the ruby project the java project etc obviously this would be useful for both getting development environments up as well as deploying on staging production servers ideally would like for the tool that accomplishes this to be written in extensible via python since that is and always will be the lingua franca of our team but am open to solutions in other languages so my question then is does anyone have any suggestions for better alternatives or any experiences they can share using one of these solutions to handle larger broader install bases
|
setuptools may be capable of more of what you are looking for than you realize if you need custom version of lxml to work correctly on macos for instance you can put url to an appropriate egg inside your setup py and have setuptools download and install that inside your developers environments as necessary it also can be told to download and install specific version of dependency from revision control that said would lean towards using scriptably generated virtual environment it is pretty straightforward to build kickstart file which installs whichever packages you depend on and then boot virtual machines or production hardware against it with puppet or similar software doing other administration adding users setting up services where is your database come from etc this comes in particularly handy when your production environment includes multiple machines just script the generation of multiple vms within their handy little sandboxed subnet use libvirt kvm for this while kvm is not available on all the platforms you have developers working on qemu certainly is or you can do as do and have small number of beefy vm hosts shared by multiple developers this gets you out of the headaches of supporting platforms you only have single virtual platform to support and means that your deployment process as defined by the kickstart file and puppet code used for setup is source controlled and run through your qa and review processes just like everything else
|
QA
|
is this the best way to get unique version of filename python still diving in to python and want to make sure am not overlooking something wrote script that extracts files from several zip files and saves the extracted files together in one directory to prevent duplicate filenames from being over written wrote this little function and am just wondering if there is better way to do this thanks def unique filename file name counter file name parts os path splitext file name returns path file ext while os path isfile file name file name file name parts str counter file name parts counter return file name really do require the files to be in single directory and numbering duplicates is definitely acceptable in my case so am not looking for more robust method though suppose any pointers are welcome but just to make sure that what this accomplishes is getting done the right way
|
if you do not care about readability uuid uuid is your friend import uuid def unique filename prefix none suffix none fn if prefix fn extend prefix fn append str uuid uuid if suffix fn extend suffix lstrip return join fn
|
QA
|
regular expression to match start of filename and filename extension what is the regular expression to match strings in this case file names that start with run and have filename extension of py the regular expression should match any of the following runfoo py runbar py run py it should not match myrunfoo py runbar py run txt the sql equivalent of what am looking for is like run py
|
if you write slightly more complex regular expression you can get an extra feature extract the bit between run and py import re regex run name py re match regex runfoo py group name foo the extra bit is the parentheses and everything between them except for which is as in rob howard answer
|
QA
|
regular expression to match start of filename and filename extension what is the regular expression to match strings in this case file names that start with run and have filename extension of py the regular expression should match any of the following runfoo py runbar py run py it should not match myrunfoo py runbar py run txt the sql equivalent of what am looking for is like run py
|
do not really understand why you are after regular expression to solve this problem you are just after way to find all py files that start with run so this is simple solution that will work without resorting to compiling an running regular expression import os for filename in os listdir dirname root ext os path splitext filename if root startswith run and ext py print filename
|
QA
|
problem opening berkeley db in python have problems opening berkeley db in python using bdtables as bdtables is used by the library am using to access the database need it to work the problem seems to be that the db environment am trying to open got copy of the database to open is version while libdb is version get the following error using bsddb dbtables bsdtabledb dbname folder db version mismatch database environment version mismatch program version does not match environment version however bsddb btopen dbname works have also tried installing db util db util and db util trying to use db verify results in db verify program version does not match environment version db verify db env open db version mismatch database environment version mismatchs db verify results in the computer just hanging and nothing happening finally if run db recover on the database that works however afterwards get the following error no such file or directory in python
|
think answers should go in the answer section rather than as an addendum to the question since that marks the question as having an answer on the various question list pages will do that for you but if you also get around to doing it leave comment on my answer so can delete it quoting answer in question verifying everything in this question eventually solved the problem the no such file or directory are caused by some db xxx files missing using bsddb dbtables bsdtabledb dbname folder create after db recover these files got created and everything is now working still it was bit of an obscure problem and initially hard to figure out but thanks to the question examining berkeley db files from the cli got the tools needed will just post it here if someone ends up with the same problem in the future and end up at stackoverflow com
|
QA
|
mvc model structure in python am having problems structuring classes in the model part of an mvc pattern in my python app no matter how turn things keep running into circular imports here is what have model init should hold all model class names so can do from model import user from controller or unit test case model database py holds database class needs to import all model classes to do orm initialization should be performed on first module import no extra init calls or instantiations all methods on database class are classmethods model user py contains user model class needs access to database class to do queries should inherit from base class common to all model classes to share functionality database persistency methods parameter validation code etc have yet to see real world python app employing mvc so my approach is probably un pythonic and possibly language agnostic mess on top of that any suggestions on how to solve this thanks simon
|
there is an inconsistency in your specification you say database py needs to import all model classes to do orm but then you say the user class need access to the database to do queries think of these as layers of an api the database class provides an api maybe object oriented to some physical persistence layer such as db api the model classes like user use the database layer to load and save their state there is no reason for the database py class to import all the model classes and in fact you would not want that because you would have to modify database py each time you created new model class which is code smell
|
QA
|
python style multiple line conditions in ifs sometimes break long conditions in ifs to several lines the most obvious way to do this is if cond val and cond val and cond val and cond val do something is not very very appealing visually because the action blends with the conditions however it is the natural way using correct python indentation of spaces for the moment am using if cond val and cond val and cond val and cond val do something but this is not very pretty can you recommend an alternative way
|
what if we only insert an additional blank line between the condition and the body and do the rest in the canonical way if cond val and cond val and cond val and cond val do something always use tabs not spaces cannot fine tune
|
QA
|
delete folder contents in python how can delete the contents of local folder in python the current project is for windows but would like to see nix also
|
updated to only delete files and to used the os path join method suggested in the comments if you also want to remove subdirectories uncomment the elif statement import os shutil folder path to folder for the file in os listdir folder file path os path join folder the file try if os path isfile file path os unlink file path elif os path isdir file path shutil rmtree file path except exception as print
|
QA
|
delete folder contents in python how can delete the contents of local folder in python the current project is for windows but would like to see nix also
|
you might be better off using os walk for this os listdir does not distinguish files from directories and you will quickly get into trouble trying to unlink these there is good example of using os walk to recursively remove directory here and hints on how to adapt it to your circumstances
|
QA
|
delete folder contents in python how can delete the contents of local folder in python the current project is for windows but would like to see nix also
|
try the shutil module import shutil shutil rmtree path to folder description shutil rmtree path ignore errors false onerror none docstring recursively delete directory tree if ignore errors is set errors are ignored otherwise if onerror is set it is called to handle the error with arguments func path exc info where func is os listdir os remove or os rmdir path is the argument to that function that caused it to fail and exc info is tuple returned by sys exc info if ignore errors is false and onerror is none an exception is raised
|
QA
|
extracting unique items from list of mappings he re an interesting problem that looks for the most pythonic solution suppose have list of mappings id id url url some ids in the list are duplicate and want to create new list with all the duplicates removed came up with the following function def unique mapping map for res in map res id res url return id id url id for id in suppose it is quite efficient but is there more pythonic way or perhaps more efficient way
|
your example can be rewritten slightly to construct the first dictionary using generator expression and to remove necessity of construction of another mappings just reuse the old ones def unique mapping mappings return dict id for in mappings values although this came out as one liner still think it is quite readable there are two things you have to keep in mind when using your original solution and mine the items will not always be returned in the same order they were originally the later entry will overwrite previous entries with the same id if you do not mind then suggest the solution above in other case this function preserves order and treats first encountered ids with priority def unique mapping mappings addedids set for in mappings mid id if mid not in addedids addedids add mid yield you might need to call it with list unique mappings mappings if you need list and not generator
|
QA
|
what is the best way to open file for exclusive access in python what is the most elegant way to solve this open file for reading but only if it is not already opened for writing open file for writing but only if it is not already opened for reading or writing the built in functions work like this path scr txt file open path print file open file scr txt mode at file open path print file open file scr txt mode at file write file write file close scr txt now contains file close scr txt was overwritten and now contains on windows python the solution should work inside the same process like in the example above as well as when another process has opened the file it is preferred if crashing program will not keep the lock open
|
to make you safe when opening files within one application you could try something like this import time class exclusivefile file openfiles filelocks class filenotexclusiveexception exception pass def init self args smode sfilename args try smode args except pass while sfilename in exclusivefile filelocks time sleep exclusivefile filelocks append sfilename if not sfilename in exclusivefile openfiles keys or exclusivefile openfiles sfilename and smode exclusivefile openfiles sfilename smode try file init self sfilename smode finally exclusivefile filelocks remove sfilename else exclusivefile filelocks remove sfilename raise self filenotexclusiveexception sfilename def close self del exclusivefile openfiles self name file close self that way you subclass the file class now just do exclusivefile tmp txt open file tmp txt mode at xb cc exclusivefile tmp txt open file tmp txt mode at xb exclusivefile tmp txt cannot open it for writing now exclfile filenotexclusiveexception tmp txt if you open it first with mode it will not allow anymore opens even in read mode just as you wanted
|
QA
|
extracting unique items from list of mappings he re an interesting problem that looks for the most pythonic solution suppose have list of mappings id id url url some ids in the list are duplicate and want to create new list with all the duplicates removed came up with the following function def unique mapping map for res in map res id res url return id id url id for id in suppose it is quite efficient but is there more pythonic way or perhaps more efficient way
|
there are couple of things you could improve you are performing two loops one over the original dict and then again over the result dict you could build up your results in one step instead you could change to use generator to avoid constructing the whole list up front use list unique mapping items to convert to full list if you need it there is no need to store the value when just checking for duplicates you can use set instead you are recreating dictionary for each element rather than returning the original this may actually be needed eg you are modifying them and do not want to touch the original but if not its more efficient to use the dictionaries already created here is an implementation def unique mapping items set for res in items if res id not in yield res add res id
|
QA
|
what is the best way to open file for exclusive access in python what is the most elegant way to solve this open file for reading but only if it is not already opened for writing open file for writing but only if it is not already opened for reading or writing the built in functions work like this path scr txt file open path print file open file scr txt mode at file open path print file open file scr txt mode at file write file write file close scr txt now contains file close scr txt was overwritten and now contains on windows python the solution should work inside the same process like in the example above as well as when another process has opened the file it is preferred if crashing program will not keep the lock open
|
do not think there is fully crossplatform way on unix the fcntl module will do this for you however on windows which assume you are by the paths you will need to use the win file module fortunately there is portable implementation portalocker using the platform appropriate method at the python cookbook to use it open the file and then call portalocker lock file flags where flags are portalocker lock ex for exclusive write access or lock sh for shared read access
|
QA
|
from import versus import have seen some python programmers use the following style fairly consistently we will call it style import some module use some module some identifier in various places for support of this style you can cite the explicit is better than implicit maxim have seen other programmers use this style style from some module import some identifier use some identifier in various places the primary benefit that see in style is maintainability especially with duck typing ideals may want to swap some module for some other module also feel style wins points with the readability counts maxim although tend to disagree one can always argue that search and replace is just as good an option when using the first style addendum it was noted that you could use as to solve the switch from some module to some other module in style forgot to mention that it is also common to decide to implement some identifier in your current module which makes creation of an equivalent some module container slightly awkward
|
with the existence of the following syntax import some other module as some module the maintainability argument of style is no longer relevant tend to use style normally find that explicitly reference the imported package name only few times in typical python program everything else is methods on the object which of course do not need to reference the imported package
|
QA
|
from import versus import have seen some python programmers use the following style fairly consistently we will call it style import some module use some module some identifier in various places for support of this style you can cite the explicit is better than implicit maxim have seen other programmers use this style style from some module import some identifier use some identifier in various places the primary benefit that see in style is maintainability especially with duck typing ideals may want to swap some module for some other module also feel style wins points with the readability counts maxim although tend to disagree one can always argue that search and replace is just as good an option when using the first style addendum it was noted that you could use as to solve the switch from some module to some other module in style forgot to mention that it is also common to decide to implement some identifier in your current module which makes creation of an equivalent some module container slightly awkward
|
usually use threshold to decide this if want to use lot of things within some module will use import some module as sm sm whatever if there is only one or two things need from some module import whatever whatever that is assuming do not need whatever from some other module of course tend to use the as clause on the imports so that can reduce my typing and substitue another module quite easily in the future
|
QA
|
from import versus import have seen some python programmers use the following style fairly consistently we will call it style import some module use some module some identifier in various places for support of this style you can cite the explicit is better than implicit maxim have seen other programmers use this style style from some module import some identifier use some identifier in various places the primary benefit that see in style is maintainability especially with duck typing ideals may want to swap some module for some other module also feel style wins points with the readability counts maxim although tend to disagree one can always argue that search and replace is just as good an option when using the first style addendum it was noted that you could use as to solve the switch from some module to some other module in style forgot to mention that it is also common to decide to implement some identifier in your current module which makes creation of an equivalent some module container slightly awkward
|
believe in newer versions of python must check my facts you can even do import some other module as some module so you could still go with style and swap in different module later on think it generally maps to how much you want to clutter up your namespace will you just be using one or two names in the module or all of them from import is not allways bad just generally
|
QA
|
from import versus import have seen some python programmers use the following style fairly consistently we will call it style import some module use some module some identifier in various places for support of this style you can cite the explicit is better than implicit maxim have seen other programmers use this style style from some module import some identifier use some identifier in various places the primary benefit that see in style is maintainability especially with duck typing ideals may want to swap some module for some other module also feel style wins points with the readability counts maxim although tend to disagree one can always argue that search and replace is just as good an option when using the first style addendum it was noted that you could use as to solve the switch from some module to some other module in style forgot to mention that it is also common to decide to implement some identifier in your current module which makes creation of an equivalent some module container slightly awkward
|
find that the notation from some module import some symbol works best in most cases also in case of name clash for the symbol you can use from some module import some symbol as other symbol as the question states it avoids rewriting the module name all the time each time with risk of mistyping it use the syntax import module as other module only in two cases use too many of the module functions objects to import them all the module defines some symbol that may change during execution
|
QA
|
from import versus import have seen some python programmers use the following style fairly consistently we will call it style import some module use some module some identifier in various places for support of this style you can cite the explicit is better than implicit maxim have seen other programmers use this style style from some module import some identifier use some identifier in various places the primary benefit that see in style is maintainability especially with duck typing ideals may want to swap some module for some other module also feel style wins points with the readability counts maxim although tend to disagree one can always argue that search and replace is just as good an option when using the first style addendum it was noted that you could use as to solve the switch from some module to some other module in style forgot to mention that it is also common to decide to implement some identifier in your current module which makes creation of an equivalent some module container slightly awkward
|
prefer to import and then use as much as possible my exception centers on the deeply nested modules in big framework like django their module names tend to get lengthy and their examples all say from django conf import settings to save you typing django conf settings debug everywhere if the module name is deeply nested then the exception is to use from import
|
QA
|
from import versus import have seen some python programmers use the following style fairly consistently we will call it style import some module use some module some identifier in various places for support of this style you can cite the explicit is better than implicit maxim have seen other programmers use this style style from some module import some identifier use some identifier in various places the primary benefit that see in style is maintainability especially with duck typing ideals may want to swap some module for some other module also feel style wins points with the readability counts maxim although tend to disagree one can always argue that search and replace is just as good an option when using the first style addendum it was noted that you could use as to solve the switch from some module to some other module in style forgot to mention that it is also common to decide to implement some identifier in your current module which makes creation of an equivalent some module container slightly awkward
|
personally try not to mess too much with my namespace so in most situations just do import module or import module as mod only real diffrence is when have module with single class that is used lot if had sublclassed list type to add some funcionality there would use from superimprovedlistoverloadedwithfeatures import newlist nl newlist etc
|
QA
|
framework language for new web sites and know will get thousand depends on what you are trying to do answers but seriously there really is no solid information about this online yet here are my assumptions think they are similar for alot of people right now it is now october want to start writing an application for january am willing to use beta code and such but by january would like site that does not have strange problems with that said if language is simply slower than another do not care about those things as long as the issue is linear my main concern is developer productivity will be using linux apache mysql for the application want the power to do things like run scp and ftp client functions with stable libraries only picked those two because they are not web related but at the same time represent pretty common network protocols that any larger app might use technologies like openid and oauth will be used as well experienced web developers are readily available do not have to find people from financial companies and such whatever the choice is is common and will be around for while here is kicker would like to be able to use advanced presentation layer tools languages similar to haml sass definitively want to use jquery will be creating facebook app and at some point doing things like dealing with sms messages iphone apps etc at this point the choices for language are php cake symfony zend python django ruby merb am really between django and merb at this point mostly because everybody else seems to be going that way please do not put any technologies in here that are not made for mainstream know merb is untested mostly but their stated goal is solid platform and it has alot of momentum behind it so am confident that it is workable please do not answer with how great perl is or net for future references these choices were already made debian lenny for converting cpu cycles into something useful trac for project management gliffy for wireframes and such google docs apps for documentation hosted email etc amazon ec for hosting storage cheers adam
|
to get feeling of where the django ecosystem is at currently you might want to check out djangopeople net try djangopeople net us ny for new york state djangogigs com
|
QA
|
framework language for new web sites and know will get thousand depends on what you are trying to do answers but seriously there really is no solid information about this online yet here are my assumptions think they are similar for alot of people right now it is now october want to start writing an application for january am willing to use beta code and such but by january would like site that does not have strange problems with that said if language is simply slower than another do not care about those things as long as the issue is linear my main concern is developer productivity will be using linux apache mysql for the application want the power to do things like run scp and ftp client functions with stable libraries only picked those two because they are not web related but at the same time represent pretty common network protocols that any larger app might use technologies like openid and oauth will be used as well experienced web developers are readily available do not have to find people from financial companies and such whatever the choice is is common and will be around for while here is kicker would like to be able to use advanced presentation layer tools languages similar to haml sass definitively want to use jquery will be creating facebook app and at some point doing things like dealing with sms messages iphone apps etc at this point the choices for language are php cake symfony zend python django ruby merb am really between django and merb at this point mostly because everybody else seems to be going that way please do not put any technologies in here that are not made for mainstream know merb is untested mostly but their stated goal is solid platform and it has alot of momentum behind it so am confident that it is workable please do not answer with how great perl is or net for future references these choices were already made debian lenny for converting cpu cycles into something useful trac for project management gliffy for wireframes and such google docs apps for documentation hosted email etc amazon ec for hosting storage cheers adam
|
my experience with various new technologies over the last ten years leads me to recommend that you make stability of the platform serious criterion it is all well and good developing with the latest and greatest framework but when you find it is moved forward point version and suddenly the way you have done everything is deprecated that can turn out to result in extra unnecessary work this was particularly my experience working with rails little ahead of version for that reason alone would avoid any platform that was not at least at when you start work on it ruby is great to work with and will keep your developer productivity high but if django is the more stable platform would favour that for sure
|
QA
|
from import versus import have seen some python programmers use the following style fairly consistently we will call it style import some module use some module some identifier in various places for support of this style you can cite the explicit is better than implicit maxim have seen other programmers use this style style from some module import some identifier use some identifier in various places the primary benefit that see in style is maintainability especially with duck typing ideals may want to swap some module for some other module also feel style wins points with the readability counts maxim although tend to disagree one can always argue that search and replace is just as good an option when using the first style addendum it was noted that you could use as to solve the switch from some module to some other module in style forgot to mention that it is also common to decide to implement some identifier in your current module which makes creation of an equivalent some module container slightly awkward
|
there are uses for both cases so do not think this is an either or issue would consider using from module import when there are fairly small number of things to import the purpose of the functions imported is obvious when divorced from the module name if the names are fairly generic they may clash with others and tell you little eg seeing remove tells you little but os remove will probably hint that you are dealing with files the names do not clash similar to the above but more important never do something like from os import open import module as renamed module has the advantage that it gives bit more context about what is being called when you use it it has the disadvantage that this is bit more cluttered when the module is not really giving more information and is slightly less performant lookups instead of it also has advantages when testing however eg replacing os open with mock object without having to change every module and should be used when using mutable modules import config config dburl sqlite test db if in doubt would always go with the import module style
|
QA
|
splitting semicolon separated string to dictionary in python have string that looks like this name value name value name value is there built in class function in python that will take that string and construct dictionary as though had done this dict name value name value name value have looked through the modules available but cannot seem to find anything that matches thanks do know how to make the relevant code myself but since such smallish solutions are usually mine fields waiting to happen ie someone writes name value etc then usually prefer some pre tested function will do it myself then
|
there is no builtin but you can accomplish this fairly simply with generator comprehension name value name value name value dict item split for item in split edit from your update you indicate you may need to handle quoting this does complicate things depending on what the exact format you are looking for is what quote chars are accepted what escape chars etc you may want to look at the csv module to see if it can cover your format here is an example note that the api is little clunky for this example as csv is designed to iterate through sequence of records hence the next calls am making to just look at the first line adjust to suit your needs name value name value name value dict csv reader item delimiter quotechar next for item in csv reader delimiter quotechar next name value name value name value depending on the exact structure of your format you may need to write your own simple parser however
|
QA
|
regular expression to match start of filename and filename extension what is the regular expression to match strings in this case file names that start with run and have filename extension of py the regular expression should match any of the following runfoo py runbar py run py it should not match myrunfoo py runbar py run txt the sql equivalent of what am looking for is like run py
|
you do not need regular expression you can use glob which takes wildcards run py for example to get those files in your current directory import os glob files glob glob join os getcwd run py
|
QA
|
configuration file with list of key value pairs in python have python script that analyzes set of error messages and checks for each message if it matches certain pattern regular expression in order to group these messages for example file does not exist and file does not exist would match file does not exist and be accounted as two occurrences of file not found category as the number of patterns and categories is growing would like to put these couples regular expression display string in configuration file basically dictionary serialization of some sort would like this file to be editable by hand so am discarding any form of binary serialization and also would rather not resort to xml serialization to avoid problems with characters to escape and so on do you have any idea of what could be good way of accomplishing this update thanks to daren thomas and federico ramponi but cannot have an external python file with possibly arbitrary code
|
think you want the configparser module in the standard library it reads and writes ini style files the examples and documentation in the standard documentation have linked to are very comprehensive
|
QA
|
configuration file with list of key value pairs in python have python script that analyzes set of error messages and checks for each message if it matches certain pattern regular expression in order to group these messages for example file does not exist and file does not exist would match file does not exist and be accounted as two occurrences of file not found category as the number of patterns and categories is growing would like to put these couples regular expression display string in configuration file basically dictionary serialization of some sort would like this file to be editable by hand so am discarding any form of binary serialization and also would rather not resort to xml serialization to avoid problems with characters to escape and so on do you have any idea of what could be good way of accomplishing this update thanks to daren thomas and federico ramponi but cannot have an external python file with possibly arbitrary code
|
have heard that configobj is easier to work with than configparser it is used by lot of big projects ipython trac turbogears etc from their introduction configobj is simple but powerful config file reader and writer an ini file round tripper its main feature is that it is very easy to use with straightforward programmer interface and simple syntax for config files it has lots of other features though nested sections subsections to any level list values multiple line values string interpolation substitution integrated with powerful validation system including automatic type checking conversion repeated sections and allowing default values when writing out config files configobj preserves all comments and the order of members and sections many useful methods and options for working with configuration files like the reload method full unicode support
|
QA
|
configuration file with list of key value pairs in python have python script that analyzes set of error messages and checks for each message if it matches certain pattern regular expression in order to group these messages for example file does not exist and file does not exist would match file does not exist and be accounted as two occurrences of file not found category as the number of patterns and categories is growing would like to put these couples regular expression display string in configuration file basically dictionary serialization of some sort would like this file to be editable by hand so am discarding any form of binary serialization and also would rather not resort to xml serialization to avoid problems with characters to escape and so on do you have any idea of what could be good way of accomplishing this update thanks to daren thomas and federico ramponi but cannot have an external python file with possibly arbitrary code
|
if you are the only one that has access to the configuration file you can use simple low level solution keep the dictionary in text file as list of tuples regexp message exactly as if it was python expression file does not exist file not found user not authorized authorization error in your code load it then eval it and compile the regexps in the result open messages py messages eval read caution you must be sure of what is in that file close messages re compile for in messages and you end up with list of tuples compiled regexp message
|
QA
|
extracting unique items from list of mappings he re an interesting problem that looks for the most pythonic solution suppose have list of mappings id id url url some ids in the list are duplicate and want to create new list with all the duplicates removed came up with the following function def unique mapping map for res in map res id res url return id id url id for id in suppose it is quite efficient but is there more pythonic way or perhaps more efficient way
|
think this can be made simpler still dictionaries do not tolerate duplicate keys make your list of mappings into dictionary of mappings this will remove duplicates somelistofdicts url http id url http id url http id dict id for in somelistofdicts values url http id url http id
|
QA
|
configuration file with list of key value pairs in python have python script that analyzes set of error messages and checks for each message if it matches certain pattern regular expression in order to group these messages for example file does not exist and file does not exist would match file does not exist and be accounted as two occurrences of file not found category as the number of patterns and categories is growing would like to put these couples regular expression display string in configuration file basically dictionary serialization of some sort would like this file to be editable by hand so am discarding any form of binary serialization and also would rather not resort to xml serialization to avoid problems with characters to escape and so on do you have any idea of what could be good way of accomplishing this update thanks to daren thomas and federico ramponi but cannot have an external python file with possibly arbitrary code
|
sometimes just write python module file called config py or something with following contents config name hello see world this can then be read like so from config import config config name config see easy
|
QA
|
is there python package to interface with ms cluster need to write couple of python scripts to automate the installation of microsoft cluster ressources more specifically will need to query ms cluster to be able to get list of ressources with their parameters and also need to be able to create resources and set their parameters is someone knows if there is package module or even some sample scripts using mark hammond pywin packages
|
ok tried it this way via pythonwin used the com makepy utility generated python interface for mscluster cluster in order to have nice introspection in ipython then localy on my server do the following import win client mscluster win client disptach mscluster cluster cluster mscluster open and got the following exception class pywintypes com error exception occurred none none none none if do cluster mscluster open insert here cluster name then got no error but cluster is in fact none any advice
|
QA
|
configuration file with list of key value pairs in python have python script that analyzes set of error messages and checks for each message if it matches certain pattern regular expression in order to group these messages for example file does not exist and file does not exist would match file does not exist and be accounted as two occurrences of file not found category as the number of patterns and categories is growing would like to put these couples regular expression display string in configuration file basically dictionary serialization of some sort would like this file to be editable by hand so am discarding any form of binary serialization and also would rather not resort to xml serialization to avoid problems with characters to escape and so on do you have any idea of what could be good way of accomplishing this update thanks to daren thomas and federico ramponi but cannot have an external python file with possibly arbitrary code
|
typically do as daren suggested just make your config file python script patterns file does not exist file not found user not found authorization error then you can use it as import config for pattern in config patterns if re search pattern log message print config patterns pattern this is what django does with their settings file by the way
|
QA
|
from import versus import have seen some python programmers use the following style fairly consistently we will call it style import some module use some module some identifier in various places for support of this style you can cite the explicit is better than implicit maxim have seen other programmers use this style style from some module import some identifier use some identifier in various places the primary benefit that see in style is maintainability especially with duck typing ideals may want to swap some module for some other module also feel style wins points with the readability counts maxim although tend to disagree one can always argue that search and replace is just as good an option when using the first style addendum it was noted that you could use as to solve the switch from some module to some other module in style forgot to mention that it is also common to decide to implement some identifier in your current module which makes creation of an equivalent some module container slightly awkward
|
tend to use only few members of each module so there is lot of from john import cleese from terry import jones gilliam in my code will import whole modules such as os or wx if expect to be using most of the module and the module name is short will also import whole modules if there is name conflict or want to remind the reader what that function is associated with import michael import sarah import wave gov speech wave open sarah palin speechfile parrot sketch wave open michael palin justresting could use from wave import open as wave open but figure that wave open will be more familiar to the reader
|
QA
|
counting array elements in python how can count the number of elements in an array because contrary to logic array count string does not count all the elements in the array it just searches for the number of occurrences of string
|
the method len returns the number of elements in the list syntax len myarray eg myarray len myarray output
|
QA
|
counting array elements in python how can count the number of elements in an array because contrary to logic array count string does not count all the elements in the array it just searches for the number of occurrences of string
|
or myarray len if you want to be oopy len myarray is lot easier to type
|
QA
|
how to make parts of website under ssl and the rest not need to create cherrypy main page that has login area want the login area to be secure but the rest of the page should not be so how can do this in cherrypy ideally any suggestions will be compatible with http tools cherrypy org wiki authenticationandaccessrestrictions thanks
|
this is commonly considered bad idea the primary reason is that it confuses most people due to the website identity markers appearing in just about every current browsers url area
|
QA
|
how to make parts of website under ssl and the rest not need to create cherrypy main page that has login area want the login area to be secure but the rest of the page should not be so how can do this in cherrypy ideally any suggestions will be compatible with http tools cherrypy org wiki authenticationandaccessrestrictions thanks
|
assuming you only want parts of the actual page to be secure you should create an iframe pointing to https source however this shows secure and non secure items on page warning to the user
|
QA
|
base binary representation using python building on how do you express binary literals in python was thinking about sensible intuitive ways to do that programming chestnut of displaying integers in base form this is the best came up with but would like to replace it with better algorithm or at least one that should have screaming fast performance def num bin places def bit at find the bit at place for number two using bitshift will have exactly one bit set at place two binary composition will be one where both numbers have at that bit this can only happen at position will yield two if has at bit return int bits bit at for in xrange places return join str for in bits or more consisely return join str int for in xrange places
|
for best efficiency you generally want to process more than single bit at time you can use simple method to get fixed width binary representation eg def bin width return join str for in xrange width bin will now give zero padded representation of lower bits this can be used to build lookup table allowing your converter to process bits at time or more if you want to devote the memory to it conv table bin for in range then you can use this in your real function stripping off leading zeroes when returning it have also added handling for signed numbers as without it you will get an infinite loop negative integers conceptually have an infinite number of set sign bits def bin if return special case do not strip leading zero if no other digits elif sign else sign while append conv table xff return sign join reversed lstrip edit changed code to handle signed integers edit here are some timing figures of the various solutions bin is the function above constantin bin is from constantin answer and num bin is the original version out of curiosity also tried bit lookup table variant of the above bin below and tried out python builtin bin function all timings were for runs using an bit pattern num bits bin bin constantin bin num bin python bin as you can see when processing long values using large chunks really pays off but nothing beats the low level code of python builtin which bizarrely seems consistently faster at bits than using bit lookup table improves things but probably is not worth it unless you really need it as it uses up large chunk of memory and can introduce small but noticalbe startup delay to precompute the table
|
QA
|
how do capture an mp stream with python what is the best way of capturing an mp stream coming off of http and saving it to disk with python thus far have tried target open target path conn urllib urlopen stream url while true target write conn read buf size this gives me data but its garbled or will not play in mp players
|
if you are on windows you might accidentally be doing crlf conversions corrupting the binary data try opening target in binary mode target open target path wb
|
QA
|
configuration file with list of key value pairs in python have python script that analyzes set of error messages and checks for each message if it matches certain pattern regular expression in order to group these messages for example file does not exist and file does not exist would match file does not exist and be accounted as two occurrences of file not found category as the number of patterns and categories is growing would like to put these couples regular expression display string in configuration file basically dictionary serialization of some sort would like this file to be editable by hand so am discarding any form of binary serialization and also would rather not resort to xml serialization to avoid problems with characters to escape and so on do you have any idea of what could be good way of accomplishing this update thanks to daren thomas and federico ramponi but cannot have an external python file with possibly arbitrary code
|
you have two decent options python standard config file format using configparser yaml using library like pyyaml the standard python configuration files look like ini files with sections and key value or key value pairs the advantages to this format are no third party libraries necessary simple familiar file format yaml is different in that it is designed to be human friendly data serialization format rather than specifically designed for configuration it is very readable and gives you couple different ways to represent the same data for your problem you could create yaml file that looks like this file does not exist file not found user not found authorization error or like this file does not exist file not found user not found authorization error using pyyaml could not be simpler import yaml errors yaml load open my yaml at this point errors is python dictionary with the expected format yaml is capable of representing more than dictionaries if you prefer list of pairs use this format file does not exist file not found user not found authorization error or file does not exist file not found user not found authorization error which will produce list of lists when yaml load is called one advantage of yaml is that you could use it to export your existing hard coded data out to file to create the initial version rather than cut paste plus bunch of find replace to get the data into the right format the yaml format will take little more time to get familiar with but using pyyaml is even simpler than using configparser with the advantage is that you have more options regarding how your data is represented using yaml either one sounds like it will fit your current needs configparser will be easier to start with while yaml gives you more flexibilty in the future if your needs expand best of luck
|
QA
|
how to make python command line program autocomplete arbitrary things not interpreter am aware of how to setup autocompletion of python objects in the python interpreter on unix google shows many hits for explanations on how to do this unfortunately there are so many references to that it is difficult to find what need to do which is slightly different need to know how to enable tab auto completion of arbitrary items in command line program written in python my specific use case is command line python program that needs to send emails want to be able to autocomplete email addresses have the addresses on disk when the user types part of it and optionally presses the tab key do not need it to work on windows or mac just linux
|
use python readline bindings for example import readline def completer text state options for in commands if startswith text if state len options return options state else return none readline parse and bind tab complete readline set completer completer the official module docs are not much more detailed see the readline docs for more info
|
QA
|
how to make python command line program autocomplete arbitrary things not interpreter am aware of how to setup autocompletion of python objects in the python interpreter on unix google shows many hits for explanations on how to do this unfortunately there are so many references to that it is difficult to find what need to do which is slightly different need to know how to enable tab auto completion of arbitrary items in command line program written in python my specific use case is command line python program that needs to send emails want to be able to autocomplete email addresses have the addresses on disk when the user types part of it and optionally presses the tab key do not need it to work on windows or mac just linux
|
follow the cmd documentation and you will be fine import cmd addresses here blubb com foo bar com whatever wherever org class mycmd cmd cmd def do send self line pass def complete send self text line start index end index if text return address for address in addresses if address startswith text else return addresses if name main my cmd mycmd my cmd cmdloop output for tab tab send tab tab tab cmd help send cmd send foo bar com here blubb com whatever wherever org cmd send foo bar com cmd
|
QA
|
reading writing ms word files in python is it possible to read and write word and files in python without using com object know that can open file doc write text close but word will read it as an html file not native doc file
|
doc word in this case and docx word are different formats where the latter is usually just an archive of xml and image files would imagine that it is very possible to write to docx files by manipulating the contents of those xml files however do not see how you could read and write to doc file without some type of com component interface
|
QA
|
reading writing ms word files in python is it possible to read and write word and files in python without using com object know that can open file doc write text close but word will read it as an html file not native doc file
|
would look into ironpython which intrinsically has access to windows office apis because it runs on net runtime
|
QA
|
what is the best way to open file for exclusive access in python what is the most elegant way to solve this open file for reading but only if it is not already opened for writing open file for writing but only if it is not already opened for reading or writing the built in functions work like this path scr txt file open path print file open file scr txt mode at file open path print file open file scr txt mode at file write file write file close scr txt now contains file close scr txt was overwritten and now contains on windows python the solution should work inside the same process like in the example above as well as when another process has opened the file it is preferred if crashing program will not keep the lock open
|
here is start on the win half of portable implementation that does not need seperate locking mechanism requires the python for windows extensions to get down to the win api but that is pretty much mandatory for python on windows already and can alternatively be done with ctypes the code could be adapted to expose more functionality if it is needed such as allowing file share read rather than no sharing at all see also the msdn documentation for the createfile and writefile system calls and the article on creating and opening files as has been mentioned you can use the standard fcntl module to implement the unix half of this if required import winerror pywintypes win file class lockerror standarderror pass class writelockedfile object using win api to achieve something similar to file path wb could be adapted to handle other modes as well def init self path try self handle win file createfile path win file generic write none win file open always win file file attribute normal none except pywintypes error if winerror error sharing violation raise lockerror raise def close self self handle close def write self str win file writefile self handle str here is how your example from above behaves path scr txt file writelockedfile path file writelockedfile path doctest ignore exception detail traceback most recent call last lockerror file write file close print file path read
|
QA
|
django admin interface inlines placement want to be able to place an inline inbetween two different fields in fieldset you can already do this with foreignkeys figured that inlining the class wanted and defining it to get extra forms would do the trick but apparently get class has no foreignkey to class error is this not something that is supported in django if so how would go about fixing the problem if there is not pre existing solution in models py class place models model name models charfield max length address models charfield max length class owner models model name models charfield max length place models foreignkey place background models textfield license expiration models datetimefield license expiration in admin py class placeinline admin tabularinline model place extra class owneradmin admin modeladmin fieldsets none fields background place license expiration inlines placeinline
|
it seems to be impossible in django admin site itself you should not include inlined fields in fields at all but you can use js to move inlined fields wherever you want
|
QA
|
counting array elements in python how can count the number of elements in an array because contrary to logic array count string does not count all the elements in the array it just searches for the number of occurrences of string
|
len is built in function that calls the given container object len member function to get the number of elements in the object functions encased with double underscores are usually special methods implementing one of the standard interfaces in python container number etc special methods are used via syntactic sugar object creation container indexing and slicing attribute access built in functions etc using obj len would not be the correct way of using the special method but do not see why the others were modded down so much
|
QA
|
framework language for new web sites and know will get thousand depends on what you are trying to do answers but seriously there really is no solid information about this online yet here are my assumptions think they are similar for alot of people right now it is now october want to start writing an application for january am willing to use beta code and such but by january would like site that does not have strange problems with that said if language is simply slower than another do not care about those things as long as the issue is linear my main concern is developer productivity will be using linux apache mysql for the application want the power to do things like run scp and ftp client functions with stable libraries only picked those two because they are not web related but at the same time represent pretty common network protocols that any larger app might use technologies like openid and oauth will be used as well experienced web developers are readily available do not have to find people from financial companies and such whatever the choice is is common and will be around for while here is kicker would like to be able to use advanced presentation layer tools languages similar to haml sass definitively want to use jquery will be creating facebook app and at some point doing things like dealing with sms messages iphone apps etc at this point the choices for language are php cake symfony zend python django ruby merb am really between django and merb at this point mostly because everybody else seems to be going that way please do not put any technologies in here that are not made for mainstream know merb is untested mostly but their stated goal is solid platform and it has alot of momentum behind it so am confident that it is workable please do not answer with how great perl is or net for future references these choices were already made debian lenny for converting cpu cycles into something useful trac for project management gliffy for wireframes and such google docs apps for documentation hosted email etc amazon ec for hosting storage cheers adam
|
all of them will get the job done use the one that you and your team are most familiar with this will have far greater impact on the delivery times and stability of your app than any of the other variables
|
QA
|
framework language for new web sites and know will get thousand depends on what you are trying to do answers but seriously there really is no solid information about this online yet here are my assumptions think they are similar for alot of people right now it is now october want to start writing an application for january am willing to use beta code and such but by january would like site that does not have strange problems with that said if language is simply slower than another do not care about those things as long as the issue is linear my main concern is developer productivity will be using linux apache mysql for the application want the power to do things like run scp and ftp client functions with stable libraries only picked those two because they are not web related but at the same time represent pretty common network protocols that any larger app might use technologies like openid and oauth will be used as well experienced web developers are readily available do not have to find people from financial companies and such whatever the choice is is common and will be around for while here is kicker would like to be able to use advanced presentation layer tools languages similar to haml sass definitively want to use jquery will be creating facebook app and at some point doing things like dealing with sms messages iphone apps etc at this point the choices for language are php cake symfony zend python django ruby merb am really between django and merb at this point mostly because everybody else seems to be going that way please do not put any technologies in here that are not made for mainstream know merb is untested mostly but their stated goal is solid platform and it has alot of momentum behind it so am confident that it is workable please do not answer with how great perl is or net for future references these choices were already made debian lenny for converting cpu cycles into something useful trac for project management gliffy for wireframes and such google docs apps for documentation hosted email etc amazon ec for hosting storage cheers adam
|
have to preface this with my agreeing with orion edwards choose the one your team is most familiar with however also have to note the curious lack of asp net languages in your list not to provoke the great zealot army but where is the beef net is stable rapid development platform and the labor pool is growing daily vb net and are transportable skill sets and that can mean lot when you are building team of developers to work on diverse set of tasks net also allows you to separate your presentation layer from your backend code like other languages but also allows you to expose that backend code as web service for things like your iphone and facebook applications take every suggestion with grain of salt and pick what suits the application best do your research and design for function and not the zealots disclaimer once php coldfusion and perl developer flex zealot and adobe lover now writing enterprise net applications do not forget mono which will let you run net under nix not that am saying it will be perfect just playing devil advocate
|
QA
|
ocsp libraries for python java going back to my previous question on ocsp does anybody know of reliable ocsp libraries for python java and need client ocsp functionality as will be checking the status of certs against an ocsp responder so responder functionality is not that important thanks
|
openssl is the most widely used product for ocsp in it is quite reliable although incredibly obtuse would recommend looking at apps ocsp for pretty good example of how to make ocsp requests and validate responses vista and server have built in ocsp support in capi check out certverifyrevocation
|
QA
|
how can in python iterate over multiple lists at once cleanly if am making simple grid based game for example might have few lists one might be for terrain another might be for objects etc unfortunately when need to iterate over the lists and have the contents of square in one list affect part of another list have to do something like this for in range len alist for in range len alist if alist iswhatever blist dosomething is there nicer way to do something like this
|
you could zip them ie for row row in zip alist blist for item item in zip row row if item iswhatever item dosomething however the overhead of zipping and iterating over the items may be higher than your original method if you rarely actually use the item ie item iswhatever is usually false you could use itertools izip instead of zip to reduce the memory impact of this but its still probably going to be slightly slower unless you always need the item alternatively consider using list instead so terrain for cell is at objects at etc or even combine the objects so you can do terrain object etc edit dzinx timings actually show that the impact of the extra check for item is not really significant next to the performance penalty of re looking up by index so the above using izip seems to be fastest have now given quick test for the approach as well and it seems faster still so if you can store your data in that form it could be both simpler and faster to access here is an example of using it initialise list alist args args for in xrange width for in xrange height process it for row in xlist for in row if iswhatever dosomething here are my timings for loops using array with various proportions of iswhatever being true are chance iswhatever is true method izip original
|
QA
|
how can in python iterate over multiple lists at once cleanly if am making simple grid based game for example might have few lists one might be for terrain another might be for objects etc unfortunately when need to iterate over the lists and have the contents of square in one list affect part of another list have to do something like this for in range len alist for in range len alist if alist iswhatever blist dosomething is there nicer way to do something like this
|
are you sure that the objects in the two matrices you are iterating in parallel are instances of conceptually distinct classes what about merging the two classes ending up with matrix of objects that contain both iswhatever and dosomething
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.