prefix
stringclasses 1
value | input_text
stringlengths 19
27.3k
⌀ | target_text
stringlengths 2
24.8k
⌀ |
---|---|---|
QA
|
unexpected list comprehension behaviour in python believe am getting bitten by some combination of nested scoping rules and list comprehensions jeremy hylton blog post is suggestive about the causes but do not really understand cpython implementation well enough to figure out how to get around this here is an overcomplicated example if people have simpler one that demos it would like to hear it the issue the list comprehensions using next are filled with the result from the last iteration edit the problem what exactly is going on with this and how do fix this do have to use standard for loop clearly the function is running the correct number of times but the list comprehensions end up with the final value instead of the result of each loop some hypotheses generators lazy filling of list comprehensions code import itertools def digit digit list false for in xrange digit list true return itertools cycle digit list digit next for in range this list comprehension works as expected true false false false false class counter object def init self self counter digit for ii in range self totalcount self display def next self self totalcount self display self counter next print self totalcount self display return self display def next self args self cycle self totalcount print self totalcount self display return self display def cycle self digit first self counter digit next print digit first print self display self display digit if first and digit self cycle digit counter next for in range next for in range output in next for in range out in next for in range out this should be or similar
|
the problem is that with return self display you return reference to this list not copy so what you end up with is list where each element is reference to self display to illustrate look at the following append you probably want to use something like return self display
|
QA
|
need some help with cursor event handling in python tkinter am building code in which would like to be able to generate an event when the user changes the focus of the cursor from an entry widget to anywhere for example another entry widget button so far only came out with the idea to bind to tab and mouse click although if bind the mouse click to the entry widget only get mouse events when inside the entry widget how can accomplish to generate events for when widget loses cursor focus any help will be much appreciated thanks in advance william
|
the events focusin and focusout are what you want run the following example and you will see you get focus in and out bindings whether you click or press tab or shift tab when focus is in one of the entry widgets from tkinter import def main global text root tk label root text field label root text field text root height width entry root entry root grid row column sticky grid row column sticky ew grid row column sticky grid row column sticky ew grid row column columnspan sticky nw root grid columnconfigure weight root grid rowconfigure weight root bind class entry focusout focusouthandler root bind class entry focusin focusinhandler text root mainloop def focusinhandler event text insert end focusin event widget text see end def focusouthandler event text insert end focusout event widget text see end if name main main
|
QA
|
help with event in python entry widget am writing some code in python and am having trouble when trying to retrieve content of an entry widget the thing is want to limit the characters that can be typed so am trying to clear the entry widget when reach the specific number of characters in this case but it looks like always miss the last typed character added the lost character in print to show here is the sample code from tkinter import class sampleframe def init self master self frame frame master self frame pack def get frame self return self frame class sampleclass def init self master self alabel label master text alabel width self alabel pack side left self aentry entry master width self aentry bind key lambda event self callback event self aentry self aentry pack side left def callback self event widgetname self value widgetname get event char print self value if len self value widgetname delete root tk asampleframe sampleframe root asampleclass sampleclass asampleframe get frame root mainloop any help will be much appreciated thanks in advance
|
to be bit more specific tk widgets have what are called bindtags when an event is processed each bindtag on the widget is considered in order to see if it has binding widget by default will have as its bindtags the widget the widget class the root widget and all thus bindings to the widget will occur before the default bindings once your binding has been processed you can prevent any further bindtags from being considered by returning break the ramifications are this if you make binding on the widget the class root window and all bindings may fire as well in addition any binding you attach to the widget fires before the class binding which is where the default behavior eg the insertion of character happens it is important to be aware of that in situations where you may want to handle the event after the default behavior rather than before
|
QA
|
get bound event handler in tkinter after bind method to an event of tkinter element is there way to get the method back root tkinter tk frame tkinter frame root width height frame bind button lambda pprint click function needed frame pack bound event method frame
|
the standard way to do this in tcl tk is trivial you use the same bind command but without the final argument bind button dosomething puts the function is bind button the function is dosomething you can do something similar with tkinter but the results are unfortunately not quite as usable bind button dosomething bind button if dosomething break break obviously tkinter is doing lot of juggling below the covers one solution would be to write little helper procedure that remembers this for you def bindwidget widget event func none set or retrieve the binding for an event on widget if not widget dict has key bindings widget bindings dict if func widget bind event func widget bindings event func else return widget bindings setdefault event none you would use it like this entry print before binding for button bindwidget button bindwidget button dosomething print after binding for button bindwidget button when run the above code get before binding for button none after binding for button function dosomething at xb as final caveat do not use tkinter much so am not sure what the ramifications are of dynamically adding an attribute to widget instance it seems to be harmless but if not you can always create global dictionary to keep track of the bindings
|
QA
|
how can generate report file odf pdf from django view would like to generate report file from view template in django preferred file formats would be openoffice odf or pdf what is the best way to do this do want to reuse the page layout defined in the template possibly by redefining some blocks in derived template ideally the report should be inserted into an existing template file so can provide the overall page layout headers and footer in the generated output format
|
try reportlab for pdf output http www reportlab org
|
QA
|
how does one put link url to the web site home page in django in django templates is there variable in the context base url root url or media url that one can use to link to the home url of project if django is running in the root of project the variable let us call it are in template would be if the root url is sub folder http host the variable are would be or http host it seems painfully simple but cannot find an answer thank you
|
always use something like href assuming your home is at the root of course seem to recall looking this up once and could not find django variable for this path at any rate seemed pretty easy anyway
|
QA
|
how does one put link url to the web site home page in django in django templates is there variable in the context base url root url or media url that one can use to link to the home url of project if django is running in the root of project the variable let us call it are in template would be if the root url is sub folder http host the variable are would be or http host it seems painfully simple but cannot find an answer thank you
|
you could give the url configuration which you are using to handle the home page name and use that urls py from django conf urls defaults import urlpatterns patterns myproject views url index name index templates href url index this note in the django book has some tips about deploying your applications to subdirectory http www djangobook com en chapter cn
|
QA
|
django forms how to use prefix parameter say have form like class generalform forms form field forms integerfield required false field forms integerfield required false and want to show it twice on page within one form tag each time with different prefix rest of page form generalform data prefix form as table generalform data prefix form as table input type submit form rest of page when the user submits this how do get the submitted form back into two separate forms to do validation and redisplay it this was the only documentation could find and it is peckish
|
you process each form as you normally would ensuring that you create instances which have the same prefixes as those used to generate the form initially here is slightly awkward example using the form you have given as do not know what the exact use case is def some view request if request method post form generalform request post prefix form form generalform request post prefix form if all form is valid form is valid pass do stuff with the forms else form generalform prefix form form generalform prefix form return render to response some template html form form form form here is some real world sample code which demonstrates processing forms using the prefix http collingrady wordpress com editing multiple objects in django with newforms
|
QA
|
elegant structured text file parsing need to parse transcript of live chat conversation my first thought on seeing the file was to throw regular expressions at the problem but was wondering what other approaches people have used put elegant in the title as have previously found that this type of task has danger of getting hard to maintain just relying on regular expressions the transcripts are being generated by www providesupport com and emailed to an account then extract plain text transcript attachment from the email the reason for parsing the file is to extract the conversation text for later but also to identify visitors and operators names so that the information can be made available via crm here is an example of transcript file chat transcript visitor random website visitor operator milton company initech started oct finished oct random website visitor where do get the cover sheet for the tps report there are no operators available at the moment if you would like to leave message please type it in the input field below and click send button call accepted by operator milton currently in room milton random website visitor milton excuse me you believe you have my stapler random website visitor really just need the cover sheet okay milton it is not okay because if they take my stapler then will will will set the building on fire random website visitor oh found it thanks anyway random website visitor is now off line and may not reply currently in room milton milton well ok but that is the last straw milton has left the conversation currently in room room is empty visitor details your name random website visitor your question where do get the cover sheet for the tps report ip address host name referrer unknown browser os mozilla compatible msie windows nt net clr infopath net clr
|
have used paul mcguire pyparsing class library and continue to be impressed by it in that it is well documented easy to get started and the rules are easy to tweak and maintain by the way the rules are expressed in your python code it certainly appears that the log file has enough regularity to parse each line as stand alone unit
|
QA
|
how does one put link url to the web site home page in django in django templates is there variable in the context base url root url or media url that one can use to link to the home url of project if django is running in the root of project the variable let us call it are in template would be if the root url is sub folder http host the variable are would be or http host it seems painfully simple but cannot find an answer thank you
|
in your admin go to sites and set the domain pass context instance requestcontext request to the templates in question now use site url in any of those templates and you are golden chapter of the django book has more information than you will need regading that context processor bit
|
QA
|
python disk based dictionary was running some dynamic programming code trying to brute force disprove the collatz conjecture and was using dict to store the lengths of the chains had already computed obviously it ran out of memory at some point is there any easy way to use some variant of dict which will page parts of itself out to disk when it runs out of room obviously it will be slower than an in memory dict and it will probably end up eating my hard drive space but this could apply to other problems that are not so futile realized that disk based dictionary is pretty much database so manually implemented one using sqlite but did not do it in any smart way and had it look up every element in the db one at time it was about slower is the smartest way to just create my own set of dicts keeping only one in memory at time and paging them out in some efficient manner
|
hash on disk is generally addressed with berkeley db or something similar several options are listed in the python data persistence documentation you can front it with an in memory cache but would test against native performance first with operating system caching in place it might come out about the same
|
QA
|
python disk based dictionary was running some dynamic programming code trying to brute force disprove the collatz conjecture and was using dict to store the lengths of the chains had already computed obviously it ran out of memory at some point is there any easy way to use some variant of dict which will page parts of itself out to disk when it runs out of room obviously it will be slower than an in memory dict and it will probably end up eating my hard drive space but this could apply to other problems that are not so futile realized that disk based dictionary is pretty much database so manually implemented one using sqlite but did not do it in any smart way and had it look up every element in the db one at time it was about slower is the smartest way to just create my own set of dicts keeping only one in memory at time and paging them out in some efficient manner
|
last time was facing problem like this rewrote to use sqlite rather than dict and had massive performance increase that performance increase was at least partially on account of the database indexing capabilities depending on your algorithms ymmv thin wrapper that does sqlite queries in getitem and setitem is not much code to write
|
QA
|
python disk based dictionary was running some dynamic programming code trying to brute force disprove the collatz conjecture and was using dict to store the lengths of the chains had already computed obviously it ran out of memory at some point is there any easy way to use some variant of dict which will page parts of itself out to disk when it runs out of room obviously it will be slower than an in memory dict and it will probably end up eating my hard drive space but this could apply to other problems that are not so futile realized that disk based dictionary is pretty much database so manually implemented one using sqlite but did not do it in any smart way and had it look up every element in the db one at time it was about slower is the smartest way to just create my own set of dicts keeping only one in memory at time and paging them out in some efficient manner
|
you should bring more than one item at time if there is some heuristic to know which are the most likely items to be retrieved next and do not forget the indexes like charles mentions
|
QA
|
python disk based dictionary was running some dynamic programming code trying to brute force disprove the collatz conjecture and was using dict to store the lengths of the chains had already computed obviously it ran out of memory at some point is there any easy way to use some variant of dict which will page parts of itself out to disk when it runs out of room obviously it will be slower than an in memory dict and it will probably end up eating my hard drive space but this could apply to other problems that are not so futile realized that disk based dictionary is pretty much database so manually implemented one using sqlite but did not do it in any smart way and had it look up every element in the db one at time it was about slower is the smartest way to just create my own set of dicts keeping only one in memory at time and paging them out in some efficient manner
|
with little bit of thought it seems like you could get the shelve module to do what you want
|
QA
|
batch renaming of files in directory is there an easy way to rename group of files already contained in directory using python example have directory full of doc files and want to rename them in consistent way doc new doc doc new doc
|
such renaming is quite easy for example with os and glob modules import glob os def rename dir pattern titlepattern for pathandfilename in glob iglob os path join dir pattern title ext os path splitext os path basename pathandfilename os rename pathandfilename os path join dir titlepattern title ext you could then use it in your example like this rename temp xx doc new the above example will convert all doc files in temp xx dir to new doc where is the previous base name of the file without extension
|
QA
|
batch renaming of files in directory is there an easy way to rename group of files already contained in directory using python example have directory full of doc files and want to rename them in consistent way doc new doc doc new doc
|
if you do not mind using regular expressions then this function would give you much power in renaming files import re glob os def renamer files pattern replacement for pathname in glob glob files basename os path basename pathname new filename re sub pattern replacement basename if new filename basename os rename pathname os path join os path dirname pathname new filename so in your example you could do assuming it is the current directory where the files are renamer doc doc new doc but you could also roll back to the initial filenames renamer doc new doc doc and more
|
QA
|
how can you extract hardware id using python how do you extract an hd and bios unique id using python script
|
solutions that come to my mind use win python extensions and call windows apis to do that directly use wmi wrapper for python some wmi interface code for reference edit assumed your os was ms windows
|
QA
|
solving an inequality for minimum value am working on programming problem which boils down to set of an equation and inequality want to solve for the values of that will give the absolute minimum of given the input and lists and and consisting of and am doing the problem at the moment in python but the problem in general is language agnostic clarification update the coefficients are restricted to the set of non negative integers
|
it looks like this is linear programming problem
|
QA
|
solving an inequality for minimum value am working on programming problem which boils down to set of an equation and inequality want to solve for the values of that will give the absolute minimum of given the input and lists and and consisting of and am doing the problem at the moment in python but the problem in general is language agnostic clarification update the coefficients are restricted to the set of non negative integers
|
this looks like linear programming problem the simplex algorithm normally gives good results it basically walks the boundaries of the subspace delimited by the inequalities looking for the optimum think of it visually each inequality denotes half space plane in dimensional space that you have to be on the right side of your utility function is what you are trying to optimize if the space is closed the optimum is going to be at one of the apexes of the closed space if it is open it is possible that the optimum is infinite
|
QA
|
how can you extract hardware id using python how do you extract an hd and bios unique id using python script
|
go get microsoft scriptomatic run it select the appropriate class from the dropdown win bios it will produce the necessary python wmi code for you it will also generate vbscript perl and jscript
|
QA
|
solving an inequality for minimum value am working on programming problem which boils down to set of an equation and inequality want to solve for the values of that will give the absolute minimum of given the input and lists and and consisting of and am doing the problem at the moment in python but the problem in general is language agnostic clarification update the coefficients are restricted to the set of non negative integers
|
you might want to use matlab or mathematica or look at code from numerical recipes in for ideas on how to implement minimization functions the link provided is to the version of the book newer versions are available at amazon
|
QA
|
solving an inequality for minimum value am working on programming problem which boils down to set of an equation and inequality want to solve for the values of that will give the absolute minimum of given the input and lists and and consisting of and am doing the problem at the moment in python but the problem in general is language agnostic clarification update the coefficients are restricted to the set of non negative integers
|
this company has tool to do that sort of thing
|
QA
|
ascii value of character in python how do get the ascii value of character as an int in python
|
you are looking for ord
|
QA
|
ascii value of character in python how do get the ascii value of character as an int in python
|
from here function ord would get the int value of the char and in case you want to convert back after playing with the number function chr does the trick ord chr chr ord would there is also the unichr function returning the unicode character whose ordinal is the unichr argument unichr you unichr you
|
QA
|
solving an inequality for minimum value am working on programming problem which boils down to set of an equation and inequality want to solve for the values of that will give the absolute minimum of given the input and lists and and consisting of and am doing the problem at the moment in python but the problem in general is language agnostic clarification update the coefficients are restricted to the set of non negative integers
|
have look at the wikipedia entry on linear programming the integer programming section is what you are searching for the constraint of the being integers is not an easy one search python libraries for branch bound branch cut and the like do not think they have been implemented in scipy yet other interesting links gnu linear programming kit ibm article on glpk
|
QA
|
open file read it process and write back shortest method in python want to do some basic filtering on file read it do processing write it back am not looking for golfing but want the simplest and most elegant method to achieve this came up with from future import with statement filename or sys argv with open filename as new txt some translation of read open filename write new txt the with statement makes things shorter since do not have to explicitly open and close the file any other ideas
|
this seems to work with open filename as new txt process read truncate write new txt
|
QA
|
open file read it process and write back shortest method in python want to do some basic filtering on file read it do processing write it back am not looking for golfing but want the simplest and most elegant method to achieve this came up with from future import with statement filename or sys argv with open filename as new txt some translation of read open filename write new txt the with statement makes things shorter since do not have to explicitly open and close the file any other ideas
|
would go for elegance different way implement your file reading and filtering operations as generators you will write more lines of code but it will be more flexible maintainable and performant code see david beazley generator tricks for systems programmers which is really important thing for anyone who is writing this kind of code to read
|
QA
|
how can you extract hardware id using python how do you extract an hd and bios unique id using python script
|
on linux look in the proc directory you will have to parse the files to find what you are looking for this might help
|
QA
|
open file read it process and write back shortest method in python want to do some basic filtering on file read it do processing write it back am not looking for golfing but want the simplest and most elegant method to achieve this came up with from future import with statement filename or sys argv with open filename as new txt some translation of read open filename write new txt the with statement makes things shorter since do not have to explicitly open and close the file any other ideas
|
if you are looking for the python equivalent of perl pi here is pretty good one import fileinput for line in fileinput input process line see http www python org doc lib module fileinput html for more done this way you would use your python script in pipe to create the new file myscript py infile txt outfile txt
|
QA
|
passing list while retaining the original so am teaching myself python and am having an issue with lists want to pass my function list and pop items off it while retaining the original list how do make python instance the passed list rather that passing pointer to the original one example def burninate for in range append pop return range burninate print output desired output thanks
|
you can call burninate with copy of the list like this burninate or burninate list the other alternative is to make copy of the list in your method def burninate for in range append pop return range burninate print
|
QA
|
passing list while retaining the original so am teaching myself python and am having an issue with lists want to pass my function list and pop items off it while retaining the original list how do make python instance the passed list rather that passing pointer to the original one example def burninate for in range append pop return range burninate print output desired output thanks
|
slightly more readable way to do the same thing is burninate list here the list constructor creates new list based on
|
QA
|
passing list while retaining the original so am teaching myself python and am having an issue with lists want to pass my function list and pop items off it while retaining the original list how do make python instance the passed list rather that passing pointer to the original one example def burninate for in range append pop return range burninate print output desired output thanks
|
other versions def burninate for in range append return def burninate reverse return and someday you will love list comprehensions def burninate return for in range
|
QA
|
passing list while retaining the original so am teaching myself python and am having an issue with lists want to pass my function list and pop items off it while retaining the original list how do make python instance the passed list rather that passing pointer to the original one example def burninate for in range append pop return range burninate print output desired output thanks
|
more general solution would be to import copy and use copy copy on the parameter
|
QA
|
passing list while retaining the original so am teaching myself python and am having an issue with lists want to pass my function list and pop items off it while retaining the original list how do make python instance the passed list rather that passing pointer to the original one example def burninate for in range append pop return range burninate print output desired output thanks
|
as other answers have suggested you can provide your function with copy of the list as an alternative your function could take copy of the argument def burninate list for in range append pop return basically you need to be clear in your mind and in your documentation whether your function will change its arguments in my opinion functions that return computed values should not change their arguments and functions that change their arguments should not return anything see python sort extend update etc for examples obviously there are exceptions like pop also depending on your particular case you could rewrite the function to avoid using pop or other functions that modify the argument def burninante return return the last three elements in reverse order
|
QA
|
passing list while retaining the original so am teaching myself python and am having an issue with lists want to pass my function list and pop items off it while retaining the original list how do make python instance the passed list rather that passing pointer to the original one example def burninate for in range append pop return range burninate print output desired output thanks
|
burninate lambda
|
QA
|
ascii value of character in python how do get the ascii value of character as an int in python
|
note that ord does not give you the ascii value per se it gives you the numeric value of the character in whatever encoding it is in therefore the result of ord can be if you are using latin or it can raise typeerror if you are using utf it can even return the unicode codepoint instead if you pass it unicode ord you
|
QA
|
what is win con module in python where can find it am building an open source project that uses python and in windows came to the following error message importerror no module named win con the same happened in prebuilt code that it is working except in my computer think this is kind of popular module in python because have saw several messages in other forums but none that could help me have python should have that module already installed is that something of vc thank you for the help got this url http sourceforge net projects pywin but am not sure what to do with the executable
|
this module contains constants related to win programming it is not part of the python release but should be part of the download of the pywin project edit imagine that the executable is an installation program though the last time downloaded pywin it was just zip file
|
QA
|
what is win con module in python where can find it am building an open source project that uses python and in windows came to the following error message importerror no module named win con the same happened in prebuilt code that it is working except in my computer think this is kind of popular module in python because have saw several messages in other forums but none that could help me have python should have that module already installed is that something of vc thank you for the help got this url http sourceforge net projects pywin but am not sure what to do with the executable
|
see the python programming on win for details on this package
|
QA
|
pretty continuous integration for python this is slightly vain question but buildbot output is not particularly nice to look at for example compared to phpundercontrol jenkins hudson cruisecontrol rb and others buildbot looks rather archaic am currently playing with hudson but it is very java centric although with this guide found it easier to setup than buildbot and produced more info basically is there any continuous integration systems aimed at python that produce lots of shiny graphs and the likes update since this time the jenkins project has replaced hudson as the community version of the package the original authors have moved to this project as well jenkins is now standard package on ubuntu debian redhat fedora centos and others the following update is still essentially correct the starting point to do this with jenkins is different update after trying few alternatives think will stick with hudson integrity was nice and simple but quite limited think buildbot is better suited to having numerous build slaves rather than everything running on single machine like was using it setting hudson up for python project was pretty simple download hudson from http hudson ci org run it with java jar hudson war open the web interface on the default address of http localhost go to manage hudson plugins click update or similar install the git plugin had to set the git path in the hudson global preferences create new project enter the repository scm polling intervals and so on install nosetests via easy install if it is not already in the build step add nosetests with xunit verbose check publish junit test result report and set test report xmls to nosetests xml that is all that is required you can setup email notifications and the plugins are worth look few am currently using for python projects sloccount plugin to count lines of code and graph it you need to install sloccount separately violations to parse the pylint output you can setup warning thresholds graph the number of violations over each build cobertura can parse the coverage py output nosetest can gather coverage while running your tests using nosetests with coverage this writes the output to coverage xml
|
we have had great success with teamcity as our ci server and using nose as our test runner teamcity plugin for nosetests gives you count pass fail readable display for failed test that can be mailed you can even see details of the test failures while you stack is running if of course supports things like running on multiple machines and it is much simpler to setup and maintain than buildbot
|
QA
|
python disk based dictionary was running some dynamic programming code trying to brute force disprove the collatz conjecture and was using dict to store the lengths of the chains had already computed obviously it ran out of memory at some point is there any easy way to use some variant of dict which will page parts of itself out to disk when it runs out of room obviously it will be slower than an in memory dict and it will probably end up eating my hard drive space but this could apply to other problems that are not so futile realized that disk based dictionary is pretty much database so manually implemented one using sqlite but did not do it in any smart way and had it look up every element in the db one at time it was about slower is the smartest way to just create my own set of dicts keeping only one in memory at time and paging them out in some efficient manner
|
the shelve module may do it at any rate it should be simple to test instead of self lengths do import shelve self lengths shelve open lengths shelf the only catch is that keys to shelves must be strings so you will have to replace self lengths indx with self lengths str indx am assuming your keys are just integers as per your comment to charles duffy post there is no built in caching in memory but your operating system may do that for you anyway actually that is not quite true you can pass the argument writeback true on creation the intent of this is to make sure storing lists and other mutable things in the shelf works correctly but side effect is that the whole dictionary is cached in memory since this caused problems for you it is probably not good idea
|
QA
|
how to merge two python dictionaries in single expression have two python dictionaries and want to write single expression that returns these two dictionaries merged the update method would be what need if it returned its result instead of modifying dict in place update print none how can get that final merged dict in not to be extra clear the last one wins conflict handling of dict update is what am looking for as well
|
in follow up answer you asked about the relative performance of these two alternatives dict items items dict on my machine at least fairly ordinary running python alternative is not only shorter and simpler but also significantly faster you can verify this for yourself using the timeit module that comes with python example identical dictionaries mapping consecutive integers to themselves python timeit dict for in range dict items items loops best of usec per loop python timeit dict for in range dict loops best of usec per loop wins by factor of or so different dictionaries seem to yield quite different results but always seems to come out ahead if you get inconsistent results for the same test try passing in with number larger than the default example non overlapping dictionaries mapping short strings to integers and vice versa python timeit from htmlentitydefs import codepoint name as name codepoint as dict items items loops best of usec per loop python timeit from htmlentitydefs import codepoint name as name codepoint as dict loops best of usec per loop wins by about factor of that is pretty big win in my book after comparing those two wondered if poor performance could be attributed to the overhead of constructing the two item lists which in turn led me to wonder if this variation might work better from itertools import chain dict chain iteritems iteritems few quick tests python timeit from itertools import chain from htmlentitydefs import codepoint name as name codepoint as dict chain iteritems iteritems loops best of usec per loop lead me to conclude that is somewhat faster than but not nearly as fast as definitely not worth all the extra typing this discussion is still missing something important which is performance comparison of these alternatives with the obvious way of merging two lists using the update method to try to keep things on an equal footing with the expressions none of which modify or am going to make copy of instead of modifying it in place as follows dict update typical result python timeit from htmlentitydefs import codepoint name as name codepoint as dict update loops best of usec per loop in other words and seem to have essentially identical performance do you think this might be coincidence do not in fact would go so far as to claim that it is impossible for pure python code to do any better than this and if you can do significantly better in extension module imagine the python folks might well be interested in incorporating your code or variation on your approach into the python core python uses dict in lots of places optimizing its operations is big deal you could also write this as copy update as tony does but not surprisingly the difference in notation turns out not to have any measurable effect on performance use whichever looks right to you of course he is absolutely correct to point out that the two statement version is much easier to understand
|
QA
|
python debugger stepping into function that you have called interactively python is quite cool but unfortunately its debugger is not as good as perl one thing that do very commonly when experimenting with code is to call function from within the debugger and step into that function like so note that this program exits immediately without calling foo cat tmp show perl pl usr local bin perl sub foo print hi print bye exit perl tmp show perl pl loading db routines from perl db pl version editor support available enter or for help or man perldebug for more help main tmp show perl pl exit magic happens here am stepping into function that am calling interactively db foo main eval usr local lib perl perl db pl foo db main foo tmp show perl pl print hi db hi main foo tmp show perl pl print bye db bye db debugged program terminated use to quit or to restart use inhibit exit to avoid stopping after program termination or to get additional info db this is incredibly useful when trying to step through function handling of various different inputs to figure out why it fails however it does not seem to work in either pdb or pydb would show an equivalent python example to the one above but it results in large exception stack dump so my question is twofold am missing something is there python debugger that would indeed let me do this obviously could put the calls in the code myself but love working interactively eg not having to start from scratch when want to try calling with slightly different set of arguments
|
and have answered my own question it is the debug command in pydb cat tmp test python py usr local bin python def foo print hi print bye exit pydb tmp test python py tmp test python py module exit pydb debug foo entering recursive debugger call level tmp test python py foo def foo pydb tmp test python py foo print hi pydb hi tmp test python py foo print bye pydb bye return from level type nonetype return from level type nonetype leaving recursive debugger tmp test python py module
|
QA
|
python debugger stepping into function that you have called interactively python is quite cool but unfortunately its debugger is not as good as perl one thing that do very commonly when experimenting with code is to call function from within the debugger and step into that function like so note that this program exits immediately without calling foo cat tmp show perl pl usr local bin perl sub foo print hi print bye exit perl tmp show perl pl loading db routines from perl db pl version editor support available enter or for help or man perldebug for more help main tmp show perl pl exit magic happens here am stepping into function that am calling interactively db foo main eval usr local lib perl perl db pl foo db main foo tmp show perl pl print hi db hi main foo tmp show perl pl print bye db bye db debugged program terminated use to quit or to restart use inhibit exit to avoid stopping after program termination or to get additional info db this is incredibly useful when trying to step through function handling of various different inputs to figure out why it fails however it does not seem to work in either pdb or pydb would show an equivalent python example to the one above but it results in large exception stack dump so my question is twofold am missing something is there python debugger that would indeed let me do this obviously could put the calls in the code myself but love working interactively eg not having to start from scratch when want to try calling with slightly different set of arguments
|
there is python debugger that is part of the core distribution of python called pdb rarely use it myself but find it useful sometimes given this program def foo print hi print bye foo here is session debugging it python usr lib python pdb py var tmp pdbtest py var tmp pdbtest py module def foo pdb var tmp pdbtest py module foo pdb call var tmp pdbtest py foo def foo pdb var tmp pdbtest py foo pdb var tmp pdbtest py foo print hi pdb print pdb hi var tmp pdbtest py foo pdb var tmp pdbtest py foo print bye pdb print pdb bye return var tmp pdbtest py foo none print bye pdb return var tmp pdbtest py module none foo pdb
|
QA
|
what is win con module in python where can find it am building an open source project that uses python and in windows came to the following error message importerror no module named win con the same happened in prebuilt code that it is working except in my computer think this is kind of popular module in python because have saw several messages in other forums but none that could help me have python should have that module already installed is that something of vc thank you for the help got this url http sourceforge net projects pywin but am not sure what to do with the executable
|
note that the pywin download page contains installers for version and amd the activestate distribution is single installer that includes pywin currently at version
|
QA
|
how to get hex string from signed integer say have the classic byte signed integer and want something like print hex to give me something like xffffffff in reality the above gives me am dawdling about in some lower level language and python commandline is quick easy so is there way to do it
|
this will do the trick print hex xffffffff xffffffffl or in function form and stripping off the trailing def hex return hex xffffffff print hex xffffffff print hex or variant that always returns fixed size there may well be better way to do this def hex return hex xffffffff print hex xffffffff print hex or avoiding the hex altogether thanks to ignacio and bobince def hex return xffffffff def hex return xffffffff
|
QA
|
how do iterate through string in python as an example let us say wanted to list the frequency of each letter of the alphabet in string what would be the easiest way to do it this is an example of what am thinking of the question is how to make alltheletters equal to said letters without something like alltheletters abcdefg xyz in many other languages could just do letter and increment my way through the alphabet but thus far have not come across way to do that in python def alphcount text lowertext text lower for letter in alltheletters print letter lowertext count letter
|
something like this for letter in range ord ord print chr letter lowertext count chr letter do not speak python please forgive my syntax errors
|
QA
|
how do iterate through string in python as an example let us say wanted to list the frequency of each letter of the alphabet in string what would be the easiest way to do it this is an example of what am thinking of the question is how to make alltheletters equal to said letters without something like alltheletters abcdefg xyz in many other languages could just do letter and increment my way through the alphabet but thus far have not come across way to do that in python def alphcount text lowertext text lower for letter in alltheletters print letter lowertext count letter
|
the question is how to make alltheletters equal to said letters without something like alltheletters abcdefg xyz that is actually provided by the string module it is not like you have to manually type it yourself import string alltheletters string ascii lowercase def alphcount text lowertext text lower for letter in alltheletters print letter lowertext count letter
|
QA
|
how do iterate through string in python as an example let us say wanted to list the frequency of each letter of the alphabet in string what would be the easiest way to do it this is an example of what am thinking of the question is how to make alltheletters equal to said letters without something like alltheletters abcdefg xyz in many other languages could just do letter and increment my way through the alphabet but thus far have not come across way to do that in python def alphcount text lowertext text lower for letter in alltheletters print letter lowertext count letter
|
do you mean using import string string ascii lowercase then counters dict for letter in string ascii lowercase counters letter lowertext count letter all lowercase letters are accounted for missing counters will have zero value using generators counters dict letter lowertext count letter for letter in string ascii lowercase
|
QA
|
how to get hex string from signed integer say have the classic byte signed integer and want something like print hex to give me something like xffffffff in reality the above gives me am dawdling about in some lower level language and python commandline is quick easy so is there way to do it
|
try this function xffffffff
|
QA
|
how do iterate through string in python as an example let us say wanted to list the frequency of each letter of the alphabet in string what would be the easiest way to do it this is an example of what am thinking of the question is how to make alltheletters equal to said letters without something like alltheletters abcdefg xyz in many other languages could just do letter and increment my way through the alphabet but thus far have not come across way to do that in python def alphcount text lowertext text lower for letter in alltheletters print letter lowertext count letter
|
if you just want to do frequency count of string try this hi there for in get print
|
QA
|
python disk based dictionary was running some dynamic programming code trying to brute force disprove the collatz conjecture and was using dict to store the lengths of the chains had already computed obviously it ran out of memory at some point is there any easy way to use some variant of dict which will page parts of itself out to disk when it runs out of room obviously it will be slower than an in memory dict and it will probably end up eating my hard drive space but this could apply to other problems that are not so futile realized that disk based dictionary is pretty much database so manually implemented one using sqlite but did not do it in any smart way and had it look up every element in the db one at time it was about slower is the smartest way to just create my own set of dicts keeping only one in memory at time and paging them out in some efficient manner
|
the rd party shove module is also worth taking look at it is very similar to shelve in that it is simple dict like object however it can store to various backends such as file svn and provides optional compression and is even threadsafe it is very handy module from shove import shove mem store shove file store shove file mystore file store key value
|
QA
|
how do iterate through string in python as an example let us say wanted to list the frequency of each letter of the alphabet in string what would be the easiest way to do it this is an example of what am thinking of the question is how to make alltheletters equal to said letters without something like alltheletters abcdefg xyz in many other languages could just do letter and increment my way through the alphabet but thus far have not come across way to do that in python def alphcount text lowertext text lower for letter in alltheletters print letter lowertext count letter
|
main question is iterate through the alphabet import string for in string lowercase print how get letter frequencies with some efficiency and without counting non letter characters import string sample hello there this is test letter freq dict for in string lowercase for in for in sample lower if isalpha letter freq print letter freq
|
QA
|
how do iterate through string in python as an example let us say wanted to list the frequency of each letter of the alphabet in string what would be the easiest way to do it this is an example of what am thinking of the question is how to make alltheletters equal to said letters without something like alltheletters abcdefg xyz in many other languages could just do letter and increment my way through the alphabet but thus far have not come across way to do that in python def alphcount text lowertext text lower for letter in alltheletters print letter lowertext count letter
|
the question you have asked how to iterate through the alphabet is not the same question as the problem you are trying to solve how to count the frequency of letters in string you can use string lowercase as other posters have suggested import string alltheletters string lowercase to do things the way you are used to treating letters as numbers you can use the ord and chr functions there is absolutely no reason to ever do exactly this but maybe it comes closer to what you are actually trying to figure out def getalltheletters begin end beginnum ord begin endnum ord end for number in xrange beginnum endnum yield chr number you can tell it does the right thing because this code prints true import string print join getalltheletters string lowercase but to solve the problem you are actually trying to solve you want to use dictionary and collect the letters as you go from collections import defaultdict def letteroccurrances string frequencies defaultdict lambda for character in string frequencies character lower return frequencies use like so occs letteroccurrances hello world print occs print occs this will print and respectively note that this works for unicode as well coding utf occs letteroccurrances you print occs you print occs you if you were to try the other approach on unicode incrementing through every character you would be waiting long time there are millions of unicode characters to implement your original function print the counts of each letter in alphabetical order in terms of this def alphcount text for character count in sorted letteroccurrances text iteritems print character count alphcount hello world
|
QA
|
open file read it process and write back shortest method in python want to do some basic filtering on file read it do processing write it back am not looking for golfing but want the simplest and most elegant method to achieve this came up with from future import with statement filename or sys argv with open filename as new txt some translation of read open filename write new txt the with statement makes things shorter since do not have to explicitly open and close the file any other ideas
|
to do it in way which will not eat your data if you crash in the middle from twisted python filepath import filepath filepath filename setcontent process getcontent
|
QA
|
how do you create simple google talk client using the twisted words python library am interested in making google talk client using python and would like to use the twisted libraries words module have looked at the examples but they do not work with the current implementation of google talk has anybody had any luck with this would you mind documenting brief tutorial as simple task would like to create client bot that tracks the online time of my various google talk accounts so that can get an aggregate number figure could friend the bot in each account and then use the xmpp presence information to keep track of the times that can then aggregate thanks
|
was looking building an xmpp client in python while ago have not gotten around to working on the project was looking at it for did not see anything that used twisted but are couple xmpp libraries found https launchpad net python xmpp http xmpppy sourceforge net http pyxmpp jajcus net also found python program under the gpl that acts multi point conference system using xmpp http coders meta net nz perry jabber confbot php
|
QA
|
how do you create simple google talk client using the twisted words python library am interested in making google talk client using python and would like to use the twisted libraries words module have looked at the examples but they do not work with the current implementation of google talk has anybody had any luck with this would you mind documenting brief tutorial as simple task would like to create client bot that tracks the online time of my various google talk accounts so that can get an aggregate number figure could friend the bot in each account and then use the xmpp presence information to keep track of the times that can then aggregate thanks
|
have written simple jabber bot and thus google talk bot using the xmpppy library which works well the examples on xmpppy should get you started specifically bot py as for something actually implemented in twisted words here is simple tutorial on creating bot that prints every received message to the local terminal and version that replies with the revere of the received message to track the online time of various accounts you would add callback for presences going online offline away etc are presence changes in jabber terminology for more complete system pownce jabber bot uses twisted words and wokkel for the jabber interface the powncebot init py file seems like good place to start it is seems pretty simple
|
QA
|
sqlite parameter substitution problem using sqlite with python am trying to iterate through list and pull the weight of an item from the database based on the item name tried using the parameter substitution suggested to prevent sql injections but it does not work for example when use for item in self inventory names self cursor execute select weight from equipment where name item self cursor close get the error sqlite programmingerror incorrect number of bindings supplied the current statement uses and there are supplied believe this is somehow caused by the initial creation of the database the module made that actually creates the db does have bindings cursor execute create table equipment id integer primary key name text price integer weight real info text ammo cap integer availability west text availability east text however when use the less secure substitution for each item name it works just fine like so for item in self inventory names self cursor execute select weight from equipment where name item self cursor close cannot figure out why it thinks have bindins when am only calling one how can fix it
|
have you tried this for item in self inventory names item self cursor execute select weight from equipment where name self cursor close cursor execute expects sequence list tuple as second parameter ddaa
|
QA
|
sqlite parameter substitution problem using sqlite with python am trying to iterate through list and pull the weight of an item from the database based on the item name tried using the parameter substitution suggested to prevent sql injections but it does not work for example when use for item in self inventory names self cursor execute select weight from equipment where name item self cursor close get the error sqlite programmingerror incorrect number of bindings supplied the current statement uses and there are supplied believe this is somehow caused by the initial creation of the database the module made that actually creates the db does have bindings cursor execute create table equipment id integer primary key name text price integer weight real info text ammo cap integer availability west text availability east text however when use the less secure substitution for each item name it works just fine like so for item in self inventory names self cursor execute select weight from equipment where name item self cursor close cannot figure out why it thinks have bindins when am only calling one how can fix it
|
the cursor execute method expects sequence as second parameter you are supplying string which happens to be characters long use the following form instead self cursor execute select weight from equipment where name item python library reference sqlite cursor objects
|
QA
|
os walk without digging into directories below how do limit os walk to only return files in the directory provide it def dir list self dir name whitelist outputlist for root dirs files in os walk dir name for in files if os path splitext in whitelist outputlist append os path join root else self email to ignore return outputlist
|
you could use os listdir which returns list of names for both files and directories in given directory if you need to distinguish between files and directories call os stat on each name
|
QA
|
os walk without digging into directories below how do limit os walk to only return files in the directory provide it def dir list self dir name whitelist outputlist for root dirs files in os walk dir name for in files if os path splitext in whitelist outputlist append os path join root else self email to ignore return outputlist
|
do not use os walk example import os root for item in os listdir root if os path isfile os path join root item print item
|
QA
|
os walk without digging into directories below how do limit os walk to only return files in the directory provide it def dir list self dir name whitelist outputlist for root dirs files in os walk dir name for in files if os path splitext in whitelist outputlist append os path join root else self email to ignore return outputlist
|
the suggestion to use listdir is good one the direct answer to your question is root dirs files os walk dir name next
|
QA
|
os walk without digging into directories below how do limit os walk to only return files in the directory provide it def dir list self dir name whitelist outputlist for root dirs files in os walk dir name for in files if os path splitext in whitelist outputlist append os path join root else self email to ignore return outputlist
|
if you have more complex requirements than just the top directory eg ignore vcs dirs etc you can also modify the list of directories to prevent os walk recursing through them ie def dir list self dir name whitelist outputlist for root dirs files in os walk dir name dirs for in dirs if is good for in files do stuff note be careful to mutate the list rather than just rebind it obviously os walk does not know about the external rebinding
|
QA
|
python debugger stepping into function that you have called interactively python is quite cool but unfortunately its debugger is not as good as perl one thing that do very commonly when experimenting with code is to call function from within the debugger and step into that function like so note that this program exits immediately without calling foo cat tmp show perl pl usr local bin perl sub foo print hi print bye exit perl tmp show perl pl loading db routines from perl db pl version editor support available enter or for help or man perldebug for more help main tmp show perl pl exit magic happens here am stepping into function that am calling interactively db foo main eval usr local lib perl perl db pl foo db main foo tmp show perl pl print hi db hi main foo tmp show perl pl print bye db bye db debugged program terminated use to quit or to restart use inhibit exit to avoid stopping after program termination or to get additional info db this is incredibly useful when trying to step through function handling of various different inputs to figure out why it fails however it does not seem to work in either pdb or pydb would show an equivalent python example to the one above but it results in large exception stack dump so my question is twofold am missing something is there python debugger that would indeed let me do this obviously could put the calls in the code myself but love working interactively eg not having to start from scratch when want to try calling with slightly different set of arguments
|
for interactive work on code am developing usually find it more efficient to set programmatic break point in the code itself with pdb set trace this makes it easir to break on the program state deep in loop too if state pdb set trace
|
QA
|
python debugger stepping into function that you have called interactively python is quite cool but unfortunately its debugger is not as good as perl one thing that do very commonly when experimenting with code is to call function from within the debugger and step into that function like so note that this program exits immediately without calling foo cat tmp show perl pl usr local bin perl sub foo print hi print bye exit perl tmp show perl pl loading db routines from perl db pl version editor support available enter or for help or man perldebug for more help main tmp show perl pl exit magic happens here am stepping into function that am calling interactively db foo main eval usr local lib perl perl db pl foo db main foo tmp show perl pl print hi db hi main foo tmp show perl pl print bye db bye db debugged program terminated use to quit or to restart use inhibit exit to avoid stopping after program termination or to get additional info db this is incredibly useful when trying to step through function handling of various different inputs to figure out why it fails however it does not seem to work in either pdb or pydb would show an equivalent python example to the one above but it results in large exception stack dump so my question is twofold am missing something is there python debugger that would indeed let me do this obviously could put the calls in the code myself but love working interactively eg not having to start from scratch when want to try calling with slightly different set of arguments
|
you can interactively debug function with pdb as well provided the script you want to debug does not exit at the end cat test py usr bin python def foo print return to debug start an interactive python session and import pdb python python apr gcc apple computer inc build on darwin type help copyright credits or license for more information import pdb import test pdb runcall test foo users simon desktop test py foo pdb users simon desktop test py foo print pdb the pdb module comes with python and is documented in the modules docs at http docs python org modindex html
|
QA
|
python find question am using python to extract the filename from link using rfind like below url http www google com test php print url url rfind this works ok with links without at the end of them and returns test php have encountered links with at the end like so http www google com test php am have trouble getting the page name when there is at the end can anyone help cheers
|
filenames with slash at the end are technically still path definitions and indicate that the index file is to be read if you actually have one that ends in test php would consider that an error in any case you can strip the from the end before running your code as follows url url rstrip
|
QA
|
python find question am using python to extract the filename from link using rfind like below url http www google com test php print url url rfind this works ok with links without at the end of them and returns test php have encountered links with at the end like so http www google com test php am have trouble getting the page name when there is at the end can anyone help cheers
|
there is library called urlparse that will parse the url for you but still does not remove the at the end so one of the above will be the best option
|
QA
|
python find question am using python to extract the filename from link using rfind like below url http www google com test php print url url rfind this works ok with links without at the end of them and returns test php have encountered links with at the end like so http www google com test php am have trouble getting the page name when there is at the end can anyone help cheers
|
just removing the slash at the end will not work as you can probably have url that looks like this http www google com test php filepath tests hey xml in which case you will get back hey xml instead of manually checking for this you can use urlparse to get rid of the parameters then do the check other people suggested from urlparse import urlparse url http www google com test php something heyharr sir txt urlparse url rstrip print rfind
|
QA
|
python find question am using python to extract the filename from link using rfind like below url http www google com test php print url url rfind this works ok with links without at the end of them and returns test php have encountered links with at the end like so http www google com test php am have trouble getting the page name when there is at the end can anyone help cheers
|
just for fun you can use regexp import re print re search url group
|
QA
|
python find question am using python to extract the filename from link using rfind like below url http www google com test php print url url rfind this works ok with links without at the end of them and returns test php have encountered links with at the end like so http www google com test php am have trouble getting the page name when there is at the end can anyone help cheers
|
use strip to remove trailing slashes url rstrip rsplit if wider range of possible urls is possible including urls with queries anchors or without path do it properly with urlparse path urlparse urlparse url path return path rstrip rsplit or root path
|
QA
|
python disk based dictionary was running some dynamic programming code trying to brute force disprove the collatz conjecture and was using dict to store the lengths of the chains had already computed obviously it ran out of memory at some point is there any easy way to use some variant of dict which will page parts of itself out to disk when it runs out of room obviously it will be slower than an in memory dict and it will probably end up eating my hard drive space but this could apply to other problems that are not so futile realized that disk based dictionary is pretty much database so manually implemented one using sqlite but did not do it in any smart way and had it look up every element in the db one at time it was about slower is the smartest way to just create my own set of dicts keeping only one in memory at time and paging them out in some efficient manner
|
did not try it yet but hamster db is promising and has python interface
|
QA
|
python library problems am relatively new to python and am having problems programming with scapy the python network manipulation tool however cannot tell if it is as much scapy problem as it is being python newbie problem on the scapy site they give sample program which am not able to run on my own machine usr bin env python import sys from scapy import sr ip icmp sr ip dst sys argv icmp if show to which get traceback most recent call last file test py line in module from scapy import sr ip icmp importerror cannot import name sr so my question then is when installing python libraries do need to change my path or anything similar also is there something can run in the interpreter to tell me the contents of the scapy package can run from scapy import just fine but since have no idea what is inside it it is hard to use it
|
with the caveat from federico ramponi you should use scapy as an interpreter by its own not as library want to answer the non scapy specific parts of the question when installing python libraries do need to change my path or anything similar think you are talking about changing pythonpath system wide this is usually not required or good idea third party python libraries should either be installed in system directories such as usr lib python site packages or installed locally in which case you might want to set pythonpath in your makefile or in driver she will script also is there something can run in the interpreter to tell me the contents of the scapy package you can do something like this import scapy dir scapy or even better import scapy help scapy bonus question asked in comment is import scapy the same as from scapy import import scapy binds the scapy name in the local namespace to the scapy module object otoh from scapy import does not bind the module name but all public names defined in the scapy module are bound in the local namespace see paragraphs and of the python reference manual the import statement
|
QA
|
python library problems am relatively new to python and am having problems programming with scapy the python network manipulation tool however cannot tell if it is as much scapy problem as it is being python newbie problem on the scapy site they give sample program which am not able to run on my own machine usr bin env python import sys from scapy import sr ip icmp sr ip dst sys argv icmp if show to which get traceback most recent call last file test py line in module from scapy import sr ip icmp importerror cannot import name sr so my question then is when installing python libraries do need to change my path or anything similar also is there something can run in the interpreter to tell me the contents of the scapy package can run from scapy import just fine but since have no idea what is inside it it is hard to use it
|
it tells you that it cannot find sr in scapy not sure just how newbite you are but the interpreter is always your friend fire up the interpreter just type python on the commandline and at the prompt type but do not type the they will show up by themselves import scapy from pprint import pformat pformat dir scapy the last line should print lot of stuff do you see sr ip and icmp there anywhere if not the example is at fault try also help scapy that is about how much can help you without installing scapy and looking at your actual source file myself
|
QA
|
python library problems am relatively new to python and am having problems programming with scapy the python network manipulation tool however cannot tell if it is as much scapy problem as it is being python newbie problem on the scapy site they give sample program which am not able to run on my own machine usr bin env python import sys from scapy import sr ip icmp sr ip dst sys argv icmp if show to which get traceback most recent call last file test py line in module from scapy import sr ip icmp importerror cannot import name sr so my question then is when installing python libraries do need to change my path or anything similar also is there something can run in the interpreter to tell me the contents of the scapy package can run from scapy import just fine but since have no idea what is inside it it is hard to use it
|
the scapy package is tool for network manipulation and monitoring am curious as to what you are trying to do with it it is rude to spy on your friends coventry metta src wget http www secdev org projects scapy files scapy latest zip coventry metta src unzip qq scapy latest zip warning scapy latest zip extra bytes at beginning or within zipfile attempting to process anyway coventry metta src find scapy name py xargs grep sr scapy scapy layers dns py sr ip dst nameserver udp dns opcode scapy scapy layers dns py sr ip dst nameserver udp dns opcode scapy scapy layers inet py from scapy sendrecv import sr sr srp scapy scapy layers snmp py are sr ip dst dst udp sport randshort snmp community community pdu snmpnext varbindlist snmpvarbind oid oid timeout chaincc verbose retry scapy scapy layers inet py from scapy sendrecv import sr sr srp scapy scapy layers inet py sr ip dst target options proto xxxxyyyyyyyyyyyy timeout timeout verbose scapy scapy sendrecv py def sr filter none iface none nofilter args kargs according to the last line sr is function defined in scapy sendrecv someone should file documentation bug with the author
|
QA
|
open file read it process and write back shortest method in python want to do some basic filtering on file read it do processing write it back am not looking for golfing but want the simplest and most elegant method to achieve this came up with from future import with statement filename or sys argv with open filename as new txt some translation of read open filename write new txt the with statement makes things shorter since do not have to explicitly open and close the file any other ideas
|
actually an easier way using fileinput is to use the inplace parameter import fileinput for line in fileinput input filenametoprocess inplace process line if you use the inplace parameter it will redirect stdout to your file so that if you do print it will write back to your file this example adds line numbers to your file import fileinput for line in fileinput input txt inplace print fileinput lineno line
|
QA
|
any good ajax framework for google app engine apps am trying to implement ajax in my google app engine application and so am looking for good ajax framework that will help me anyone has any idea am thinking about google web toolkit how good it is in terms of creating ajax for google app engine
|
am currently using jquery for my gae app and it works beautifully for me have chart google charts that is dynamic and uses an ajax call to grab json string it really seems to work fine for me
|
QA
|
decoding wbxml syncml message from an device am trying to decode wbxml encoded syncml message from nokia my first attempt was to use the python pywbxml module which wraps calls to libwbxml decoding the message with this gave lot of unknown tags and big chunk of binary within collection tag tried running the contents of the collection through by itself but it failed is there something am missing also does anyone know of pure python implementation of wbxml parser failing that command line or online tool to decode these messages would be useful it would make it lot easier for me to write my own
|
funnily enough have been working on the same problem am about halfway through writing my own pure python wbxml parser but it is not yet complete enough to be useful and have very little time to work on it right now those unknown tags might be because pywbxml libwbxml does not have the right tag vocabulary loaded wbxml represents tags by an index number to avoid transmitting the same tag name hundreds of times and the table that maps index numbers to tag names has to be supplied separately from the wbxml document itself from vague glance at the libwbxml source it seems like libwbxml has bunch of tag tables hard coded it has tables for syncml think my nokia sends syncml if so your probably does too which it looks like libwbxml does not support yet getting it to work might be as simple as adding syncml table to libwbxml that said last time tried pywbxml does not compile against the vanilla libwbxml source so you have to apply some patches first so simple may be relative term
|
QA
|
python debugger stepping into function that you have called interactively python is quite cool but unfortunately its debugger is not as good as perl one thing that do very commonly when experimenting with code is to call function from within the debugger and step into that function like so note that this program exits immediately without calling foo cat tmp show perl pl usr local bin perl sub foo print hi print bye exit perl tmp show perl pl loading db routines from perl db pl version editor support available enter or for help or man perldebug for more help main tmp show perl pl exit magic happens here am stepping into function that am calling interactively db foo main eval usr local lib perl perl db pl foo db main foo tmp show perl pl print hi db hi main foo tmp show perl pl print bye db bye db debugged program terminated use to quit or to restart use inhibit exit to avoid stopping after program termination or to get additional info db this is incredibly useful when trying to step through function handling of various different inputs to figure out why it fails however it does not seem to work in either pdb or pydb would show an equivalent python example to the one above but it results in large exception stack dump so my question is twofold am missing something is there python debugger that would indeed let me do this obviously could put the calls in the code myself but love working interactively eg not having to start from scratch when want to try calling with slightly different set of arguments
|
if you are more familiar with gui debugger there is winpdb win in this case does not refer to windows actually use it on linux on debian ubuntu sudo aptitude install winpdb then just put this in your code where you want it to break import rpdb rpdb start embedded debugger interactive password then start winpdb and attach to your running script
|
QA
|
how do perform query filtering in django templates need to perform filtered query from within django template to get set of objects equivalent to python code within view queryset modelclass objects filter somekey foo in my template would like to do for object in data somekey set filter but just cannot seem to find out how to write filter
|
run into this problem on regular basis and often use the add method solution however there are definitely cases where add method or compute it in the view do not work or do not work well when you are caching template fragments and need some non trivial db computation to produce it you do not want to do the db work unless you need to but you will not know if you need to until you are deep in the template logic some other possible solutions use the expr expression as var name template tag found at http www djangosnippets org snippets the expression is any legal python expression with your template context as your local scope change your template processor jinja http jinja pocoo org has syntax that is almost identical to the django template language but with full python power available it is also faster you can do this wholesale or you might limit its use to templates that you are working on but use django safer templates for designer maintained pages
|
QA
|
how to flush output of python print how do force python print function to output to the screen
|
import sys sys stdout flush print by default prints to sys stdout references http docs python org reference simple stmts html the print statement http docs python org library sys html http docs python org library stdtypes html file objects
|
QA
|
how to flush output of python print how do force python print function to output to the screen
|
running python see command line option you unbuffered binary stdout and stderr also pythonunbuffered see man page for details on internal buffering relating to you here is the relevant doc
|
QA
|
make python enter password when running csh script am writing python script that executes csh script in solaris the csh script prompts the user for the root password which know but am not sure how to make the python script answer the prompt with the password is this possible here is what am using to execute the csh script import commands commands getoutput server stop
|
should be able to pass it as parameter something like commands getoutput server stop password
|
QA
|
make python enter password when running csh script am writing python script that executes csh script in solaris the csh script prompts the user for the root password which know but am not sure how to make the python script answer the prompt with the password is this possible here is what am using to execute the csh script import commands commands getoutput server stop
|
use subprocess call popen to create your process and use communicate to send it text sorry forgot to include the pipe from subprocess import popen pipe proc popen server stop stdin pipe proc communicate password you would do better do avoid the password and try scheme like sudo and sudoers pexpect mentioned elsewhere is not part of the standard library
|
QA
|
given list of variable names in python how do create dictionary with the variable names as keys to the variables values have list of variable names like this foo bar baz originally asked how convert list of variables see greg hewgill answer below how do convert this to dictionary where the keys are the variable names as strings and the values are the values of the variables foo foo bar bar baz baz now that am re asking the question came up with for name in list of variable names name eval name can that be improved upon update responding to the question in comment of why would want to do this often find myself using the operator to strings with dictionary of names and values to interpolate often the names in the string is just the names of local variables so with the answer below can do something like this message name name zip zip dear name dict locals for in name zip
|
your original list foo bar baz does not contain the variable names it just contains elements that refer to the same values as the variables you listed this is because you can have two different variable names that refer to the same value so the list by itself does not contain information about what other names refer to the objects the first element in your array has the name foo but it also has the name assuming your array is called after executing the following code quux also refers to the same object quux update you are right that you can use eval for that but its use is generally discouraged python provides special member named dict that contains the symbol table for the current module so you can import main dict main dict for in list of variable names having to import main when your code is in the unnamed main module is quirk of python
|
QA
|
given list of variable names in python how do create dictionary with the variable names as keys to the variables values have list of variable names like this foo bar baz originally asked how convert list of variables see greg hewgill answer below how do convert this to dictionary where the keys are the variable names as strings and the values are the values of the variables foo foo bar bar baz baz now that am re asking the question came up with for name in list of variable names name eval name can that be improved upon update responding to the question in comment of why would want to do this often find myself using the operator to strings with dictionary of names and values to interpolate often the names in the string is just the names of local variables so with the answer below can do something like this message name name zip zip dear name dict locals for in name zip
|
you can use list or generator comprehensions to build list of key value tuples used to directly instantiate dict the best way is below dict name eval name for name in list of variable names in addition if you know for example that the variables exist in the local symbol table you can save yourself from the dangerous eval by looking the variable directly from locals dict name locals name for name in list of variable names after your final update think the answer below is really what you want if you are just using this for string expansion with strings that you control just pass locals directly to the string expansion and it will cherry pick out the desired values if however these strings could ever come from an outside source translation files than it is good idea to filter locals
|
QA
|
given list of variable names in python how do create dictionary with the variable names as keys to the variables values have list of variable names like this foo bar baz originally asked how convert list of variables see greg hewgill answer below how do convert this to dictionary where the keys are the variable names as strings and the values are the values of the variables foo foo bar bar baz baz now that am re asking the question came up with for name in list of variable names name eval name can that be improved upon update responding to the question in comment of why would want to do this often find myself using the operator to strings with dictionary of names and values to interpolate often the names in the string is just the names of local variables so with the answer below can do something like this message name name zip zip dear name dict locals for in name zip
|
not efficient but without invoking eval dict for in globals iteritems if in list of variable names or dict for in vars iteritems if in list of variable names depending on what you want
|
QA
|
make python enter password when running csh script am writing python script that executes csh script in solaris the csh script prompts the user for the root password which know but am not sure how to make the python script answer the prompt with the password is this possible here is what am using to execute the csh script import commands commands getoutput server stop
|
this seems to work better import popen stdout stdin popen popen server stop stdin write password but it is not yet even though password is the correct password am still getting su sorry back from the csh script when it is trying to su to root
|
QA
|
make python enter password when running csh script am writing python script that executes csh script in solaris the csh script prompts the user for the root password which know but am not sure how to make the python script answer the prompt with the password is this possible here is what am using to execute the csh script import commands commands getoutput server stop
|
have look at the pexpect module it is designed to deal with interactive programs which seems to be your case oh and remember that hard encoding root password in she will or python script is potentially security hole
|
QA
|
how to flush output of python print how do force python print function to output to the screen
|
using the you command line switch works but it is little bit clumsy it would mean that the program would potentially behave incorrectly if the user invoked the script without the you option usually use custom stdout like this class flushfile file def init self self def write self self write self flush import sys sys stdout flushfile sys stdout now all your print calls which use sys stdout implicitly will be automatically flushed
|
QA
|
given list of variable names in python how do create dictionary with the variable names as keys to the variables values have list of variable names like this foo bar baz originally asked how convert list of variables see greg hewgill answer below how do convert this to dictionary where the keys are the variable names as strings and the values are the values of the variables foo foo bar bar baz baz now that am re asking the question came up with for name in list of variable names name eval name can that be improved upon update responding to the question in comment of why would want to do this often find myself using the operator to strings with dictionary of names and values to interpolate often the names in the string is just the names of local variables so with the answer below can do something like this message name name zip zip dear name dict locals for in name zip
|
forget filtering locals the dictionary you give to the formatting string is allowed to contain unused keys name foo zip unused whoops locals name foo zip unused whoops name zip locals foo
|
QA
|
unexpected list comprehension behaviour in python believe am getting bitten by some combination of nested scoping rules and list comprehensions jeremy hylton blog post is suggestive about the causes but do not really understand cpython implementation well enough to figure out how to get around this here is an overcomplicated example if people have simpler one that demos it would like to hear it the issue the list comprehensions using next are filled with the result from the last iteration edit the problem what exactly is going on with this and how do fix this do have to use standard for loop clearly the function is running the correct number of times but the list comprehensions end up with the final value instead of the result of each loop some hypotheses generators lazy filling of list comprehensions code import itertools def digit digit list false for in xrange digit list true return itertools cycle digit list digit next for in range this list comprehension works as expected true false false false false class counter object def init self self counter digit for ii in range self totalcount self display def next self self totalcount self display self counter next print self totalcount self display return self display def next self args self cycle self totalcount print self totalcount self display return self display def cycle self digit first self counter digit next print digit first print self display self display digit if first and digit self cycle digit counter next for in range next for in range output in next for in range out in next for in range out this should be or similar
|
mind if refactor this bit def digit for in itertools count yield not but actually you do not need that one if you implement the whole thing as simple iterator def counter digits base counter digits def iterator for total in itertools count for in range len counter counter counter base if counter break print total list reversed counter yield list reversed counter return iterator counter print list itertools islice if you want to get rid of the print debugging is it go with while loop this incindentally also solves your initial problem because reversed returns copy of the list oh and it is zero based now
|
QA
|
what does the yield keyword do what is the use of the yield keyword in python what does it do for example am trying to understand this code def get child candidates self distance min dist max dist if self leftchild and distance max dist self median yield self leftchild if self rightchild and distance max dist self median yield self rightchild and this is the caller result candidates list self while candidates node candidates pop distance node get dist obj if distance max dist and distance min dist result extend node values candidates extend node get child candidates distance min dist max dist return result what happens when the method get child candidates is called list is returned single element is returned is it called again when will subsequent calls stop the code comes from jochen schulz jrschulz who made great python library for metric spaces this is the link to the complete source module mspace
|
yield is just like return it returns whatever you tell it to the only difference is that the next time you call the function execution starts from the last call to the yield statement in the case of your code the function get child candidates is acting like an iterator so that when you extend your list it adds one element at time to the new list list extend calls an iterator until it is exhausted in the case of the code sample you posted it would be much clearer to just return tuple and append that to the list
|
QA
|
what does the yield keyword do what is the use of the yield keyword in python what does it do for example am trying to understand this code def get child candidates self distance min dist max dist if self leftchild and distance max dist self median yield self leftchild if self rightchild and distance max dist self median yield self rightchild and this is the caller result candidates list self while candidates node candidates pop distance node get dist obj if distance max dist and distance min dist result extend node values candidates extend node get child candidates distance min dist max dist return result what happens when the method get child candidates is called list is returned single element is returned is it called again when will subsequent calls stop the code comes from jochen schulz jrschulz who made great python library for metric spaces this is the link to the complete source module mspace
|
it is returning generator am not particularly familiar with python but believe it is the same kind of thing as iterator blocks if you are familiar with those there is an ibm article which explains it reasonably well for python as far as can see the key idea is that the compiler interpreter whatever does some trickery so that as far as the caller is concerned they can keep calling next and it will keep returning values as if the generator method was paused now obviously you cannot really pause method so the compiler builds state machine for you to remember where you currently are and what the local variables etc look like this is much easier than writing an iterator yourself
|
QA
|
what does the yield keyword do what is the use of the yield keyword in python what does it do for example am trying to understand this code def get child candidates self distance min dist max dist if self leftchild and distance max dist self median yield self leftchild if self rightchild and distance max dist self median yield self rightchild and this is the caller result candidates list self while candidates node candidates pop distance node get dist obj if distance max dist and distance min dist result extend node values candidates extend node get child candidates distance min dist max dist return result what happens when the method get child candidates is called list is returned single element is returned is it called again when will subsequent calls stop the code comes from jochen schulz jrschulz who made great python library for metric spaces this is the link to the complete source module mspace
|
think of it this way an iterator is just fancy sounding term for an object that has next method so yield ed function ends up being something like this original version def some function for in xrange yield for in some function print this is basically what the python interpreter does with the above code class it def init self start at so that we get when we add below self count the iter method will be called once by the for loop the rest of the magic happens on the object returned by this method in this case it is the object itself def iter self return self the next method will be called repeatedly by the for loop until it raises stopiteration def next self self count if self count return self count else stopiteration exception is raised to signal that the iterator is done this is caught implicitly by the for loop raise stopiteration def some func return it for in some func print for more insight as to what is happening behind the scenes the for loop can be rewritten to this iterator some func try while print iterator next except stopiteration pass does that make more sense or just confuse you more edit should note that this is an oversimplification for illustrative purposes edit forgot to throw the stopiteration exception
|
QA
|
what does the yield keyword do what is the use of the yield keyword in python what does it do for example am trying to understand this code def get child candidates self distance min dist max dist if self leftchild and distance max dist self median yield self leftchild if self rightchild and distance max dist self median yield self rightchild and this is the caller result candidates list self while candidates node candidates pop distance node get dist obj if distance max dist and distance min dist result extend node values candidates extend node get child candidates distance min dist max dist return result what happens when the method get child candidates is called list is returned single element is returned is it called again when will subsequent calls stop the code comes from jochen schulz jrschulz who made great python library for metric spaces this is the link to the complete source module mspace
|
to understand what yield does you must understand what generators are and before generators come iterables iterables when you create list you can read its items one by one reading its items one by one is called iteration mylist for in mylist print mylist is an iterable when you use list comprehension you create list and so an iterable mylist for in range for in mylist print everything you can use for in on is an iterable lists strings files these iterables are handy because you can read them as much as you wish but you store all the values in memory and this is not always what you want when you have lot of values generators generators are iterators but you can only iterate over them once it is because they do not store all the values in memory they generate the values on the fly mygenerator for in range for in mygenerator print it is just the same except you used instead of but you cannot perform for in mygenerator second time since generators can only be used once they calculate then forget about it and calculate and end calculating one by one yield yield is keyword that is used like return except the function will return generator def creategenerator mylist range for in mylist yield mygenerator creategenerator create generator print mygenerator mygenerator is an object generator object creategenerator at xb for in mygenerator print here it is useless example but it is handy when you know your function will return huge set of values that you will only need to read once to master yield you must understand that when you call the function the code you have written in the function body does not run the function only returns the generator object this is bit tricky then your code will be run each time the for uses the generator now the hard part the first time the for calls the generator object created from your function it will run the code in your function from the beginning until it hits yield then it will return the first value of the loop then each other call will run the loop you have written in the function one more time and return the next value until there is no value to return the generator is considered empty once the function runs but does not hit yield anymore it can be because the loop had come to an end or because you do not satisfy an if else anymore your code explained generator here you create the method of the node object that will return the generator def node get child candidates self distance min dist max dist here is the code that will be called each time you use the generator object if there is still child of the node object on its left and if distance is ok return the next child if self leftchild and distance max dist self median yield self leftchild if there is still child of the node object on its right and if distance is ok return the next child if self rightchild and distance max dist self median yield self rightchild if the function arrives here the generator will be considered empty there is no more than two values the left and the right children caller create an empty list and list with the current object reference result candidates list self loop on candidates they contain only one element at the beginning while candidates get the last candidate and remove it from the list node candidates pop get the distance between obj and the candidate distance node get dist obj if distance is ok then you can fill the result if distance max dist and distance min dist result extend node values add the children of the candidate in the candidates list so the loop will keep running until it will have looked at all the children of the children of the children etc of the candidate candidates extend node get child candidates distance min dist max dist return result this code contains several smart parts the loop iterates on list but the list expands while the loop is being iterated it is concise way to go through all these nested data even if it is bit dangerous since you can end up with an infinite loop in this case candidates extend node get child candidates distance min dist max dist exhausts all the values of the generator but while keeps creating new generator objects which will produce different values from the previous ones since it is not applied on the same node the extend method is list object method that expects an iterable and adds its values to the list usually we pass list to it extend print but in your code it gets generator which is good because you do not need to read the values twice you may have lot of children and you do not want them all stored in memory and it works because python does not care if the argument of method is list or not python expects iterables so it will work with strings lists tuples and generators this is called duck typing and is one of the reason why python is so cool but this is another story for another question you can stop here or read little bit to see an advanced use of generator controlling generator exhaustion class bank let us create bank building atms crisis false def create atm self while not self crisis yield hsbc bank when everything ok the atm gives you as much as you want corner street atm hsbc create atm print corner street atm next print corner street atm next print corner street atm next for cash in range hsbc crisis true crisis is coming no more money print corner street atm next type exceptions stopiteration wall street atm hsbc create atm it is even true for new atms print wall street atm next type exceptions stopiteration hsbc crisis false trouble is even post crisis the atm remains empty print corner street atm next type exceptions stopiteration brand new atm hsbc create atm build new one to get back in business for cash in brand new atm print cash it can be useful for various things like controlling access to resource itertools your best friend the itertools module contains special functions to manipulate iterables ever wish to duplicate generator chain two generators group values in nested list with one liner map zip without creating another list then just import itertools an example let us see the possible orders of arrival for horse race horses races itertools permutations horses print races itertools permutations object at xb dc print list itertools permutations horses understanding the inner mechanisms of iteration iteration is process implying iterables implementing the iter method and iterators implementing the next method iterables are any objects you can get an iterator from iterators are objects that let you iterate on iterables more about it in this article about how does the for loop work
|
QA
|
python inheritance how to disable function in you can disable function in parent class by declaring it as private in the child class how can this be done in python how can hide parent function from child public interface
|
class object def some function self do some stuff class object some function none this may lead to some nasty and hard to find exceptions being thrown though so you might try this class object def some function self do some stuff class object def some function self raise notimplementederror function some function not implemented
|
QA
|
python inheritance how to disable function in you can disable function in parent class by declaring it as private in the child class how can this be done in python how can hide parent function from child public interface
|
there really are not any true private attributes or methods in python one thing you can do is simply override the method you do not want in the subclass and raise an exception class foo object def foo self print foo class bar foo def foo self raise attributeerror bar object has no attribute foo bar foo traceback most recent call last file interactive input line in module file interactive input line in foo attributeerror bar object has no attribute foo
|
QA
|
will django be good choice for permissions based web app have been exploring the details of django for about week now and like what see however have come upon some negativity in relation to fine grained control of permissions to the crud interface what am writing is an intranet client management web app the organisation is about tiers and need to restrict access to client groups based on tiers continually expanding have fairly good idea how am going to do this but am not sure if will be able to integrate it well into the pre built admin interface have done absolutely zero django development otherwise would probably have better idea on whether this would work or not probably will not use django if the generated admin interface is going to be useless to this project but like said there is heavy reliance on fine grained custom permissions will django let me build custom permissions rules and integrate it seamlessly into the admin crud interface update one want to use the admin app to minimise the repitition of generating crud interfaces so yes consider it must have update two want to describe the permissions required for this project client can belong to one or many stores full time employees should only be able to edit clients at their store even if they belong to another store however they should not be able to see edit clients at another store casuals should only be able to view clients based on what store they are rostered too or if the casual is logged in as the store user more likely management above them need to be able to see all employees for the stores they manage nothing more senior management should be able to edit all employees and grant permissions below themselves after reading the django documentation it says you cannot autmoatically set permissions for sub set of group only the entire group is it easy enough to mock up your own permissions for this purpose
|
modeladmin objects have has add permission has change permission has delete permission and queryset methods which can be used to enforce permissions around what the logged in user can see and modify you could create subclass which uses these to enforce whatever permissions you want to implement and register all your models with the admin application using your subclass however it all depends how exactly your permissions system will work what are the exact requirements which fall out of your fine grained permissions the more you move away from what the admin application was designed to do the more work it will take but there are lot of hooks in there which you can use to implement your custom requirements here is blog post from luke plant which gives examples of some of the fine tuning you can do without having to dig too deep does it absolutely have to be based around the admin application generic views and modelforms can take care of lot of the tedious bits involved in implementing crud so be wary of getting too hung up on customising admin it is almost django tradition to start by getting hung up on the admin app and what it can and cannot do initially thinking you will never have to write any code again
|
QA
|
what does the yield keyword do what is the use of the yield keyword in python what does it do for example am trying to understand this code def get child candidates self distance min dist max dist if self leftchild and distance max dist self median yield self leftchild if self rightchild and distance max dist self median yield self rightchild and this is the caller result candidates list self while candidates node candidates pop distance node get dist obj if distance max dist and distance min dist result extend node values candidates extend node get child candidates distance min dist max dist return result what happens when the method get child candidates is called list is returned single element is returned is it called again when will subsequent calls stop the code comes from jochen schulz jrschulz who made great python library for metric spaces this is the link to the complete source module mspace
|
an example in plain language will provide correspondence between high level human concepts to low level python concepts want to operate on sequence of numbers but do not want to bother my self with the creation of that sequence want only to focus on the operation want to do so do the following call you and tell you that want sequence of numbers which is produced in specific way and let you know what the algorithm is this step corresponds to defining the generator function the function containing yield sometime later tell you ok get ready to tell me the sequence of numbers this step corresponds to calling the generator function which returns generator object note that you do not tell me any numbers yet you just grab your paper and pencil ask you tell me the next number and you tell me the first number after that you wait for me to ask you for the next number it is your job to remember where you were what numbers you have already said what is the next number do not care about the details this step corresponds to calling next on the generator object repeat previous step until eventually you might come to an end you do not tell me number you just shout hold your horses am done no more numbers this step corresponds to the generator object ending its job and raising stopiteration exception the generator function does not need to raise the exception it is raised automatically when the function ends or issues return this is what generator does function that contains yield it starts executing pauses whenever it does yield and when asked for next value it continues from the point it was last it fits perfectly by design with the iterator protocol of python which describes how to sequentially request for values the most famous user of the iterator protocol is the for command in python so whenever you do for item in sequence it does not matter if sequence is list string dictionary or generator object like described above the result is the same you read items off sequence one by one note that defining function which contains yield keyword is not the only way to create generator it is just the easiest way to create one for more accurate information read about iterator types the yield statement and generators in the python documentation
|
QA
|
how to do makefile dependencies for python code have bunch of files that are generated by collection of python programs that have number of shared python modules and need to account for this in my make system it is easy enough to enumerate which python program need to be run to generate each file what cannot find good solution for is determining which other python files those programs depend on need this so make will know what needs regenerating if one of the shared python files changes is there good system for producing make style dependency rules from collection of python sources
|
the import statements are pretty much all the dependencies there are there are are two relevant forms for the import statements import from import you will also need the pythonpath and sites information that is used to build sys path this shows the physical locations of the modules and packages that is kind of painful to process since you have to do the transitive closure of all imports in all modules you import as an alternative approach you can use the option to get the complete list of imports and physical files this produces log that you can edit into flat list of dependencies for instance when do import math see this in the log dlopen library frameworks python framework versions lib python lib dynload math so import math dynamically loaded from library frameworks python framework versions lib python lib dynload math so
|
QA
|
will django be good choice for permissions based web app have been exploring the details of django for about week now and like what see however have come upon some negativity in relation to fine grained control of permissions to the crud interface what am writing is an intranet client management web app the organisation is about tiers and need to restrict access to client groups based on tiers continually expanding have fairly good idea how am going to do this but am not sure if will be able to integrate it well into the pre built admin interface have done absolutely zero django development otherwise would probably have better idea on whether this would work or not probably will not use django if the generated admin interface is going to be useless to this project but like said there is heavy reliance on fine grained custom permissions will django let me build custom permissions rules and integrate it seamlessly into the admin crud interface update one want to use the admin app to minimise the repitition of generating crud interfaces so yes consider it must have update two want to describe the permissions required for this project client can belong to one or many stores full time employees should only be able to edit clients at their store even if they belong to another store however they should not be able to see edit clients at another store casuals should only be able to view clients based on what store they are rostered too or if the casual is logged in as the store user more likely management above them need to be able to see all employees for the stores they manage nothing more senior management should be able to edit all employees and grant permissions below themselves after reading the django documentation it says you cannot autmoatically set permissions for sub set of group only the entire group is it easy enough to mock up your own permissions for this purpose
|
the django permission system totally rules each model has default set of permissions you can add new permissions to your models also each user has set of permissions as well as group memberships individual users can have individual permissions and they inherit permissions from their group membership your view functions and templates can easily check the presence of absence of those permissions at any level of granularity you need to use and if this is not enough for you the profile add on gives you yet more options for defining user and their capabilities permissions roles responsibilities etc and if this is not enough for you you can define your own authentication schemes what is important is not to try and define groups that are actual subsets of users not casually defined titles or roles you never need to set permissions for sub set of group you need to have smaller groups groups defined around subsets of people django default permissions are around model access not row access within model on the other hand your problem is about subsets of rows in several models client store employee manager you will need basic set of fk among these items and some filters to subset the rows you may have trouble doing this with default admin pages you may need your own version of admin to make use of specialized filters if you cannot do it with the django permission system you should rethink your use cases seriously the django rest interface however is another beast entirely and requires some care and feeding
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.