prefix
stringclasses 1
value | input_text
stringlengths 19
27.3k
⌀ | target_text
stringlengths 2
24.8k
⌀ |
---|---|---|
QA
|
how do check whether file exists using python how do check whether file exists without using the try statement
|
you have the os path exists function import os path os path exists file path this returns true for both files and directories but you can additionally use os path isfile to test if it is file specifically
|
QA
|
how do check whether file exists using python how do check whether file exists without using the try statement
|
you can also use os path isfile return true if path is an existing regular file this follows symbolic links so both islink and isfile can be true for the same path import os path os path isfile fname if you need to be sure it is file starting with python the pathlib module offers an object oriented approach from pathlib import path my file path path to file if my file is file file exists
|
QA
|
python dns cannot get rrsig records no answer get dns records from python program using dns python can get various dnssec related records import dns resolver myresolver dns resolver resolver myresolver use edns print myresolver query sources org dnskey dns resolver answer object at xb ed print myresolver query ripe net nsec dns resolver answer object at but no rrsig records print myresolver query sources org rrsig traceback most recent call last file stdin line in module file usr lib python site packages dns resolver py line in query answer answer qname rdtype rdclass response file usr lib python site packages dns resolver py line in init raise noanswer tried several signed domains like absolight fr or ripe net trying with dig see that there are indeed rrsig records checking with tcpdump can see that dns python sends the correct query and receives correct replies here eight records ip au rrsig sources org ip rrsig domain dns python python aug gcc on linux
|
if you try this what happens print myresolver query sources org any rrsig
|
QA
|
classes in python in python is there any way to make class then make second version of that class with identical dat but which can be changed then reverted to be the same as the data in the original class so would make class with the numbers to as the data in it then make second class with the same names for sections or very similar mess around with the numbers in the second class then with one function then reset them to be the same as in the first class the only alternative have found is to make one aggravatingly long class with too many separate pieces of data in it to be readily usable
|
here is another answer kind of like pobk it uses the instance dict to do the work of saving resetting variables but does not require you to specify the names of them in your code you can call save at any time to save the state of the instance and reset to reset to that state class myreset def init self self self self save def save self self saved self dict copy def reset self self dict self saved copy myreset print reset print why do you want to do this it might not be the best only way
|
QA
|
how do check whether file exists using python how do check whether file exists without using the try statement
|
additionally os access if os access myfile os ok with open myfile as fp return fp read being ok ok and ok the flags to test for permissions doc
|
QA
|
what does blazeds livecycle data services do that something like pyamf or rubyamf not do am doing tech review and looking at amf integration with various backends rails python grails etc lots of options are out there question is what do the adobe products do blazeds etc that something like rubyamf pyamf do not
|
adobe has two products livecycle data services es lcds and blazeds blazeds contains subset of lcds features and was made open source unfortunately nio channels rtmp nio http and the datamanagement features are implemented only in lcds not blazeds blazeds can be used only to integrate flex with java backend it offers not only remoting services using amf serialization as rubyamf but also messaging and collaboration features take look at this link http livedocs adobe com blazeds blazeds devguide help html content lcoverview html also suppose that the support is better compared with rubyamf pyamf if your backend is java and you want to use only free product you can also use graniteds or weborb blazeds competitors
|
QA
|
django vs grails vs am wondering if there is such thing as django like ease of web app development combined with good deployment debugging and other tools django is very productive framework for building content heavy sites the best have tried and breath of fresh air compared to some of the java monstrosities out there however it is written in python which means there is little real support in the way of deployment packaging debugging profilers and other tools that make building and maintaining applications much easier ruby has similar issues and although do like ruby much better than like python get the impression that rails is roughly in the same boat at django when it comes to managing supporting the app has anyone here tried both django and grails or other web frameworks for non trivial projects how did they compare
|
by good deployment are you comparing it with java ear files which allow you to deploy web applications by uploading single file to ee server and to lesser extent war files ear files can have war files for dependent projects do not think django or rails have gotten quite to that point yet but could be wrong zuber pointed out an article with more details on the python side capistrano may help out on the ruby side unfortunately have not really worked with either python or ruby that much so cannot help out on profilers or debuggers
|
QA
|
how do get the name of python class as string what method do call to get the name of class
|
agree with mr shark but if you have an instance of class you will need to use its class member class test pass test test test name traceback most recent call last file stdin line in module attributeerror test instance has no attribute name test class class main test at eede
|
QA
|
how to programmatically enable disable network interfaces windows xp need to enable disable completely network interfaces from script in windows xp am looking for python solution but any general way eg wmi some command line la netsh some windows call is welcome and will be adjusted thanks
|
the devcon tool can control the nic but not the interface directly it is command line version of the device manager applet devcon disable id or portion of name devcon enable id or portion of name
|
QA
|
how to programmatically enable disable network interfaces windows xp need to enable disable completely network interfaces from script in windows xp am looking for python solution but any general way eg wmi some command line la netsh some windows call is welcome and will be adjusted thanks
|
this is vb net dim objectquery as new objectquery select from win networkadapter where netconnectionid is not null dim searcher as new managementobjectsearcher scope objectquery dim os as managementobject dim mocoll as managementobjectcollection searcher get dim list as string for each os in mocoll console writeline os netconnectionid next os that will get all the interfaces on you computer then you can do netsh to disable it netsh interface set interface disabled
|
QA
|
how to programmatically enable disable network interfaces windows xp need to enable disable completely network interfaces from script in windows xp am looking for python solution but any general way eg wmi some command line la netsh some windows call is welcome and will be adjusted thanks
|
cannot seem to find any basic api for controlling interfaces on msdn apart from the ras api but do not think they apply to non dialup connections as you suggest yourself netsh might be an option supposedly it also has programmatic interface http msdn microsoft com en us library ms vs aspx if you want to be pure python you can perhaps open set of pipes to communicate with an netsh process
|
QA
|
why is not the len function inherited by dictionaries and lists in python example list list len does not work len list works python being very object oriented do not understand why the len function is not inherited by the object plus keep trying the wrong solution since it appears as the logical one to me
|
maybe you are looking for len if that method exists then len calls it class spam def len self return spam len
|
QA
|
why is not the len function inherited by dictionaries and lists in python example list list len does not work len list works python being very object oriented do not understand why the len function is not inherited by the object plus keep trying the wrong solution since it appears as the logical one to me
|
it just is not you can however do len adding len method to class is what makes the len magic work
|
QA
|
why is not the len function inherited by dictionaries and lists in python example list list len does not work len list works python being very object oriented do not understand why the len function is not inherited by the object plus keep trying the wrong solution since it appears as the logical one to me
|
well there actually is length method it is just hidden list list len the len built in function appears to be simply wrapper for call to the hidden len method of the object not sure why they made the decision to implement things this way though
|
QA
|
how to programmatically enable disable network interfaces windows xp need to enable disable completely network interfaces from script in windows xp am looking for python solution but any general way eg wmi some command line la netsh some windows call is welcome and will be adjusted thanks
|
you may need to use wmi this may serve as good starting point http msdn microsoft com en us library aa aspx
|
QA
|
why is not the len function inherited by dictionaries and lists in python example list list len does not work len list works python being very object oriented do not understand why the len function is not inherited by the object plus keep trying the wrong solution since it appears as the logical one to me
|
guido explanation is here first of all chose len over len for hci reasons def len came much later there are two intertwined reasons actually both hci for some operations prefix notation just reads better than postfix prefix and infix operations have long tradition in mathematics which likes notations where the visuals help the mathematician thinking about problem compare the easy with which we rewrite formula like into to the clumsiness of doing the same thing using raw oo notation when read code that says len know that it is asking for the length of something this tells me two things the result is an integer and the argument is some kind of container to the contrary when read len have to already know that is some kind of container implementing an interface or inheriting from class that has standard len witness the confusion we occasionally have when class that is not implementing mapping has get or keys method or something that isn file has write method saying the same thing in another way see len as built in operation hate to lose that
|
QA
|
why is not the len function inherited by dictionaries and lists in python example list list len does not work len list works python being very object oriented do not understand why the len function is not inherited by the object plus keep trying the wrong solution since it appears as the logical one to me
|
the short answer backwards compatibility and there is not enough of difference for it to really matter for more detailed explanation read on the idiomatic python approach to such operations is special methods which are not intended to be called directly for example to make work for your own class you write add method to make sure that int spam properly converts your custom class write int method to make sure that len foo does something sensible write len method this is how things have always been with python and think it makes lot of sense for some things in particular this seems like sensible way to implement operator overloading as for the rest different languages disagree in ruby you would convert something to an integer by calling spam to directly instead of saying int spam you are right that python is an extremely object oriented language and that having to call an external function on an object to get its length seems odd on the other hand len silly walks is not any more onerous than silly walks len and guido has said that he actually prefers it http mail python org pipermail python november html
|
QA
|
how do check whether file exists using python how do check whether file exists without using the try statement
|
unlike isfile exists will yield true for directories so depending on if you want only plain files or also directories you will use isfile or exists here is simple repl output print os path isfile etc password txt true print os path isfile etc false print os path isfile does not exist false print os path exists etc password txt true print os path exists etc true print os path exists does not exist false
|
QA
|
why is not the len function inherited by dictionaries and lists in python example list list len does not work len list works python being very object oriented do not understand why the len function is not inherited by the object plus keep trying the wrong solution since it appears as the logical one to me
|
this way fits in better with the rest of the language the convention in python is that you add foo special methods to objects to make them have certain capabilities rather than deriving from specific base class for example an object is callable if it has call method iterable if it has an iter method supports access with if it has getitem and setitem one of these special methods is len which makes it have length accessible with len
|
QA
|
pythonwin python interactive she will calling constructors twice while answering http stackoverflow com questions python static variable noticed that pythonwin pywin build interpreter seems to evaluate twice pythonwin mar msc bit intel on win portions copyright mark hammond see help about pythonwin for further copyright information class def init self self class append while the python interpreter does the right thing python activepython activestate software inc based on python mar msc bit intel on win type help copyright credits or license for more information class def init self self class append
|
dave webb is correct and you can see this by adding print statement class def init self print inited self class append then as soon as you type the period in it prints inited prior to offering you the completion popup
|
QA
|
how to programmatically enable disable network interfaces windows xp need to enable disable completely network interfaces from script in windows xp am looking for python solution but any general way eg wmi some command line la netsh some windows call is welcome and will be adjusted thanks
|
so far have found the following python solution import wmi wmi wmi query select from win networkadapter where netconnectionid wifi enabledevice which is translated afaiu to the generic wmi error could be permissions
|
QA
|
why is not the len function inherited by dictionaries and lists in python example list list len does not work len list works python being very object oriented do not understand why the len function is not inherited by the object plus keep trying the wrong solution since it appears as the logical one to me
|
there is some good info below on why certain things are functions and other are methods it does indeed because some inconsistencies in the language http mail python org pipermail python dev january html
|
QA
|
python dns cannot get rrsig records no answer get dns records from python program using dns python can get various dnssec related records import dns resolver myresolver dns resolver resolver myresolver use edns print myresolver query sources org dnskey dns resolver answer object at xb ed print myresolver query ripe net nsec dns resolver answer object at but no rrsig records print myresolver query sources org rrsig traceback most recent call last file stdin line in module file usr lib python site packages dns resolver py line in query answer answer qname rdtype rdclass response file usr lib python site packages dns resolver py line in init raise noanswer tried several signed domains like absolight fr or ripe net trying with dig see that there are indeed rrsig records checking with tcpdump can see that dns python sends the correct query and receives correct replies here eight records ip au rrsig sources org ip rrsig domain dns python python aug gcc on linux
|
you probably mean rrsig any otherwise the order is wrong the class needs to be after the type print myresolver query sources org rrsig any traceback most recent call last file stdin line in module file usr lib python site packages dns resolver py line in query answer answer qname rdtype rdclass response file usr lib python site packages dns resolver py line in init raise noanswer dns resolver noanswer
|
QA
|
how can access app engine through corporate proxy have corporate proxy that supports https but not http connect even after authentication it just gives forbidden in response anything but http or https urls it uses http authenication not ntlm it is well documented the urllib does not work with https thru proxy app engine trys to connect to https url using urllib to update the app on nix urllib expects proxies to set using env variables export http proxy http mycorporateproxy export https proxy https mycorporateproxy this is sited as work around http code activestate com recipes also see http code google com googleappengine issues detail id none of these fixes have worked for me they seem to rely on the proxy server supporting http connect does anyone have any other work arounds sure am not the only one behind restrictive corporate proxy
|
do you mean it uses http basic auth before allowing proxying and does it then allow connect then you should be able to tunnel over it using http tunnel or proxytunnel
|
QA
|
how can get emacs key bindings in python idle use emacs primarily for coding python but sometimes use idle is there way to change the key bindings easily in idle to match emacs
|
readline module supposedly provides emacs like key bindings and even functionality however it is not available on windows but on unix therefore this might be viable solution if you are not using windows import readline since am running idle on windows it is unfortunately not an option for me
|
QA
|
running multiple sites from single python web framework what are come good or at least clever ways of running multiple sites from single common python web framework ie pylons turbogears etc know you can do redirection based on the domain or path to rewrite the uri to point at site specific location and have also seen some brutish if site site elseif elseif etc that would like to avoid
|
django has this built in see the sites framework as general technique include host column in your database schema attached to the data you want to be host specific then include the host http header in the query when you are retrieving data
|
QA
|
running multiple sites from single python web framework what are come good or at least clever ways of running multiple sites from single common python web framework ie pylons turbogears etc know you can do redirection based on the domain or path to rewrite the uri to point at site specific location and have also seen some brutish if site site elseif elseif etc that would like to avoid
|
use cherrypy as my web server which comes bundled with turbogears and simply run multiple instances of the cherrypy web server on different ports bound to localhost then configure apache with mod proxy and mod rewrite to transparently forward requests to the proper port based on the http request
|
QA
|
python time clock vs time time accuracy which is better to use for timing in python time clock or time time which one provides more accuracy for example start time clock do something elapsed time clock start vs start time time do something elapsed time time start
|
depends on what you care about if you mean wall time as in the time on the clock on your wall time clock provides no accuracy because it may manage cpu time
|
QA
|
python time clock vs time time accuracy which is better to use for timing in python time clock or time time which one provides more accuracy for example start time clock do something elapsed time clock start vs start time time do something elapsed time time start
|
clock floating point number return the cpu time or real time since the start of the process or since the first call to clock this has as much precision as the system records time floating point number return the current time in seconds since the epoch fractions of second may be present if the system clock provides them usually time is more precise because operating systems do not store the process running time with the precision they store the system time ie actual time
|
QA
|
opengl user interface programming am developing graphical application to present data not game but real workhorse app it needs to be cross platform so have chosen python opengl need blending textures etc pyopengl wx pywx windowing dialogs etc the last component wx raises the question can put together very nice looking app the prototypes look slick but when need to interact with the user to ask questions get input have to use wx it makes the app look inconsistent to have traditional ui with traditional dialogs and combos and text entry on top of full screen app with blending smooth motion textures etc has anyone developed gui using opengl and python can you share with me the toolkits and or tricks you used need combos text entry buttons radios option buttons tree view there are some toolkits out there but they are either incomplete or old and unmaintained great example is pyui http pyui sourceforge net looks slick but untouched for years
|
both wx and qt do an excellent job of creating an application that matches the os look and feel it is also possible to implment all the widgets yourself directly in openg this slashdot post lists some of the sets available http ask slashdot org askslashdot shtml tid fox is probably the most developed but looks like windows on all platforms
|
QA
|
python time clock vs time time accuracy which is better to use for timing in python time clock or time time which one provides more accuracy for example start time clock do something elapsed time clock start vs start time time do something elapsed time time start
|
the short answer is most of the time time clock will be better however if you are timing some hardware for example some algorithm you put in the gpu then time clock will get rid of this time and time time is the only solution left note whatever the method used the timing will depend on factors you cannot control when will the process switch how often this is worse with time time but exists also with time clock so you should never run one timing test only but always run series of test and look at mean variance of the times
|
QA
|
python time clock vs time time accuracy which is better to use for timing in python time clock or time time which one provides more accuracy for example start time clock do something elapsed time clock start vs start time time do something elapsed time time start
|
short answer use time clock for timing in python on nix systems clock returns the processor time as floating point number expressed in seconds on windows it returns the seconds elapsed since the first call to this function as floating point number time returns the the seconds since the epoch in utc as floating point number there is no guarantee that you will get better precision that second even though time returns floating point number also note that if the system clock has been set back between two calls to this function the second function call will return lower value
|
QA
|
python time clock vs time time accuracy which is better to use for timing in python time clock or time time which one provides more accuracy for example start time clock do something elapsed time clock start vs start time time do something elapsed time time start
|
as of time clock is deprecated and it is suggested to use time process time or time perf counter instead previously in according to the time module docs time clock on unix return the current processor time as floating point number expressed in seconds the precision and in fact the very definition of the meaning of processor time depends on that of the function of the same name but in any case this is the function to use for benchmarking python or timing algorithms on windows this function returns wall clock seconds elapsed since the first call to this function as floating point number based on the win function queryperformancecounter the resolution is typically better than one microsecond additionally there is the timeit module for benchmarking code snippets
|
QA
|
python time clock vs time time accuracy which is better to use for timing in python time clock or time time which one provides more accuracy for example start time clock do something elapsed time clock start vs start time time do something elapsed time time start
|
others have answered re time time vs time clock however if you are timing the execution of block of code for benchmarking profiling purposes you should take look at the timeit module
|
QA
|
python time clock vs time time accuracy which is better to use for timing in python time clock or time time which one provides more accuracy for example start time clock do something elapsed time clock start vs start time time do something elapsed time time start
|
on unix time clock measures the amount of cpu time that has been used by the current process so it is no good for measuring elapsed time from some point in the past on windows it will measure wall clock seconds elapsed since the first call to the function on either system time time will return seconds passed since the epoch if you are writing code that is meant only for windows either will work though you will use the two differently no subtraction is necessary for time clock if this is going to run on unix system or you want code that is guaranteed to be portable you will want to use time time
|
QA
|
search for host with mac address using python would like to search for given mac address on my network all from within python script already have map of all the active ip addresses in the network but cannot figure out how to glean the mac address any ideas
|
do not think there is built in way to get it from python itself my question is how are you getting the ip information from your network to get it from your local machine you could parse ifconfig unix or ipconfig windows with little difficulty
|
QA
|
search for host with mac address using python would like to search for given mac address on my network all from within python script already have map of all the active ip addresses in the network but cannot figure out how to glean the mac address any ideas
|
you need arp python standard library does not include any code for that so you either need to call an external program your os may have an arp utility or you need to build the packets yourself possibly with tool like scapy
|
QA
|
search for host with mac address using python would like to search for given mac address on my network all from within python script already have map of all the active ip addresses in the network but cannot figure out how to glean the mac address any ideas
|
depends on your platform if you are using nix you can use the arp command to look up the mac address for given ip assuming ipv address if that does not work you could ping the address and then look or if you have access to the raw network using bpf or some other mechanism you could send your own arp packets but that is probably overkill
|
QA
|
search for host with mac address using python would like to search for given mac address on my network all from within python script already have map of all the active ip addresses in the network but cannot figure out how to glean the mac address any ideas
|
if you want pure python solution you can take look at scapy to craft packets you need to send arp request and inspect replies or if you do not mind invoking external program you can use arping on un systems do not know of windows equivalent
|
QA
|
search for host with mac address using python would like to search for given mac address on my network all from within python script already have map of all the active ip addresses in the network but cannot figure out how to glean the mac address any ideas
|
it seems that there is not native way of doing this with python your best bet would be to parse the output of ipconfig all on windows or ifconfig on linux consider using os popen with some regexps
|
QA
|
search for host with mac address using python would like to search for given mac address on my network all from within python script already have map of all the active ip addresses in the network but cannot figure out how to glean the mac address any ideas
|
you would want to parse the output of arp but the kernel arp cache will only contain those ip address es if those hosts have communicated with the host where the python script is running ifconfig can be used to display the mac addresses of local interfaces but not those on the lan
|
QA
|
python time clock vs time time accuracy which is better to use for timing in python time clock or time time which one provides more accuracy for example start time clock do something elapsed time clock start vs start time time do something elapsed time time start
|
the difference is very platform specific clock is very different on windows than on linux for example for the sort of examples you describe you probably want the timeit module instead
|
QA
|
search for host with mac address using python would like to search for given mac address on my network all from within python script already have map of all the active ip addresses in the network but cannot figure out how to glean the mac address any ideas
|
mark pilgrim describes how to do this on windows for the current machine with the netbios module here you can get the netbios module as part of the win package available at python org unfortunately at the moment cannot find the docs on the module
|
QA
|
what is the best way to calculate or centroid as part of project at work have to calculate the centroid of set of points in space right now am doing it in way that seems simple but naive by taking the average of each set of points as in centroid average average average where and are arrays of floating point numbers seem to recall that there is way to get more accurate centroid but have not found simple algorithm for doing so anyone have any ideas or suggestions am using python for this but can adapt examples from other languages
|
potentially more efficient if you are calculating this multiple times you can speed this up quite bit by keeping two standing variables number of points sums dict sums of the locations for each point then changing and sums whenever points are created or destroyed this changes things from to for calculations at the cost of more work every time point is created moves or is destroyed
|
QA
|
running multiple sites from single python web framework what are come good or at least clever ways of running multiple sites from single common python web framework ie pylons turbogears etc know you can do redirection based on the domain or path to rewrite the uri to point at site specific location and have also seen some brutish if site site elseif elseif etc that would like to avoid
|
using multiple server instances on local ports is good idea but you do not need full featured web server to redirect http requests would use pound as reverse proxy to do the job it is small fast simple and does exactly what we need here what pound is reverse proxy it passes requests from client browsers to one or more back end servers load balancer it will distribute the requests from the client browsers among several back end servers while keeping session information an ssl wrapper pound will decrypt https requests from client browsers and pass them as plain http to the back end servers an http https sanitizer pound will verify requests for correctness and accept only well formed ones fail over server should back end server fail pound will take note of the fact and stop passing requests to it until it recovers request redirector requests may be distributed among servers according to the requested url
|
QA
|
how to best implement simple crash error reporting what would be the best way to implement simple crash error reporting mechanism details my app is cross platform mac windows linux and written in python so just need something that will send me small amount of text just timestamp and traceback which already generate and show in my error dialog it would be fine if it could simply email it but cannot think of way to do this without including username and password for the smtp server in the application should implement simple web service on the server side and have my app send it an http request with the info any better ideas thanks
|
the web hit is the way to go but make sure you pick good url your app will be hitting it for years to come
|
QA
|
how to best implement simple crash error reporting what would be the best way to implement simple crash error reporting mechanism details my app is cross platform mac windows linux and written in python so just need something that will send me small amount of text just timestamp and traceback which already generate and show in my error dialog it would be fine if it could simply email it but cannot think of way to do this without including username and password for the smtp server in the application should implement simple web service on the server side and have my app send it an http request with the info any better ideas thanks
|
pycrash
|
QA
|
how to best implement simple crash error reporting what would be the best way to implement simple crash error reporting mechanism details my app is cross platform mac windows linux and written in python so just need something that will send me small amount of text just timestamp and traceback which already generate and show in my error dialog it would be fine if it could simply email it but cannot think of way to do this without including username and password for the smtp server in the application should implement simple web service on the server side and have my app send it an http request with the info any better ideas thanks
|
whether you use smtp or http to send the data you need to have username password in the application to prevent just anyone from sending random data to you with that in mind suspect it would be easier to use smtp rather than http to send the data
|
QA
|
how to best implement simple crash error reporting what would be the best way to implement simple crash error reporting mechanism details my app is cross platform mac windows linux and written in python so just need something that will send me small amount of text just timestamp and traceback which already generate and show in my error dialog it would be fine if it could simply email it but cannot think of way to do this without including username and password for the smtp server in the application should implement simple web service on the server side and have my app send it an http request with the info any better ideas thanks
|
the web service is the best way but there are some caveats you should always ask the user if it is ok to send error feedback information you should be prepared to fail gracefully if there are network errors do not let failure to report crash impede recovery you should avoid including user identifying or sensitive information unless the user knows see and you should either use ssl or otherwise protect it some jurisdictions impose burdens on you that you might not want to deal with so it is best to simply not save such information like any web service make sure your service is not exploitable by miscreants
|
QA
|
how to best implement simple crash error reporting what would be the best way to implement simple crash error reporting mechanism details my app is cross platform mac windows linux and written in python so just need something that will send me small amount of text just timestamp and traceback which already generate and show in my error dialog it would be fine if it could simply email it but cannot think of way to do this without including username and password for the smtp server in the application should implement simple web service on the server side and have my app send it an http request with the info any better ideas thanks
|
some kind of simple web service would suffice you would have to consider security so not just anyone could make requests to your service on larger scale we considered jms messaging system put serialized object of data containing the traceback error message into queue and consume it every minutes generating reports alerts from that data
|
QA
|
how to best implement simple crash error reporting what would be the best way to implement simple crash error reporting mechanism details my app is cross platform mac windows linux and written in python so just need something that will send me small amount of text just timestamp and traceback which already generate and show in my error dialog it would be fine if it could simply email it but cannot think of way to do this without including username and password for the smtp server in the application should implement simple web service on the server side and have my app send it an http request with the info any better ideas thanks
|
cannot think of way to do this without including username and password for the smtp server in the application you only need username and password for authenticating yourself to smarthost you do not need it to send mail directly you need it to send mail through relay your isp mail server it is perfectly possible to send email without authentication that is why spam is so hard to stop having said that some isps block outbound traffic on port so the most robust alternative is an http post which is unlikely to be blocked by anything be sure to pick url that you will not feel restricted by later on or better yet have the application periodically check for updates so if you decide to change domains or something you can push an update in advance security is not really an issue you can fairly easily discard junk data so all that really concerns you is whether or not somebody would go to the trouble of constructing fake tracebacks to mess with you and that is very unlikely situation as for the payload pycrash can help you with that
|
QA
|
what are the pros and cons of the various python implementations am relatively new to python and have always used the standard cpython implementation have been wondering about the other implementations though particularly jython and ironpython what makes them better what makes them worse what other implementations are there guess what am looking for is summary and list of pros and cons for each implementation
|
pros access to the libraries available for jvm or clr cons both naturally lag behind cpython in terms of features
|
QA
|
what are the pros and cons of the various python implementations am relatively new to python and have always used the standard cpython implementation have been wondering about the other implementations though particularly jython and ironpython what makes them better what makes them worse what other implementations are there guess what am looking for is summary and list of pros and cons for each implementation
|
jython and ironpython are useful if you have an overriding need to interface with existing libraries written in different platform like if you have lines of java and you just want to write line python script not particularly useful for anything else in my opinion because they are perpetually few versions behind cpython due to community inertia stackless is interesting because it has support for green threads continuations etc sort of an erlang lite pypy is an experimental interpreter compiler that may one day supplant cpython but for now is more of testbed for new ideas
|
QA
|
what are the pros and cons of the various python implementations am relatively new to python and have always used the standard cpython implementation have been wondering about the other implementations though particularly jython and ironpython what makes them better what makes them worse what other implementations are there guess what am looking for is summary and list of pros and cons for each implementation
|
all of the implementations are listed here https wiki python org moin pythonimplementations cpython is the reference implementation and developed by guido and the core developers
|
QA
|
what is the easiest way to read foxpro dbf file from python have got bunch of foxpro vfp dbf files on my ubuntu system is there library to open these in python only need to read them and would preferably have access to the memo fields too update thanks cnu used yusdi santoso dbf py and it works nicely one gotcha the memo file name extension must be lower case fpt not fpt which was how the filename came over from windows
|
if you are still checking this have gpl foxpro to postgresql converter at https github com kstrauser pgdbf we use it to routinely copy our tables into postgresql for fast reporting
|
QA
|
what are the pros and cons of the various python implementations am relatively new to python and have always used the standard cpython implementation have been wondering about the other implementations though particularly jython and ironpython what makes them better what makes them worse what other implementations are there guess what am looking for is summary and list of pros and cons for each implementation
|
ironpython and jython use the runtime environment for net or java and with that comes just in time compilation and garbage collector different from the original cpython they might be also faster than cpython thanks to the jit but do not know that for sure downside in using jython or ironpython is that you cannot use native modules they can be only used in cpython
|
QA
|
how to programmatically enable disable network interfaces windows xp need to enable disable completely network interfaces from script in windows xp am looking for python solution but any general way eg wmi some command line la netsh some windows call is welcome and will be adjusted thanks
|
using the netsh interface usage set interface name ifname admin enabled disabled connect connected disconnected newname newname try including everything inside the outer brackets netsh interface set interface name thename admin disabled connect disconnected newname thename see also this ms kb page http support microsoft com kb you could follow either of their suggestions for disabling the adapter you will need to determine way to reference the hardware device if there will not be multiple adapters with the same name on the computer you could possibly go off of the description for the interface or pci id works well after that using devcon disable enable devcon is an add on console interface for the device manager
|
QA
|
what are the pros and cons of the various python implementations am relatively new to python and have always used the standard cpython implementation have been wondering about the other implementations though particularly jython and ironpython what makes them better what makes them worse what other implementations are there guess what am looking for is summary and list of pros and cons for each implementation
|
pypy is python implementation written in rpython wich is python subset rpython can be translated to run on vm or unlike standard python rpython can be statically compiled
|
QA
|
running multiple sites from single python web framework what are come good or at least clever ways of running multiple sites from single common python web framework ie pylons turbogears etc know you can do redirection based on the domain or path to rewrite the uri to point at site specific location and have also seen some brutish if site site elseif elseif etc that would like to avoid
|
using django on apache with mod python host multiple unrelated django sites simply with the following apache config virtualhost documentroot www site servername site com location sethandler python program setenv django settings module site settings pythonpath www sys path pythondebug on pythoninterpreter site location virtualhost virtualhost documentroot www site servername site com location sethandler python program setenv django settings module site settings pythonpath www sys path pythondebug on pythoninterpreter site location virtualhost no need for multiple apache instances or proxy servers using different pythoninterpreter directive for each site the name you enter is arbitrary keeps the namespaces separate
|
QA
|
python time clock vs time time accuracy which is better to use for timing in python time clock or time time which one provides more accuracy for example start time clock do something elapsed time clock start vs start time time do something elapsed time time start
|
to the best of my understanding time clock has as much precision as your system will allow it
|
QA
|
pros and cons of different approaches to web programming in python would like to do some server side scripting using python but am kind of lost with the number of ways to do that it starts with the do it yourself cgi approach and it seems to end with some pretty robust frameworks that would basically do all the job themselves and huge lot of stuff in between like web py pyroxide and django what are the pros and cons of the frameworks or approaches that you have worked on what trade offs are there for what kind of projects they do well and for what they do not edit have not got much experience with web programing yet would like to avoid the basic and tedious things like parsing the url for parameters etc on the other hand while the video of blog created in minutes with ruby on rails left me impressed realized that there were hundreds of things hidden from me which is cool if you need to write working webapp in no time but not that great for really understanding the magic and that is what seek now
|
if you want to go big choose django and you are set but if you want just to learn roll your own framework using already mentioned webob this can be really fun and am sure you will learn much more plus you can use components you like template system url dispatcher database layer sessions et caetera in last years built few large sites using django and all can say django will fill of your needs in of time remaining of work will take of the time no matter which framework you would use
|
QA
|
get list of xml attribute values in python need to get list of attribute values from child elements in python it is easiest to explain with an example given some xml like this elements parent name categorya child value child value child value parent parent name categoryb child value child value child value parent elements want to be able to do something like getvalues categorya getvalues categoryb it looks like job for xpath but am open to all recommendations would also like to hear about your favourite python xml libraries
|
must admit am fan of xmltramp due to its ease of use accessing the above becomes import xmltramp values xmltramp parse def getvalues values category cat parent for parent in values parent if parent name category cat values child value for child in parent child for parent in cat return cat values getvalues values categorya getvalues values categoryb
|
QA
|
get list of xml attribute values in python need to get list of attribute values from child elements in python it is easiest to explain with an example given some xml like this elements parent name categorya child value child value child value parent parent name categoryb child value child value child value parent elements want to be able to do something like getvalues categorya getvalues categoryb it looks like job for xpath but am open to all recommendations would also like to hear about your favourite python xml libraries
|
you can do this with beautifulsoup from beautifulsoup import beautifulstonesoup soup beautifulstonesoup xml def getvalues name return child value for child in soup find parent attrs name name findall child if you are doing work with html xml would recommend you take look at beautifulsoup it is similar to the dom tree but contains more functionality
|
QA
|
if it is decided that our system needs an overhaul what is the best way to go about it we are mainting web application that is built on classic asp using vbscript as the primary language we are in agreement that our backend framework if you will is out dated and does not provide us with the proper tools to move forward in quick manner we have pretty much embraced the current webmvc pattern that is all over the place and cannot do it in reasonable manner with the current technology the big missing features are proper dispatching and templating with inheritance amongst others currently there are two paths being discussed port the existing application to classic asp using jscript which will allow us to hopefully go from there to net msjscript without too much trouble and eventually end up on the net platform preferably the mvc stuff will be done by then asp net is not much better than were we are on now in our opinions this has been argued as the safer path with less risk than the next option albeit it might take slightly longer completely rewrite the application using some other technology right now the leader of the pack is python wsgi with custom framework orm and good templating solution there is wiggle room here for even django and other pre built solutions this method would hopefully be the quickest solution as we would probably run beta beside the actual product but it does have the potential for big waste of time if we cannot do not get it right this does not mean that our logic is gone as what we have built over the years is fairly stable as noted just difficult to deal with it is built on sql server with heavy use of stored procedures and published on iis just for little more background now the question has anyone taken either of the two paths above if so was it successful how could it have been better etc we are not looking to deviate much from doing one of those two things but some suggestions or other solutions would potentially be helpful
|
use this as an opportunity to remove unused features definitely go with the new language call it it will be lot less work to rebuild the of it that you really need start by wiping your brain clean of the whole application sit down with list of its overall goals then decide which features are needed based on which ones are used then redesign it with those features in mind and build love to delete code
|
QA
|
if it is decided that our system needs an overhaul what is the best way to go about it we are mainting web application that is built on classic asp using vbscript as the primary language we are in agreement that our backend framework if you will is out dated and does not provide us with the proper tools to move forward in quick manner we have pretty much embraced the current webmvc pattern that is all over the place and cannot do it in reasonable manner with the current technology the big missing features are proper dispatching and templating with inheritance amongst others currently there are two paths being discussed port the existing application to classic asp using jscript which will allow us to hopefully go from there to net msjscript without too much trouble and eventually end up on the net platform preferably the mvc stuff will be done by then asp net is not much better than were we are on now in our opinions this has been argued as the safer path with less risk than the next option albeit it might take slightly longer completely rewrite the application using some other technology right now the leader of the pack is python wsgi with custom framework orm and good templating solution there is wiggle room here for even django and other pre built solutions this method would hopefully be the quickest solution as we would probably run beta beside the actual product but it does have the potential for big waste of time if we cannot do not get it right this does not mean that our logic is gone as what we have built over the years is fairly stable as noted just difficult to deal with it is built on sql server with heavy use of stored procedures and published on iis just for little more background now the question has anyone taken either of the two paths above if so was it successful how could it have been better etc we are not looking to deviate much from doing one of those two things but some suggestions or other solutions would potentially be helpful
|
would not recommend jscript as that is definitely the road less traveled asp net mvc is rapidly maturing and think that you could begin migration to it simultaneously ramping up on the asp net mvc framework as its finalization comes through another option would be to use something like asp net subsonic or nhibernate
|
QA
|
get list of xml attribute values in python need to get list of attribute values from child elements in python it is easiest to explain with an example given some xml like this elements parent name categorya child value child value child value parent parent name categoryb child value child value child value parent elements want to be able to do something like getvalues categorya getvalues categoryb it looks like job for xpath but am open to all recommendations would also like to hear about your favourite python xml libraries
|
am not really an old hand at python but here is an xpath solution using libxml import libxml doc elements parent name categorya child value child value child value parent parent name categoryb child value child value child value parent elements doc libxml parsedoc doc def getvalues cat return attr content for attr in doc xpatheval elements parent name child value cat print getvalues categorya with result
|
QA
|
get list of xml attribute values in python need to get list of attribute values from child elements in python it is easiest to explain with an example given some xml like this elements parent name categorya child value child value child value parent parent name categoryb child value child value child value parent elements want to be able to do something like getvalues categorya getvalues categoryb it looks like job for xpath but am open to all recommendations would also like to hear about your favourite python xml libraries
|
using standard dom such as the stdlib minidom or pxdom def getvalues category for parent in document getelementsbytagname parent if parent getattribute name category return el getattribute value for el in parent getelementsbytagname child raise valueerror parent not found
|
QA
|
get list of xml attribute values in python need to get list of attribute values from child elements in python it is easiest to explain with an example given some xml like this elements parent name categorya child value child value child value parent parent name categoryb child value child value child value parent elements want to be able to do something like getvalues categorya getvalues categoryb it looks like job for xpath but am open to all recommendations would also like to hear about your favourite python xml libraries
|
elementtree unfortunately not which is the one included with python supports xpath like this import elementtree elementtree as xml def getvalues tree category parent tree find parent name category return child get value for child in parent then you can do tree xml parse data xml getvalues tree categorya getvalues tree categoryb lxml etree which also provides the elementtree interface will also work in the same way
|
QA
|
if it is decided that our system needs an overhaul what is the best way to go about it we are mainting web application that is built on classic asp using vbscript as the primary language we are in agreement that our backend framework if you will is out dated and does not provide us with the proper tools to move forward in quick manner we have pretty much embraced the current webmvc pattern that is all over the place and cannot do it in reasonable manner with the current technology the big missing features are proper dispatching and templating with inheritance amongst others currently there are two paths being discussed port the existing application to classic asp using jscript which will allow us to hopefully go from there to net msjscript without too much trouble and eventually end up on the net platform preferably the mvc stuff will be done by then asp net is not much better than were we are on now in our opinions this has been argued as the safer path with less risk than the next option albeit it might take slightly longer completely rewrite the application using some other technology right now the leader of the pack is python wsgi with custom framework orm and good templating solution there is wiggle room here for even django and other pre built solutions this method would hopefully be the quickest solution as we would probably run beta beside the actual product but it does have the potential for big waste of time if we cannot do not get it right this does not mean that our logic is gone as what we have built over the years is fairly stable as noted just difficult to deal with it is built on sql server with heavy use of stored procedures and published on iis just for little more background now the question has anyone taken either of the two paths above if so was it successful how could it have been better etc we are not looking to deviate much from doing one of those two things but some suggestions or other solutions would potentially be helpful
|
whatever you do see if you can manage to follow plan where you do not have to port the application all in one big bang it is tempting to throw it all away and start from scratch but if you can manage to do it gradually the mistakes you do will not cost so much and because so much panic
|
QA
|
get list of xml attribute values in python need to get list of attribute values from child elements in python it is easiest to explain with an example given some xml like this elements parent name categorya child value child value child value parent parent name categoryb child value child value child value parent elements want to be able to do something like getvalues categorya getvalues categoryb it looks like job for xpath but am open to all recommendations would also like to hear about your favourite python xml libraries
|
my preferred python xml library is lxml which wraps libxml xpath does seem the way to go here so would write this as something like from lxml import etree def getvalues xml category return attrib value for in xml findall parent name category xml etree parse open filename xml print getvalues xml categorya print getvalues xml categoryb
|
QA
|
if it is decided that our system needs an overhaul what is the best way to go about it we are mainting web application that is built on classic asp using vbscript as the primary language we are in agreement that our backend framework if you will is out dated and does not provide us with the proper tools to move forward in quick manner we have pretty much embraced the current webmvc pattern that is all over the place and cannot do it in reasonable manner with the current technology the big missing features are proper dispatching and templating with inheritance amongst others currently there are two paths being discussed port the existing application to classic asp using jscript which will allow us to hopefully go from there to net msjscript without too much trouble and eventually end up on the net platform preferably the mvc stuff will be done by then asp net is not much better than were we are on now in our opinions this has been argued as the safer path with less risk than the next option albeit it might take slightly longer completely rewrite the application using some other technology right now the leader of the pack is python wsgi with custom framework orm and good templating solution there is wiggle room here for even django and other pre built solutions this method would hopefully be the quickest solution as we would probably run beta beside the actual product but it does have the potential for big waste of time if we cannot do not get it right this does not mean that our logic is gone as what we have built over the years is fairly stable as noted just difficult to deal with it is built on sql server with heavy use of stored procedures and published on iis just for little more background now the question has anyone taken either of the two paths above if so was it successful how could it have been better etc we are not looking to deviate much from doing one of those two things but some suggestions or other solutions would potentially be helpful
|
it works out better than you would believe recently did large reverse engineering job on hideous old collection of code function by function reallocated the features that were still relevant into classes wrote unit tests for the classes and built up what looked like replacement application it had some of the original logic flow through the classes and some classes were poorly designed mostly this was because of subset of the global variables that was too hard to tease apart it passed unit tests at the class level and at the overall application level the legacy source was mostly used as kind of specification in to ferret out the really obscure business rules last year wrote project plan for replacing year old cobol the customer was leaning toward java prototyped the revised data model in python using django as part of the planning effort could demo the core transactions before was done planning note it was quicker to build the model and admin interface in django than to plan the project as whole because of the we need to use java mentality the resulting project will be larger and more expensive than finishing the django demo with no real value to balance that cost also did the same basic prototype in django for vb desktop application that needed to become web application built the model in django loaded legacy data and was up and running in few weeks used that working prototype to specify the rest of the conversion effort note had working django implementation model and admin pages only that used to plan the rest of the effort the best part about doing this kind of prototyping in django is that you can mess around with the model unit tests and admin pages until you get it right once the model right you can spend the rest of your time fiddling around with the user interface until everyone is happy
|
QA
|
setting environment variables for mercurial hook am trying to call she will script that sets bunch of environment variables on our server from mercurial hook the she will script gets called fine when new changegroup comes in but the environment variables are not carrying over past the call to the she will script my hgrc file on the respository looks like this hooks changegroup shell script changegroup env env can see the output of the she will script and then the output of the env command but the env command does not include the new environment variables set by the she will script have verified that the she will script works fine when run by itself but when run in the context of the mercurial hook it does not properly set the environment thank you guys for any help you can provide
|
she will scripts cannot modify their enviroment http tldp org ldp abs html gotchas html script may not export variables back to its parent process the she will or to the environment just as we learned in biology child process can inherit from parent but not vice versa cat eg sh export foo bar bash eg sh echo foo also the problem is greater as you have multiple calls of bash bash hg bash she will script bash env call it would be like thinking could set variable in one php script and then magically get it with another simply by running one after the other
|
QA
|
how do you configure django for simple development and deployment tend to use sqlite when doing django development but on live server something more robust is often needed mysql postgresql for example invariably there are other changes to make to the django settings as well different logging locations intensities media paths etc how do you manage all these changes to make deployment simple automated process
|
update django configurations has been released which is probably better option for most people than doing it manually if you would prefer to do things manually my earlier answer still applies have multiple settings files settings local py host specific configuration such as database name file paths etc settings development py configuration used for development debug true settings production py configuration used for production server email tie these all together with settings py file that firstly imports settings local py and then one of the other two it decides which to load by two settings inside settings local py development hosts and production hosts settings py calls platform node to find the hostname of the machine it is running on and then looks for that hostname in the lists and loads the second settings file depending on which list it finds the hostname in that way the only thing you really need to worry about is keeping the settings local py file up to date with the host specific configuration and everything else is handled automatically check out an example here
|
QA
|
how do you configure django for simple development and deployment tend to use sqlite when doing django development but on live server something more robust is often needed mysql postgresql for example invariably there are other changes to make to the django settings as well different logging locations intensities media paths etc how do you manage all these changes to make deployment simple automated process
|
have two files settings base py which contains common default settings and which is checked into source control each deployment has separate settings py which executes from settings base import at the beginning and then overrides as needed
|
QA
|
how do unit test an init method of python class with assertraises have class class myclass def init self foo if foo raise error foo is not equal to and unit test that is supposed to make sure the incorrect arg passed to the constructor properly raises an error def testinsufficientargs self foo self assertraises error myclass myclass error foo but get nameerror global name error is not defined why where should be defining this error object thought it was built in as default exception type no
|
error in this example could be any exception object think perhaps you have read code example that used it as metasyntatic placeholder to mean the appropriate exception class the baseclass of all exceptions is called exception and most of its subclasses are descriptive names of the type of error involved such as oserror valueerror nameerror typeerror in this case the appropriate error is valueerror the value of foo was wrong therefore valueerror would recommend replacing error with valueerror in your script here is complete version of the code you are trying to write am duplicating everything because you have weird keyword argument in your original example that you seem to be conflating with an assignment and am using the failunless function name because that is the non aliased name of the function class myclass def init self foo if foo raise valueerror foo is not equal to import unittest class testfoo unittest testcase def testinsufficientargs self foo self failunlessraises valueerror myclass foo if name main unittest main the output is ran test in ok there is flaw in the unit testing library unittest that other unit testing frameworks fix you will note that it is impossible to gain access to the exception object from the calling context if you want to fix this you will have to redefine that method in subclass of unittest this is an example of it in use class testfoo unittest testcase def failunlessraises self excclass callableobj args kwargs try callableobj args kwargs except excclass excobj return excobj actually return the exception object else if hasattr excclass name excname excclass name else excname str excclass raise self failureexception not raised excname def testinsufficientargs self foo excobj self failunlessraises valueerror myclass foo self failunlessequal excobj foo is not equal to have copied the failunlessraises function from unittest py from python and modified it slightly
|
QA
|
how do unit test an init method of python class with assertraises have class class myclass def init self foo if foo raise error foo is not equal to and unit test that is supposed to make sure the incorrect arg passed to the constructor properly raises an error def testinsufficientargs self foo self assertraises error myclass myclass error foo but get nameerror global name error is not defined why where should be defining this error object thought it was built in as default exception type no
|
think you are thinking of exceptions replace the word error in your description with exception and you should be good to go
|
QA
|
how do unit test an init method of python class with assertraises have class class myclass def init self foo if foo raise error foo is not equal to and unit test that is supposed to make sure the incorrect arg passed to the constructor properly raises an error def testinsufficientargs self foo self assertraises error myclass myclass error foo but get nameerror global name error is not defined why where should be defining this error object thought it was built in as default exception type no
|
how about this class myclass def init self foo if foo raise exception foo is not equal to import unittest class tests unittest testcase def testsufficientargs self foo myclass foo def testinsufficientargs self foo self assertraises exception myclass foo if name main unittest main
|
QA
|
what is the best way to calculate or centroid as part of project at work have to calculate the centroid of set of points in space right now am doing it in way that seems simple but naive by taking the average of each set of points as in centroid average average average where and are arrays of floating point numbers seem to recall that there is way to get more accurate centroid but have not found simple algorithm for doing so anyone have any ideas or suggestions am using python for this but can adapt examples from other languages
|
you vaguely mention way to get more accurate centroid maybe you are talking about centroid that is not affected by outliers for example the average household income in the usa is probably very high because small number of very rich people skew the average they are the outliers for that reason statisticians use the median instead one way to obtain the median is to sort the values then pick the value halfway down the list maybe you are looking for something like this but for or points the problem is in and higher you cannot sort there is no natural order nevertheless there are ways to get rid of outliers one way is to find the convex hull of the points the convex hull has all the points on the outside of the set of points if you do this and throw out the points that are on the hull you will be throwing out the outliers and the points that remain will give more representative centroid you can even repeat this process several times and the result is kind like peeling an onion in fact it is called convex hull peeling
|
QA
|
pygame within pygtk application what is the best way to use pygame sdl within pygtk application am searching for method that allows me to have drawing area in the gtk window and at the same time being able to manage both gtk and sdl events
|
tried doing this myself while ago and never got it to work perfectly actually never got it to work at all under windows as it kept crashing the entire os and ran out of patience continued to use it though as it was only important it ran on linux and was only small project would strongly recommend you investigate alternatives it always felt like nasty hack and made me feel dirty
|
QA
|
in python how do you take tokenized input such as with the in can have take input like this cin and can be int can be float and can be whatever how do do the same in python input and raw input the way am using them do not seem to be giving me the desired results
|
you generally should not use input in production code if you want an int and then float try this line raw input split int line float line join line it all depends on what exactly you are trying to accomplish but remember that readability counts obscure one liners may seem cool but in the face of maintainability try to choose something sensible do not forget to check for errors with try except valueerror indexerror
|
QA
|
in python how do you take tokenized input such as with the in can have take input like this cin and can be int can be float and can be whatever how do do the same in python input and raw input the way am using them do not seem to be giving me the desired results
|
depending upon what you are doing something like the getopt module could be useful but only in certain situations and am not sure if it would apply in yours
|
QA
|
how do split string into list if have this string what is the most efficient approach for creating this list
|
regular expressions import re splitter re compile splitter split you can expand the regular expression to include any other characters you want to split on
|
QA
|
how do split string into list if have this string what is the most efficient approach for creating this list
|
re compile split
|
QA
|
how do split string into list if have this string what is the most efficient approach for creating this list
|
you can use split from the re module re split pattern string maxsplit flags split string by the occurrences of pattern if capturing parentheses are used in pattern then the text of all groups in the pattern are also returned as part of the resulting list example code import re data re split when the unicode flag is not specified matches any non digit character this is equivalent to the set
|
QA
|
in python how do you take tokenized input such as with the in can have take input like this cin and can be int can be float and can be whatever how do do the same in python input and raw input the way am using them do not seem to be giving me the desired results
|
since the cin reads from sys stdin you will often do something more like the following import sys tokens sys stdin read split try int token float token except valueerror print handle the invalid input
|
QA
|
how do split string into list if have this string what is the most efficient approach for creating this list
|
this looks like parsing problem and thus am compelled to present solution based on parsing techniques while it may seem that you want to split this string think what you actually want to do is tokenize it tokenization or lexxing is the compilation step before parsing have amended my original example in an edit to implement proper recursive decent parser here this is the easiest way to implement parser by hand import re patterns number re compile re compile re compile re compile re compile whitespace re compile def tokenize string while string strip off whitespace whitespace match string if string string end for tokentype pattern in patterns pattern match string if yield tokentype group string string end def parsenumber tokens tokentype literal tokens pop assert tokentype number return int literal def parsemultiplication tokens product parsenumber tokens while tokens and tokens in tokentype literal tokens pop if tokentype product parsenumber tokens elif tokentype product parsenumber tokens else raise valueerror parse error unexpected tokentype literal return product def parseaddition tokens total parsemultiplication tokens while tokens and tokens in tokentype literal tokens pop if tokentype total parsemultiplication tokens elif tokentype total parsemultiplication tokens else raise valueerror parse error unexpected tokentype literal return total def parse tokens tokenlist list tokens returnvalue parseaddition tokenlist if tokenlist print unconsumed data tokenlist return returnvalue def main string for tokentype literal in tokenize string print tokentype literal print parse tokenize string if name main main implementation of handling of brackets is left as an exercise for the reader this example will correctly do multiplication before addition
|
QA
|
how do split string into list if have this string what is the most efficient approach for creating this list
|
am sure tim meant splitter re compile if you copy exactly what he has down you only get the digits not the operators
|
QA
|
how do generate histogram for given probability distribution for functional testing server am trying to automate functional testing of server using realistic frequency distribution of requests sort of load testing sort of simulation have chosen the weibull distribution as it sort of matches the distribution have observed ramps up quickly drops off quickly but not instantly use this distribution to generate the number of requests that should be sent each day between given start and end date have hacked together an algorithm in python that sort of works but it feels kludgy how many days end date start date days freqs defaultdict int for in xrange how many responses freqs int how many days weibullvariate timeline day start date for freq in sorted freqs iteritems timeline append day freq day timedelta days return timeline what better ways are there to do this
|
another solution is to use rpy which puts all of the power of are including lots of tools for distributions easily into python
|
QA
|
calling an external command in python how can call an external command as if would typed it at the unix she will or windows command prompt from within python script
|
import os os system your command note that this is dangerous since the command is not cleaned leave it up to you to google for the relevant docs on the os and sys modules there are bunch of functions exec spawn that will do similar things
|
QA
|
calling an external command in python how can call an external command as if would typed it at the unix she will or windows command prompt from within python script
|
import os cmd ls al os system cmd if you want to return the results of the command you can use os popen however this is deprecated since version in favor of the subprocess module which other answers have covered well
|
QA
|
calling an external command in python how can call an external command as if would typed it at the unix she will or windows command prompt from within python script
|
look at the subprocess module in the stdlib from subprocess import call call ls the advantage of subprocess vs system is that it is more flexible you can get the stdout stderr the real status code better error handling etc think os system is deprecated too or will be https docs python org library subprocess html replacing older functions with the subprocess module for quick dirty one time scripts os system is enough though
|
QA
|
calling an external command in python how can call an external command as if would typed it at the unix she will or windows command prompt from within python script
|
would recommend using the subprocess module instead of os system because it does she will escaping for you and is therefore much safer http docs python org library subprocess html subprocess call ping localhost
|
QA
|
calling an external command in python how can call an external command as if would typed it at the unix she will or windows command prompt from within python script
|
https docs python org library subprocess html or for very simple command import os os system cat testfile
|
QA
|
calling an external command in python how can call an external command as if would typed it at the unix she will or windows command prompt from within python script
|
os system has been superceeded by the subprocess module use subproccess instead
|
QA
|
calling an external command in python how can call an external command as if would typed it at the unix she will or windows command prompt from within python script
|
os system is ok but kind of dated it is also not very secure instead try subprocess subprocess does not call sh directly and is therefore more secure than os system get more information at https docs python org library subprocess html
|
QA
|
how do you configure django for simple development and deployment tend to use sqlite when doing django development but on live server something more robust is often needed mysql postgresql for example invariably there are other changes to make to the django settings as well different logging locations intensities media paths etc how do you manage all these changes to make deployment simple automated process
|
in addition to the multiple settings files mentioned by jim also tend to place two settings into my settings py file at the top base dir and base url set to the path of the code and the url to the base of the site all other settings are modified to append themselves to these base dir home sean myapp media root smedia basedir so when moving the project only have to edit these settings and not search the whole file would also recommend looking at fabric and capistrano ruby tool but it can be used to deploy django applications which facilitate automation of remote deployment
|
QA
|
if it is decided that our system needs an overhaul what is the best way to go about it we are mainting web application that is built on classic asp using vbscript as the primary language we are in agreement that our backend framework if you will is out dated and does not provide us with the proper tools to move forward in quick manner we have pretty much embraced the current webmvc pattern that is all over the place and cannot do it in reasonable manner with the current technology the big missing features are proper dispatching and templating with inheritance amongst others currently there are two paths being discussed port the existing application to classic asp using jscript which will allow us to hopefully go from there to net msjscript without too much trouble and eventually end up on the net platform preferably the mvc stuff will be done by then asp net is not much better than were we are on now in our opinions this has been argued as the safer path with less risk than the next option albeit it might take slightly longer completely rewrite the application using some other technology right now the leader of the pack is python wsgi with custom framework orm and good templating solution there is wiggle room here for even django and other pre built solutions this method would hopefully be the quickest solution as we would probably run beta beside the actual product but it does have the potential for big waste of time if we cannot do not get it right this does not mean that our logic is gone as what we have built over the years is fairly stable as noted just difficult to deal with it is built on sql server with heavy use of stored procedures and published on iis just for little more background now the question has anyone taken either of the two paths above if so was it successful how could it have been better etc we are not looking to deviate much from doing one of those two things but some suggestions or other solutions would potentially be helpful
|
do not throw away your code it is the single worst mistake you can make on large codebase see things you should never do part you have invested lot of effort into that old code and worked out many bugs throwing it away is classic developer mistake and one have done many times it makes you feel better like spring cleaning but you do not need to buy new apartment and all new furniture to outfit your house you can work on one room at time and maybe some things just need new paintjob hence this is where refactoring comes in for new functionality in your app write it in and call it from your classic asp you will be forced to be modular when you rewrite this new code when you have time refactor parts of your old code into as well and work out the bugs as you go eventually you will have replaced your app with all new code you could also write your own compiler we wrote one for our classic asp app long time ago to allow us to output php it is called wasabi and think it is the reason jeff atwood thought joel spolsky went off his rocker actually maybe we should just ship it and then you could use that it allowed us to switch our entire codebase to net for the next release while only rewriting very small portion of our source it also caused bunch of people to call us crazy but writing compiler is not that complicated and it gave us lot of flexibility also if this is an internal only app just leave it do not rewrite it you are the only customer and if the requirement is you need to run it as classic asp you can meet that requirement
|
QA
|
if it is decided that our system needs an overhaul what is the best way to go about it we are mainting web application that is built on classic asp using vbscript as the primary language we are in agreement that our backend framework if you will is out dated and does not provide us with the proper tools to move forward in quick manner we have pretty much embraced the current webmvc pattern that is all over the place and cannot do it in reasonable manner with the current technology the big missing features are proper dispatching and templating with inheritance amongst others currently there are two paths being discussed port the existing application to classic asp using jscript which will allow us to hopefully go from there to net msjscript without too much trouble and eventually end up on the net platform preferably the mvc stuff will be done by then asp net is not much better than were we are on now in our opinions this has been argued as the safer path with less risk than the next option albeit it might take slightly longer completely rewrite the application using some other technology right now the leader of the pack is python wsgi with custom framework orm and good templating solution there is wiggle room here for even django and other pre built solutions this method would hopefully be the quickest solution as we would probably run beta beside the actual product but it does have the potential for big waste of time if we cannot do not get it right this does not mean that our logic is gone as what we have built over the years is fairly stable as noted just difficult to deal with it is built on sql server with heavy use of stored procedures and published on iis just for little more background now the question has anyone taken either of the two paths above if so was it successful how could it have been better etc we are not looking to deviate much from doing one of those two things but some suggestions or other solutions would potentially be helpful
|
do not try and go more features then currently exists or scheduled instead build your new platform with the intent of resolving the current issues with the code base maintainability speed wtf and go from there
|
QA
|
how do split string into list if have this string what is the most efficient approach for creating this list
|
import re re findall matches consecutive digits or consecutive non digits each match is returned as new element in the list depending on the usage you may need to alter the regular expression such as if you need to match numbers with decimal point re findall
|
QA
|
how do split string into list if have this string what is the most efficient approach for creating this list
|
another solution to this would be to avoid writing calculator like that altogether writing an rpn parser is much simpler and does not have any of the ambiguity inherent in writing math with infix notation import operator math calc operands operator add operator sub operator mul operator truediv operator div operator mod operator pow math pow abs operator abs ceil math ceil floor math floor round round trunc int log math log ln math log pi lambda math pi lambda math def calculate inp stack for tok in inp split if tok in self calc operands pops func self calc operands tok args stack pop for in xrange pops args reverse stack append func args elif in tok stack append float tok else stack append int tok if not stack raise valueerror no items on the stack return stack pop if stack raise valueerror item left on the stack len stack calculate
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.