prefix
stringclasses
1 value
input_text
stringlengths
19
27.3k
target_text
stringlengths
2
24.8k
QA
how can find the full path to font from its display name on mac am using the photoshop javascript api to find the fonts in given psd given font name returned by the api want to find the actual physical font file that that font name corresponds to on the disc this is all happening in python program running on osx so guess am looking for one of some photoshop javascript python function an osx api that can call from python
open up terminal applications utilities terminal and type this in locate insertfonthere this will spit out every file that has the name you want warning there may be alot to wade through
QA
how can find the full path to font from its display name on mac am using the photoshop javascript api to find the fonts in given psd given font name returned by the api want to find the actual physical font file that that font name corresponds to on the disc this is all happening in python program running on osx so guess am looking for one of some photoshop javascript python function an osx api that can call from python
have not been able to find anything that does this directly think you will have to iterate through the various font folders on the system system library fonts library fonts and there can probably be user level directory as well library fonts
QA
get preview jpeg of pdf on windows have cross platform python application which needs to generate jpeg preview of the first page of pdf on the mac am spawning sips is there something similarly simple can do on windows
you can use imagemagick convert utility for this see some examples in http studio imagemagick org pipermail magick users may html convert taxes pdf taxes jpg will convert two page pdf file into jpeg files taxes jpg taxes jpg can also convert these jpegs to thumbnail as follows convert size taxes jpg geometry profile thumbnail jpg can even convert the pdf directly to jpeg thumbnail as follows convert size taxes pdf geometry profile thumbnail jpg this will result in thumbnail jpg and thumbnail jpg for the two pages
QA
continuous integration system for python codebase am starting work on hobby project with python codebase and would like to set up some form of continuous integration running battery of test cases each time check in is made and sending nag mails to responsible persons when the tests fail similar to cruisecontrol or teamcity realize could do this with hooks in most vcses but that requires that the tests run on the same machine as the version control server which is not as elegant as would like does anyone have any suggestions for small user friendly open source continuous integration system suitable for python codebase
one possibility is hudson it is written in java but there is integration with python projects hudson embraces python have never tried it myself however update sept after trademark dispute hudson has been renamed to jenkins
QA
continuous integration system for python codebase am starting work on hobby project with python codebase and would like to set up some form of continuous integration running battery of test cases each time check in is made and sending nag mails to responsible persons when the tests fail similar to cruisecontrol or teamcity realize could do this with hooks in most vcses but that requires that the tests run on the same machine as the version control server which is not as elegant as would like does anyone have any suggestions for small user friendly open source continuous integration system suitable for python codebase
we run buildbot trac at work have not used it too much since my code base is not part of the release cycle yet but we run the tests on different environments osx linux win and it sends emails and it is written in python
QA
cx oracle how do iterate over result set there are several ways to iterate over result set what are the tradeoff of each
the canonical way is to use the built in cursor iterator curs execute select from people for row in curs print row you can use fetchall to get all rows at once for row in curs fetchall print row it can be convenient to use this to create python list containing the values returned curs execute select first name from people names row for row in curs fetchall this can be useful for smaller result sets but can have bad side effects if the result set is large you have to wait for the entire result set to be returned to your client process you may eat up lot of memory in your client to hold the built up list it may take while for python to construct and deconstruct the list which you are going to immediately discard anyways if you know there is single row being returned in the result set you can call fetchone to get the single row curs execute select max from maxvalue curs fetchone finally you can loop over the result set fetching one row at time in general there is no particular advantage in doing this over using the iterator row curs fetchone while row print row row curs fetchone
QA
continuous integration system for python codebase am starting work on hobby project with python codebase and would like to set up some form of continuous integration running battery of test cases each time check in is made and sending nag mails to responsible persons when the tests fail similar to cruisecontrol or teamcity realize could do this with hooks in most vcses but that requires that the tests run on the same machine as the version control server which is not as elegant as would like does anyone have any suggestions for small user friendly open source continuous integration system suitable for python codebase
second the buildbot trac integration you can find more information about the integration on the buildbot website at my previous job we wrote and used the plugin they mention tracbb what the plugin does is rewriting all of the buildbot urls so you can use buildbot from within trac http example com tracbb the really nice thing about buildbot is that the configuration is written in python you can integrate your own python code directly to the configuration it is also very easy to write your own buildsteps to execute specific tasks we used buildsteps to get the source from svn pull the dependencies publish test results to webdav etcetera wrote an interface so we could send signals with build results when the build failed we switched on red lava lamp when the build succeeded green lava lamp switched on good times
QA
using in to match an attribute of python objects in an array do not remember whether was dreaming or not but seem to recall there being function which allowed something like foo in iter attr array of python objects attribute name have looked over the docs but this kind of thing does not fall under any obvious listed headers
no you were not dreaming python has pretty excellent list comprehension system that let us you manipulate lists pretty elegantly and depending on exactly what you want to accomplish this can be done couple of ways in essence what you are doing is saying for item in list if criteria matches and from that you can just iterate through the results or dump the results into new list am going to crib an example from dive into python here because it is pretty elegant and they are smarter than am here they are getting list of files in directory then filtering the list for all files that match regular expression criteria files os listdir path test re compile test py re ignorecase files for in files if test search you could do this without regular expressions for your example for anything where your expression at the end returns true for match there are other options like using the filter function but if were going to choose would go with this eric sipple
QA
using in to match an attribute of python objects in an array do not remember whether was dreaming or not but seem to recall there being function which allowed something like foo in iter attr array of python objects attribute name have looked over the docs but this kind of thing does not fall under any obvious listed headers
are you looking to get list of objects that have certain attribute if so list comprehension is the right way to do this result obj for obj in listofobjs if hasattr obj attributename
QA
using in to match an attribute of python objects in an array do not remember whether was dreaming or not but seem to recall there being function which allowed something like foo in iter attr array of python objects attribute name have looked over the docs but this kind of thing does not fall under any obvious listed headers
what was thinking of can be achieved using list comprehensions but thought that there was function that did this in slightly neater way bar is list of objects all of which have the attribute id the mythical functional way foo foo in iter attr bar id the list comprehension way foo foo in obj id for obj in bar in retrospect the list comprehension way is pretty neat anyway
QA
class views in django django view points to function which can be problem if you want to change only bit of functionality yes could have million keyword arguments and even more if statements in the function but was thinking more of an object oriented approach for example have page that displays user this page is very similar to page that displays group but it is still not so similar to just use another data model group also has members etc one way would be to point views to class methods and then extend that class has anyone tried this approach or has any other idea
sounds to me like you are trying to combine things that should not be combined if you need to do different processing in your view depending on if it is user or group object you are trying to look at then you should use two different view functions on the other hand there can be common idioms you would want to extract out of your object detail type views perhaps you could use decorator or just helper functions dan
QA
python and mysql can get python to work with postgresql but cannot get it to work with mysql the main problem is that on the shared hosting account have do not have the ability to install things such as django or pysql generally fail when installing them on my computer so maybe it is good cannot install on the host found bpgsql really good because it does not require an install it is single file that can look at read and then call the functions of does anybody know of something like this for mysql
do not have any experience with http www siteground com as web host personally this is just guess but it is common for shared host to support python and mysql with the mysqldb module godaddy does this try the following cgi script to see if mysqldb is installed usr bin pythonmodule name mysqldb head content type text html is module nametry import module name print head installed except importerror print head not installed
QA
how do use python itertools groupby have not been able to find an understandable explanation of how to actually use python itertools groupby function what am trying to do is this take list in this case the children of an objectified lxml element divide it into groups based on some criteria then later iterate over each of these groups separately have reviewed the documentation and the examples but have had trouble trying to apply them beyond simple list of numbers so how do use of itertools groupby is there another technique should be using pointers to good prerequisite reading would also be appreciated
can you show us your code the example on the python docs is quite straightforward groups uniquekeys for in groupby data keyfunc groups append list store group iterator as list uniquekeys append so in your case data is list of nodes keyfunc is where the logic of your criteria function goes and then groupby groups the data you must be careful to sort the data by the criteria before you call groupby or it will not work groupby method actually just iterates through list and whenever the key changes it creates new group
QA
python and mysql can get python to work with postgresql but cannot get it to work with mysql the main problem is that on the shared hosting account have do not have the ability to install things such as django or pysql generally fail when installing them on my computer so maybe it is good cannot install on the host found bpgsql really good because it does not require an install it is single file that can look at read and then call the functions of does anybody know of something like this for mysql
uploaded it and got an internal error premature end of script headers after much playing around found that if had import cgiimport cgitb cgitb enable import mysqldb it would give me much more useful answer and say that it was not installed you can see it yourself http woarl com db py oddly enough this would produce an error import mysqldbimport cgiimport cgitb cgitb enable looked at some of the other files had up there and it seems that library was one of the ones had already tried
QA
adding method to an existing object instance have read that it is possible to add method to an existing object not in the class definition in python think this is called monkey patching or in some cases duck punching understand that it is not always good decision to do so but how might one do this update est that looks like good answer john downey tried it but it appears that it ends up being not true method your example defines the new patch function with an argument of self but if you write actual code that way the now patched class method asks for an argument named self it does not automagically recognize it as the object to which it is supposed to bind which is what would happen if defined within the class definition meaning you have to call class patch obj instead of just class patch if you want the same functionality as true method it looks like python is not really treating it as method but more just as variable which happens to be function and as such is callable is there any way to attach an actual method to class oh and ryan that is not exactly what was looking for it is not builtin functionality but it is quite cool nonetheless
in python monkey patching generally works by overwriting class or functions signature with your own below is an example from the zope wiki from someotherproduct somemodule import someclassdef speak self return ook ook eee eee eee someclass speak speak that code will overwrite create method called speak on the class in jeff atwood recent post on monkey patching he shows an example in which is the current language use for work
QA
how do you express binary literals in python how do you express an integer as binary number with python literals was easily able to find the answer for hex af and octal how do you use literals to express binary in python summary of answers python and earlier can express binary using int but not with literal python and earlier there is no way to express binary literals python beta you can do like so or python beta will also allow or second character is the letter to represent an octal python beta same as but will no longer allow the older syntax for octals
print int print int another way
QA
python and mysql can get python to work with postgresql but cannot get it to work with mysql the main problem is that on the shared hosting account have do not have the ability to install things such as django or pysql generally fail when installing them on my computer so maybe it is good cannot install on the host found bpgsql really good because it does not require an install it is single file that can look at read and then call the functions of does anybody know of something like this for mysql
mysqldb is what have used before if you host is using python version or higher support for sqlite databases is built in sqlite allows you to have relational database that is simply file in your filesystem but buyer beware sqlite is not suited for production so it may depend what you are trying to do with it another option may be to call your host and complain or change hosts honestly these days any self respecting web host that supports python and mysql ought to have mysqldb pre installed
QA
any experiences with protocol buffers was just looking through some information about google protocol buffers data interchange format has anyone played around with the code or even created project around it am currently using xml in python project for structured content created by hand in text editor and was wondering what the general opinion was on protocol buffers as user facing input format the speed and brevity benefits definitely seem to be there but there are so many factors when it comes to actually generating and processing the data
if you are looking for user facing interaction stick with xml it has more support understanding and general acceptance currently if it is internal would say that protocol buffers are great idea maybe in few years as more tools come out to support protocol buffers then start looking towards that for public facing api until then json
QA
how do make menu that does not require the user to press enter to make selection have got menu in python that part was easy am using raw input to get the selection from the user the problem is that raw input and input require the user to press enter after they make selection is there any way to make the program act immediately upon keystroke here is what have got so far import sys print menu say foo say bar answer raw input make selection if in answer print foo elif in answer print bar it would be great to have something like print menu while lastkey lastkey check for recent keystrokes if in lastkey do stuff
on linux set raw mode select and read the keystroke restore normal settings import sys import select import termios import tty def getkey old settings termios tcgetattr sys stdin tty setraw sys stdin fileno select select sys stdin answer sys stdin read termios tcsetattr sys stdin termios tcsadrain old settings return answer print menu say foo say bar answer getkey if in answer print foo elif in answer print bar
QA
how do make menu that does not require the user to press enter to make selection have got menu in python that part was easy am using raw input to get the selection from the user the problem is that raw input and input require the user to press enter after they make selection is there any way to make the program act immediately upon keystroke here is what have got so far import sys print menu say foo say bar answer raw input make selection if in answer print foo elif in answer print bar it would be great to have something like print menu while lastkey lastkey check for recent keystrokes if in lastkey do stuff
on windows import msvcrt answer msvcrt getch
QA
how to check what os am running on in python what do need to look at to see if am on windows unix etc
import os print os name posix import platform platform system linux platform release generic see platform access to underlying platform identifying data
QA
how do make menu that does not require the user to press enter to make selection have got menu in python that part was easy am using raw input to get the selection from the user the problem is that raw input and input require the user to press enter after they make selection is there any way to make the program act immediately upon keystroke here is what have got so far import sys print menu say foo say bar answer raw input make selection if in answer print foo elif in answer print bar it would be great to have something like print menu while lastkey lastkey check for recent keystrokes if in lastkey do stuff
wow that took forever ok here is what have ended up with python python exeimport msvcrtprint menu say foo say bar while char msvcrt getch if char chr escape break if char print foo break if char print bar break it fails hard using idle the python thing that comes with python but once tried it in dos er cmd exe as real program then it ran fine no one try it in idle unless you have task manager handy have already forgotten how lived with menus that arn super instant responsive
QA
how to check what os am running on in python what do need to look at to see if am on windows unix etc
dang lbrandy beat me to the punch but that does not mean cannot provide you with the system results for vista import os os name nt import platform platform system windows platform release vista
QA
how to check what os am running on in python what do need to look at to see if am on windows unix etc
for the record here is the results on mac import os os name posix import platform platform system darwin platform release
QA
how do make menu that does not require the user to press enter to make selection have got menu in python that part was easy am using raw input to get the selection from the user the problem is that raw input and input require the user to press enter after they make selection is there any way to make the program act immediately upon keystroke here is what have got so far import sys print menu say foo say bar answer raw input make selection if in answer print foo elif in answer print bar it would be great to have something like print menu while lastkey lastkey check for recent keystrokes if in lastkey do stuff
the reason msvcrt fails in idle is because idle is not accessing the library that runs msvcrt whereas when you run the program natively in cmd exe it works nicely for the same reason that your program blows up on mac and linux terminals but guess if you are going to be using this specifically for windows more power to ya
QA
python what is the difference between and and when should use each in many places and can be used interchangeably when should use one or the other and why
the list is dynamic and flexible but that flexibility comes at speed cost the tuple is fixed immutable and therefore faster
QA
python what is the difference between and and when should use each in many places and can be used interchangeably when should use one or the other and why
from the python faq lists and tuples while similar in many respects are generally used in fundamentally different ways tuples can be thought of as being similar to pascal records or structs they are small collections of related data which may be of different types which are operated on as group for example cartesian coordinate is appropriately represented as tuple of two or three numbers lists on the other hand are more like arrays in other languages they tend to hold varying number of objects all of which have the same type and which are operated on one by one generally by convention you would not choose list or tuple just based on its am mutability you would choose tuple for small collections of completely different pieces of data in which full blown class would be too heavyweight and list for collections of any reasonable size where you have homogeneous set of data
QA
file size differences after copying file to server ftp have created php script to update webserver that is live inside local directory am migrating the script into python it works fine for the most part but after put command the size of the file appears to change thus the size of the file is different from that of the file on the server once download again the file from the ftp server the only difference is the cr lf mark this annoys me because the same script is comparing the size of the files to update also in case it means anything the script works perfectly in php ftp put from ftplib import ftp ftpserver myserver ftpuser myuser ftppass mypwd locfile test style css ftpfile temp style css try ftp ftp ftpserver ftpuser ftppass except exit cannot connect open locfile try ftp delete ftpfile except pass ftp sendcmd type ftp storlines stor ftpfile ftp storbinary stor ftpfile close ftp dir ftpfile ftp quit any suggestions
do you need to open the locfile in binary using rb open locfile rb
QA
file size differences after copying file to server ftp have created php script to update webserver that is live inside local directory am migrating the script into python it works fine for the most part but after put command the size of the file appears to change thus the size of the file is different from that of the file on the server once download again the file from the ftp server the only difference is the cr lf mark this annoys me because the same script is comparing the size of the files to update also in case it means anything the script works perfectly in php ftp put from ftplib import ftp ftpserver myserver ftpuser myuser ftppass mypwd locfile test style css ftpfile temp style css try ftp ftp ftpserver ftpuser ftppass except exit cannot connect open locfile try ftp delete ftpfile except pass ftp sendcmd type ftp storlines stor ftpfile ftp storbinary stor ftpfile close ftp dir ftpfile ftp quit any suggestions
well if you go under the properties of your file in windows or nix environment you will notice two sizes one is the sector size and one is the actual size the sector size is the number of sectors in bytes that are used up on your hard disk that is because two files cannot be in the same sector with most modern file systems so if your file fills up half of the sector the whole sector is marked as filled so you might be comparing the sector file size to the actual file size on the ftp server or vice versa
QA
file size differences after copying file to server ftp have created php script to update webserver that is live inside local directory am migrating the script into python it works fine for the most part but after put command the size of the file appears to change thus the size of the file is different from that of the file on the server once download again the file from the ftp server the only difference is the cr lf mark this annoys me because the same script is comparing the size of the files to update also in case it means anything the script works perfectly in php ftp put from ftplib import ftp ftpserver myserver ftpuser myuser ftppass mypwd locfile test style css ftpfile temp style css try ftp ftp ftpserver ftpuser ftppass except exit cannot connect open locfile try ftp delete ftpfile except pass ftp sendcmd type ftp storlines stor ftpfile ftp storbinary stor ftpfile close ftp dir ftpfile ftp quit any suggestions
small files take up whole node on the filesystem whatever size that is my host tends to report all small files as kb in ftp but in she will gives an accurate size so it might be feature common to ftp clients
QA
how can create directly executable cross platform gui app using python python works on multiple platforms and can be used for desktop and web applications thus conclude that there is some way to compile it into an executable for mac windows and linux the problem being have no idea where to start or how to write gui with it can anybody she would some light on this and point me in the right direction please
first you will need some gui library with python bindings and then if you want some program that will convert your python scripts into standalone executables cross platform gui libraries with python bindings windows linux mac of course there are many but the most popular that have seen in wild are tkinter based on tk gui toolkit de facto standard gui library for python free for commercial projects wxpython based on wxwidgets very popular free for commercial projects pyqt based on qt also very popular and more stable than wxwidgets but costly license for commercial projects complete list is at http wiki python org moin guiprogramming single executable windows py exe probably the most popular out there pyinstaller is also gaining in popularity single executable linux freeze works the same way like py exe but targets linux platform single executable mac py app again works like py exe but targets mac os
QA
how can create directly executable cross platform gui app using python python works on multiple platforms and can be used for desktop and web applications thus conclude that there is some way to compile it into an executable for mac windows and linux the problem being have no idea where to start or how to write gui with it can anybody she would some light on this and point me in the right direction please
you do not need to compile python for mac windows linux it is an interpreted language so you simply need to have the python interpreter installed on the system of your choice it is available for all three platforms as for gui library that works cross platform python tk tcl widget library works very well and believe is sufficiently cross platform tkinter is the python interface to tk tcl from the python project webpage tkinter is not the only guiprogramming toolkit for python it is however the most commonly used one and almost the only one that is portable between unix mac and windows
QA
how can create directly executable cross platform gui app using python python works on multiple platforms and can be used for desktop and web applications thus conclude that there is some way to compile it into an executable for mac windows and linux the problem being have no idea where to start or how to write gui with it can anybody she would some light on this and point me in the right direction please
since python is installed on nearly every non windows os by default now the only thing you really need to make sure of is that all of the non standard libraries you use are installed having said that it is possible to build executables that include the python interpreter and any libraries you use this is likely to create large executable however macos even includes support in the xcode ide for creating full standalone gui apps these can be run by any user running os
QA
adding method to an existing object instance have read that it is possible to add method to an existing object not in the class definition in python think this is called monkey patching or in some cases duck punching understand that it is not always good decision to do so but how might one do this update est that looks like good answer john downey tried it but it appears that it ends up being not true method your example defines the new patch function with an argument of self but if you write actual code that way the now patched class method asks for an argument named self it does not automagically recognize it as the object to which it is supposed to bind which is what would happen if defined within the class definition meaning you have to call class patch obj instead of just class patch if you want the same functionality as true method it looks like python is not really treating it as method but more just as variable which happens to be function and as such is callable is there any way to attach an actual method to class oh and ryan that is not exactly what was looking for it is not builtin functionality but it is quite cool nonetheless
in python there is difference between functions and bound methods def foo print foo class def bar self print bar foo function foo at bar bound method bar of main instance at bc bound methods have been bound how descriptive to an instance and that instance will be passed as the first argument whenever the method is called callables that are attributes of class as opposed to an instance are still unbound though so you can modify the class definition whenever you want def foofighters self print foofighters foofighters foofighters foofighters bound method foofighters of main instance at beb foofighters foofighters previously defined instances are updated as well as long as they have not overridden the attribute themselves foofighters foofighters the problem comes when you want to attach method to single instance def barfighters self print barfighters barfighters barfighters barfighters traceback most recent call last file stdin line in module typeerror barfighters takes exactly argument given the function is not automatically bound when it is attached directly to an instance barfighters function barfighters at ef to bind it we can use the methodtype function in the types module import types barfighters types methodtype barfighters barfighters bound method barfighters of main instance at bc barfighters barfighters this time other instances of the class have not been affected barfighters traceback most recent call last file stdin line in module attributeerror instance has no attribute barfighters more information can be found by reading about descriptors and metaclass programming
QA
how can find the full path to font from its display name on mac am using the photoshop javascript api to find the fonts in given psd given font name returned by the api want to find the actual physical font file that that font name corresponds to on the disc this is all happening in python program running on osx so guess am looking for one of some photoshop javascript python function an osx api that can call from python
unfortunately the only api that is not deprecated is located in the applicationservices framework which does not have bridge support file and thus is not available in the bridge if you are wanting to use ctypes you can use atsfontgetfilereference after looking up the atsfontref cocoa does not have any native support at least as of for getting the location of font
QA
calling function of module from string with the function name in python what is the best way to go about calling function given string with the function name in python program for example let us say that have module foo and have string whose contents are bar what is the best way to go about calling foo bar need to get the return value of the function which is why do not just use eval figured out how to do it by using eval to define temp function that returns the result of that function call but am hoping that there is more elegant way to do this
assuming module foo with method bar import foo methodtocall getattr foo bar result methodtocall as far as that goes lines and can be compressed to result getattr foo bar if that makes more sense for your use case you can use getattr in this fashion on class instance bound methods module level methods class methods the list goes on
QA
programmatically talking to serial port in os or linux have prolite led sign that like to set up to show scrolling search queries from apache logs and other fun statistics the problem is my does not have serial port so have to use usb to serial dongle it shows up as dev cu usbserial and dev tty usbserial when do this everything seems to be hunky dory stty dev cu usbserial speed baud lflags icanon isig iexten echo iflags icrnl ixon ixany imaxbel brkint oflags opost onlcr oxtabs cflags cs parenb everything also works when use the serial port tool to talk to it if run this piece of code while the above mentioned serial port tool everthing also works but as soon as disconnect the tool the connection gets lost usr bin python import serial ser serial serial dev cu usbserial timeout ser write id pa read chars ser read print read chars ser close so the question is what magicks do need to perform to start talking to the serial port without the serial port tool is that permissions problem also what is the difference between dev cu usbserial and dev tty usbserial nope no serial numbers the thing is the problem persists even with sudo running the python script and the only thing that makes it go through if open the connection in the gui tool that mentioned
have you tried watching the traffic between the gui and the serial port to see if there is some kind of special command being sent across also just curious python is sending ascii and not utf or something else right the reason ask is because noticed your quote changes for the strings and in some languages that actually is the difference between ascii and utf
QA
programmatically talking to serial port in os or linux have prolite led sign that like to set up to show scrolling search queries from apache logs and other fun statistics the problem is my does not have serial port so have to use usb to serial dongle it shows up as dev cu usbserial and dev tty usbserial when do this everything seems to be hunky dory stty dev cu usbserial speed baud lflags icanon isig iexten echo iflags icrnl ixon ixany imaxbel brkint oflags opost onlcr oxtabs cflags cs parenb everything also works when use the serial port tool to talk to it if run this piece of code while the above mentioned serial port tool everthing also works but as soon as disconnect the tool the connection gets lost usr bin python import serial ser serial serial dev cu usbserial timeout ser write id pa read chars ser read print read chars ser close so the question is what magicks do need to perform to start talking to the serial port without the serial port tool is that permissions problem also what is the difference between dev cu usbserial and dev tty usbserial nope no serial numbers the thing is the problem persists even with sudo running the python script and the only thing that makes it go through if open the connection in the gui tool that mentioned
dev cu xxxxx is the callout device it is what you use when you establish connection to the serial device and start talking to it dev tty xxxxx is the dialin device used for monitoring port for incoming calls for fax listener
QA
class views in django django view points to function which can be problem if you want to change only bit of functionality yes could have million keyword arguments and even more if statements in the function but was thinking more of an object oriented approach for example have page that displays user this page is very similar to page that displays group but it is still not so similar to just use another data model group also has members etc one way would be to point views to class methods and then extend that class has anyone tried this approach or has any other idea
if you are simply displaying data from models why not use the django generic views they are designed to let you easy show data from model without having to write your own view and stuff about mapping url paramaters to views fetching data handling edge cases rendering output etc
QA
python what is the difference between and and when should use each in many places and can be used interchangeably when should use one or the other and why
tuples are quick flexible way to create composite data types lists are containers for well lists of objects for example you would use list to store list of student details in class each student detail in that list may be tuple containing their roll number name and test score mark john also because tuples are immutable they can be used as keys in dictionaries
QA
adding method to an existing object instance have read that it is possible to add method to an existing object not in the class definition in python think this is called monkey patching or in some cases duck punching understand that it is not always good decision to do so but how might one do this update est that looks like good answer john downey tried it but it appears that it ends up being not true method your example defines the new patch function with an argument of self but if you write actual code that way the now patched class method asks for an argument named self it does not automagically recognize it as the object to which it is supposed to bind which is what would happen if defined within the class definition meaning you have to call class patch obj instead of just class patch if you want the same functionality as true method it looks like python is not really treating it as method but more just as variable which happens to be function and as such is callable is there any way to attach an actual method to class oh and ryan that is not exactly what was looking for it is not builtin functionality but it is quite cool nonetheless
what you are looking for is setattr believe use this to set an attribute on an object def printme print repr class pass setattr printme printme printme becomes the implicit self variable main instance at xabcdefg
QA
calling function of module from string with the function name in python what is the best way to go about calling function given string with the function name in python program for example let us say that have module foo and have string whose contents are bar what is the best way to go about calling foo bar need to get the return value of the function which is why do not just use eval figured out how to do it by using eval to define temp function that returns the result of that function call but am hoping that there is more elegant way to do this
patrick solution is probably the cleanest if you need to dynamically pick up the module as well you can import it like import foo func getattr bar func
QA
how to sell python to client boss person with lots of cash when asked to create system xyz and you ask to do it in python over php or ruby what are the main features you can mention when they require you to explain it
focus on the shorter time needed for development prototype and possibly easier maintenance none of this may apply against ruby
QA
how to sell python to client boss person with lots of cash when asked to create system xyz and you ask to do it in python over php or ruby what are the main features you can mention when they require you to explain it
this is one of those cases that really boil down to personal preference or situational details if you are more comfortable and experienced with python then say so are they asking you to justify it because they are more comfortable with one of the other environments after you are done will the system be passed off to someone else for long term maintenance if they ask you to use technology or language that you are not as familiar with then make sure they know up front that it is going to take you longer
QA
how to sell python to client boss person with lots of cash when asked to create system xyz and you ask to do it in python over php or ruby what are the main features you can mention when they require you to explain it
would consider that using python on new project is completely dependent on what problem you are trying to solve with python if you want someone to agree with you that you should use python then show them how python features apply specifically to that problem in the case of web development with python talk about wsgi and other web libraries and frameworks you could use that would make your life easier one note for python is that most of the frameworks for python web development can be plugged right into any current project with ruby on rails you are practically working in dsl that anyone who uses your project will have to learn if they know python then they can figure out what you are doing with django etc in day am only talking about web development because it appears that is what you are going to be working on seeing ruby python and php in the same list the real message that is important is applying to whatever it is you like about python directly to some problem you are trying to solve
QA
how do you set up python scripts to work in apache tried to follow couple of googled up tutorials on setting up mod python but failed every time do you have good step by step rock solid howto my dev box is os production centos
there are two main ways of running python on apache the simplest would be to use cgi and write normal python scripts while the second is using web framework like django or pylons using cgi is straightforward make sure your apache config file has cgi bin set up if not follow their documentation http httpd apache org docs howto cgi html at that point all you need to do is place your python scripts in the cgi bin directory and the standard output will become the http response refer to python documentation for further info https docs python org library cgi html if you want to use web framework you will need to setup mod python or fastcgi these steps are dependent on which framework you want to use django provides clear instructions on how to setup mod python and django with apache http www djangoproject com documentation modpython
QA
how do you set up python scripts to work in apache tried to follow couple of googled up tutorials on setting up mod python but failed every time do you have good step by step rock solid howto my dev box is os production centos
yes mod python is pretty confusing to set up here is how did it in httpd conf loadmodule python module modules mod python so directory serverbase htdocs myapp addhandler mod python py pythonhandler myapp pythondebug on and in your application directory serverbase htdocs myapp ls ltotal xr xr root sys may myapp py repeat the configuration for each python program you wish to have running under mod python
QA
how do you set up python scripts to work in apache tried to follow couple of googled up tutorials on setting up mod python but failed every time do you have good step by step rock solid howto my dev box is os production centos
are you running python on unix or windows an alternative to mod python and fastcgi is mod wsgi you can find out more at modwsgi have built and installed this on solaris without problems had previously tried mod python but ran into problems with shared libraries as part of the build there are good install docs available
QA
does anyone have experience creating shared library in matlab researcher has created small simulation in matlab and we want to make it accessible to others my plan is to take the simulation clean up few things and turn it into set of functions then plan to compile it into library and use swig to create python wrapper at that point should be able to call the simulation from small django app at least hope so do have the right plan has anyone else done something similar can you let me know if there are some serious pitfalls am not aware of at the moment
will not help much but remember that was able to wrap matlab simulation into dll and then call it from delphi app it work really well anyway good luck
QA
cross platform language agnostic gui markup language learned swing back in the day but now have moved to python and want to make some apps with guis have not had the time to learn new gui api so have been using jython but would prefer to use cpython it would be great if can have one simple markup that allows me to switch gui libraries it would be even better if can use the same markup language across languages so can quickly make guis for any language am using does anyone know of such markup library have seen markups like glade and wxwidget markup forget the name they are partly what am looking for making gui without coding it in language but they are intertwined with specific library and neither are really nice looking or friendly to human editting
erm html trying to be funny here while we wait for real answers
QA
cross platform language agnostic gui markup language learned swing back in the day but now have moved to python and want to make some apps with guis have not had the time to learn new gui api so have been using jython but would prefer to use cpython it would be great if can have one simple markup that allows me to switch gui libraries it would be even better if can use the same markup language across languages so can quickly make guis for any language am using does anyone know of such markup library have seen markups like glade and wxwidget markup forget the name they are partly what am looking for making gui without coding it in language but they are intertwined with specific library and neither are really nice looking or friendly to human editting
the wxwidgets formerly known as wxwindows library might be what you are looking for there is particularly good port for python wxpython as well as versions for different languages perl and ruby come to mind and for various guis win mac os gtk motif wince the library been around for while and is pretty solid
QA
cross platform language agnostic gui markup language learned swing back in the day but now have moved to python and want to make some apps with guis have not had the time to learn new gui api so have been using jython but would prefer to use cpython it would be great if can have one simple markup that allows me to switch gui libraries it would be even better if can use the same markup language across languages so can quickly make guis for any language am using does anyone know of such markup library have seen markups like glade and wxwidget markup forget the name they are partly what am looking for making gui without coding it in language but they are intertwined with specific library and neither are really nice looking or friendly to human editting
not sure if this is what you are looking for but there is glade or windows download which is designer for gtk it generates an xml file which can then be used to build the gui in number of different languages
QA
cross platform language agnostic gui markup language learned swing back in the day but now have moved to python and want to make some apps with guis have not had the time to learn new gui api so have been using jython but would prefer to use cpython it would be great if can have one simple markup that allows me to switch gui libraries it would be even better if can use the same markup language across languages so can quickly make guis for any language am using does anyone know of such markup library have seen markups like glade and wxwidget markup forget the name they are partly what am looking for making gui without coding it in language but they are intertwined with specific library and neither are really nice looking or friendly to human editting
qt pronounced cute by its creators is cross platform application development framework widely used for the development of gui programs qt uses with several non standard extensions implemented by an additional pre processor that generates standard code before compilation qt can also be used in several other programming languages bindings exist for ada qtada qyoto kimono java qt jambi pascal perl php php qt ruby rubyqt and python pyqt it runs on all major platforms and has extensive internationalization support non gui features include sql database access xml parsing thread management network support and unified cross platform api for file handling
QA
python unicode and the windows console when try to print unicode string in windows console get unicodeencodeerror charmap codec cannot encode character error assume this is because the windows console does not accept unicode only characters what is the best way around this is there any way can make python automatically print instead of failing in this situation edit am using python note lassev karlsen answer with the checkmark is sort of outdated from please use the solutions answers suggestions below with care jfsebastian answer is more relevant as of today jan
note this answer is sort of outdated from please use the solution below with care here is page that details the problem and solution search the page for the text wrapping sys stdout into an instance printfails python wiki here is code excerpt from that page python import sys codecs locale print sys stdout encoding sys stdout codecs getwriter locale getpreferredencoding sys stdout line you print type line len line sys stdout write line print line utf type unicode python import sys codecs locale print sys stdout encoding sys stdout codecs getwriter locale getpreferredencoding sys stdout line you print type line len line sys stdout write line print line cat none type unicode there is some more information on that page well worth read
QA
convert bytes to floating point numbers in python have binary file that have to parse and am using python is there way to take bytes and convert it to single precision floating point number
you will want the struct package
QA
python what is the difference between and and when should use each in many places and can be used interchangeably when should use one or the other and why
as others have mentioned lists and tuples are both containers which can be used to store python objects lists are extensible and their contents can change by assignment on the other hand tuples are immutable also lists cannot be used as keys in dictionary whereas tuples can
QA
python what is the difference between and and when should use each in many places and can be used interchangeably when should use one or the other and why
if you can find solution that works with tuples use them as it forces immutability which kind of drives you down more functional path you almost never regret going down the functional immutable path
QA
get size of file before downloading in python am downloading an entire directory from web server it works ok but cannot figure how to get the file size before download to compare if it was updated on the server or not can this be done as if was downloading the file from ftp server import urllib import re url http www someurl com download the page locally urllib urlopen url html read close open temp htm write html close list only the txt zip files fnames re findall href txt zip html re multiline for fname in fnames print fname urllib urlopen url fname here want to check the filesize to download or not file read close open fname write file close jon thank for your quick answer it works but the filesize on the web server is slightly less than the filesize of the downloaded file examples local size server size it has anything to do with the cr lf conversion
the size of the file is sent as the content length header here is how to get it with urllib site urllib urlopen http python org meta site info print meta getheaders content length
QA
get size of file before downloading in python am downloading an entire directory from web server it works ok but cannot figure how to get the file size before download to compare if it was updated on the server or not can this be done as if was downloading the file from ftp server import urllib import re url http www someurl com download the page locally urllib urlopen url html read close open temp htm write html close list only the txt zip files fnames re findall href txt zip html re multiline for fname in fnames print fname urllib urlopen url fname here want to check the filesize to download or not file read close open fname write file close jon thank for your quick answer it works but the filesize on the web server is slightly less than the filesize of the downloaded file examples local size server size it has anything to do with the cr lf conversion
using the returned urllib object method info you can get various information on the retrived document example of grabbing the current google logo import urllib urllib urlopen http www google co uk logos olympics opening gif print info content type image giflast modified thu aug gmt expires sun jan gmt cache control public date fri aug gmt server gws content length connection close it is dict so to get the size of the file you do urllibobject info content length print info content length and to get the size of the local file for comparison you can use the os stat command os stat the local file zip st size
QA
get size of file before downloading in python am downloading an entire directory from web server it works ok but cannot figure how to get the file size before download to compare if it was updated on the server or not can this be done as if was downloading the file from ftp server import urllib import re url http www someurl com download the page locally urllib urlopen url html read close open temp htm write html close list only the txt zip files fnames re findall href txt zip html re multiline for fname in fnames print fname urllib urlopen url fname here want to check the filesize to download or not file read close open fname write file close jon thank for your quick answer it works but the filesize on the web server is slightly less than the filesize of the downloaded file examples local size server size it has anything to do with the cr lf conversion
also if the server you are connecting to supports it look at etags and the if modified since and if none match headers using these will take advantage of the webserver caching rules and will return not modified status code if the content has not changed
QA
get size of file before downloading in python am downloading an entire directory from web server it works ok but cannot figure how to get the file size before download to compare if it was updated on the server or not can this be done as if was downloading the file from ftp server import urllib import re url http www someurl com download the page locally urllib urlopen url html read close open temp htm write html close list only the txt zip files fnames re findall href txt zip html re multiline for fname in fnames print fname urllib urlopen url fname here want to check the filesize to download or not file read close open fname write file close jon thank for your quick answer it works but the filesize on the web server is slightly less than the filesize of the downloaded file examples local size server size it has anything to do with the cr lf conversion
have reproduced what you are seeing import urllib oslink http python org print opening url linksite urllib urlopen link meta site info print content length meta getheaders content length open out txt print file on disk len read close open out txt write site read site close close open out txt print file on disk after download len read close print os stat st size returns os stat out txt st size outputs this opening url http python orgcontent length file on disk file on disk after download os stat st size returns what am doing wrong here is os stat st size not returning the correct size edit ok figured out what the problem was import urllib oslink http python org print opening url linksite urllib urlopen link meta site info print content length meta getheaders content length open out txt rb print file on disk len read close open out txt wb write site read site close close open out txt rb print file on disk after download len read close print os stat st size returns os stat out txt st size this outputs python test pyopening url http python orgcontent length file on disk file on disk after download os stat st size returns make sure you are opening both files for binary read write open for binary writeopen filename wb open for binary readopen filename rb
QA
best way to abstract season show episode data basically have written an api to www thetvdb com in python the current code can be found here it grabs data from the api as requested and has to store the data somehow and make it available by doing print tvdbinstance episodename get the name of episode of season what is the best way to abstract this data within the tvdb class originally used extended dict that automatically created sub dicts so you could do something without having to do if has key and so on then just stored the data by doing self data show id season number episode number attribute name something this worked okay but there was no easy way of checking if was supposed to exist or not so could not raise the season not found exception currently it is using four classes showcontainer show season and episode each one is very basic dict which can easily add extra functionality in the search function on show for example each has setitem getitem and has key this works mostly fine can check in shows if it has that season in it is self data dict if not raise season not found check in season if it has that episode and so on the problem now is it is presenting itself as dict but does not have all the functionality and because am overriding the getitem and setitem functions it is easy to accidently recursively call getitem so am not sure if extending the dict class will cause problems the other slight problem is adding data into the dict is lot more work than the old ddict method which was self data seas no ep no attribute something see setitem and setdata it is not too bad since it is currently only read only api interface so the users of the api should only ever retrieve data not add more but it is hardly elegant think the series of classes system is probably the best way but does anyone have better idea for storing the data and would extending the showcontainer etc classes with dict because problems
why not use sqlite there is good support in python and you can write sql queries to get the data out here is the python docs for sqlite if you do not want to use sqlite you could do an array of dicts episodes episodes append season episode name something episodes append season episode name something actors billy bob sean penn that way you add metadata to any record and search it very easily season for in episodes if season billy bob for in episodes if actors in and billy bob in actors for episode in billy bob print billy bob was in season episode episode season episode episode
QA
any experiences with protocol buffers was just looking through some information about google protocol buffers data interchange format has anyone played around with the code or even created project around it am currently using xml in python project for structured content created by hand in text editor and was wondering what the general opinion was on protocol buffers as user facing input format the speed and brevity benefits definitely seem to be there but there are so many factors when it comes to actually generating and processing the data
protocol buffers are intended to optimize communications between machines they are really not intended for human interaction also the format is binary so it could not replace xml in that use case would also recommend json as being the most compact text based format
QA
cross platform language agnostic gui markup language learned swing back in the day but now have moved to python and want to make some apps with guis have not had the time to learn new gui api so have been using jython but would prefer to use cpython it would be great if can have one simple markup that allows me to switch gui libraries it would be even better if can use the same markup language across languages so can quickly make guis for any language am using does anyone know of such markup library have seen markups like glade and wxwidget markup forget the name they are partly what am looking for making gui without coding it in language but they are intertwined with specific library and neither are really nice looking or friendly to human editting
xml user interface language do not know much about it so not sure if it meets your desires post back with your experience if you play with it
QA
best way to abstract season show episode data basically have written an api to www thetvdb com in python the current code can be found here it grabs data from the api as requested and has to store the data somehow and make it available by doing print tvdbinstance episodename get the name of episode of season what is the best way to abstract this data within the tvdb class originally used extended dict that automatically created sub dicts so you could do something without having to do if has key and so on then just stored the data by doing self data show id season number episode number attribute name something this worked okay but there was no easy way of checking if was supposed to exist or not so could not raise the season not found exception currently it is using four classes showcontainer show season and episode each one is very basic dict which can easily add extra functionality in the search function on show for example each has setitem getitem and has key this works mostly fine can check in shows if it has that season in it is self data dict if not raise season not found check in season if it has that episode and so on the problem now is it is presenting itself as dict but does not have all the functionality and because am overriding the getitem and setitem functions it is easy to accidently recursively call getitem so am not sure if extending the dict class will cause problems the other slight problem is adding data into the dict is lot more work than the old ddict method which was self data seas no ep no attribute something see setitem and setdata it is not too bad since it is currently only read only api interface so the users of the api should only ever retrieve data not add more but it is hardly elegant think the series of classes system is probably the best way but does anyone have better idea for storing the data and would extending the showcontainer etc classes with dict because problems
have done something similar in the past and used an in memory xml document as quick and dirty hierachical database for storage you can store each show season episode as an element nested appropriately and attributes of these things as xml attributes on the elements then you can use xquery to get info back out note am not python guy so do not know what your xml support is like note you will want to profile this because it will be bigger and slower than the solution you have already got likely enough if you are doing some high volume processing then xml is probably not going to be your friend
QA
get preview jpeg of pdf on windows have cross platform python application which needs to generate jpeg preview of the first page of pdf on the mac am spawning sips is there something similarly simple can do on windows
is the pc likely to have acrobat installed think acrobat installs she will extension so previews of the first page of pdf document appear in windows explorer thumbnail view you can get thumbnails yourself via the iextractimage com api which you will need to wrap vbaccelerator has an example in that you could port to python
QA
get preview jpeg of pdf on windows have cross platform python application which needs to generate jpeg preview of the first page of pdf on the mac am spawning sips is there something similarly simple can do on windows
imagemagick delegates the pdf bitmap conversion to ghostscript anyway so here is command you can use it is based on the actual command listed by the ps alpha delegate in imagemagick just adjusted to use jpeg as output gs dquiet dparanoidsafer dbatch dnopause dnoprompt dmaxbitmap dlastpage daligntopixels dgridfittt sdevice jpeg dtextalphabits dgraphicsalphabits soutputfile output input where output and input are the output and input filenames adjust the to whatever resolution you need obviously strip out the backslashes if you are writing out the whole command as one line this is good for two reasons you do not need to have imagemagick installed anymore not that have anything against imagemagick love it to bits but believe in simple solutions imagemagick does two step conversion first pdf ppm then ppm jpeg this way the conversion is one step other things to consider with the files have tested png compresses better than jpeg if you want to use png change the sdevice jpeg to sdevice png
QA
how do use python itertools groupby have not been able to find an understandable explanation of how to actually use python itertools groupby function what am trying to do is this take list in this case the children of an objectified lxml element divide it into groups based on some criteria then later iterate over each of these groups separately have reviewed the documentation and the examples but have had trouble trying to apply them beyond simple list of numbers so how do use of itertools groupby is there another technique should be using pointers to good prerequisite reading would also be appreciated
as sebastjan said you first have to sort your data this is important the part did not get is that in the example construction groups uniquekeys for in groupby data keyfunc groups append list store group iterator as list uniquekeys append is the current grouping key and is an iterator that you can use to iterate over the group defined by that grouping key in other words the groupby iterator itself returns iterators here is an example of that using clearer variable names from itertools import groupby things animal bear animal duck plant cactus vehicle speed boat vehicle school bus for key group in groupby things lambda for thing in group print is thing key print this will give you the output bear is animal duck is animal cactus is plant speed boat is vehicle school bus is vehicle in this example things is list of tuples where the first item in each tuple is the group the second item belongs to the groupby function takes two arguments the data to group and the function to group it with here lambda tells groupby to use the first item in each tuple as the grouping key in the above for statement groupby returns three key group iterator pairs once for each unique key you can use the returned iterator to iterate over each individual item in that group here is slightly different example with the same data using list comprehension for key group in groupby things lambda listofthings and join thing for thing in group print key listofthings this will give you the output animals bear and duck plants cactus vehicles speed boat and school bus
QA
cross platform language agnostic gui markup language learned swing back in the day but now have moved to python and want to make some apps with guis have not had the time to learn new gui api so have been using jython but would prefer to use cpython it would be great if can have one simple markup that allows me to switch gui libraries it would be even better if can use the same markup language across languages so can quickly make guis for any language am using does anyone know of such markup library have seen markups like glade and wxwidget markup forget the name they are partly what am looking for making gui without coding it in language but they are intertwined with specific library and neither are really nice looking or friendly to human editting
read little on xml user interface language xul and it looks really robust and well supported the main problem for me is it is tied to the gecko rendering engine so it is cross platform the way wxwidgets qt and gtk are cross platform also there python bindings do not seem as good as those other libraries gladexml and xrc seem like better markups
QA
cross platform language agnostic gui markup language learned swing back in the day but now have moved to python and want to make some apps with guis have not had the time to learn new gui api so have been using jython but would prefer to use cpython it would be great if can have one simple markup that allows me to switch gui libraries it would be even better if can use the same markup language across languages so can quickly make guis for any language am using does anyone know of such markup library have seen markups like glade and wxwidget markup forget the name they are partly what am looking for making gui without coding it in language but they are intertwined with specific library and neither are really nice looking or friendly to human editting
cristian and antony cramp while xul is nice choice for ui development cross platform open source licensed used in firefox and other major software it is certainly not language agnostic you are tied to gecko with js for scripting there is experimental support for python scripting but it is only experimental afaik you can define the ui in xul js and use back end components written in though there are python and java bridges available too
QA
cross platform language agnostic gui markup language learned swing back in the day but now have moved to python and want to make some apps with guis have not had the time to learn new gui api so have been using jython but would prefer to use cpython it would be great if can have one simple markup that allows me to switch gui libraries it would be even better if can use the same markup language across languages so can quickly make guis for any language am using does anyone know of such markup library have seen markups like glade and wxwidget markup forget the name they are partly what am looking for making gui without coding it in language but they are intertwined with specific library and neither are really nice looking or friendly to human editting
seriously doubt you are going to find markup language for giu that is not tied to specific library for such thing to exist there would need to be standardized gui markup language with several implementations
QA
best way to abstract season show episode data basically have written an api to www thetvdb com in python the current code can be found here it grabs data from the api as requested and has to store the data somehow and make it available by doing print tvdbinstance episodename get the name of episode of season what is the best way to abstract this data within the tvdb class originally used extended dict that automatically created sub dicts so you could do something without having to do if has key and so on then just stored the data by doing self data show id season number episode number attribute name something this worked okay but there was no easy way of checking if was supposed to exist or not so could not raise the season not found exception currently it is using four classes showcontainer show season and episode each one is very basic dict which can easily add extra functionality in the search function on show for example each has setitem getitem and has key this works mostly fine can check in shows if it has that season in it is self data dict if not raise season not found check in season if it has that episode and so on the problem now is it is presenting itself as dict but does not have all the functionality and because am overriding the getitem and setitem functions it is easy to accidently recursively call getitem so am not sure if extending the dict class will cause problems the other slight problem is adding data into the dict is lot more work than the old ddict method which was self data seas no ep no attribute something see setitem and setdata it is not too bad since it is currently only read only api interface so the users of the api should only ever retrieve data not add more but it is hardly elegant think the series of classes system is probably the best way but does anyone have better idea for storing the data and would extending the showcontainer etc classes with dict because problems
do not get this part here this worked okay but there was no easy way of checking if was supposed to exist or not so could not raise the seasonnotfound exception there is way to do it called in in true in false what seems to be the problem with that
QA
class views in django django view points to function which can be problem if you want to change only bit of functionality yes could have million keyword arguments and even more if statements in the function but was thinking more of an object oriented approach for example have page that displays user this page is very similar to page that displays group but it is still not so similar to just use another data model group also has members etc one way would be to point views to class methods and then extend that class has anyone tried this approach or has any other idea
unless you want to do something little complex using the generic views are the way to go they are far more powerful than their name implies and if you are just displaying model data generic views will do the job
QA
python and mysql can get python to work with postgresql but cannot get it to work with mysql the main problem is that on the shared hosting account have do not have the ability to install things such as django or pysql generally fail when installing them on my computer so maybe it is good cannot install on the host found bpgsql really good because it does not require an install it is single file that can look at read and then call the functions of does anybody know of something like this for mysql
you could try setting up your own python installation using virtual python check out how to setup django using it here that was written long time ago but it shows how got mysqldb setup without having root access or anything like it once you have got the basics going you can install any python library you want
QA
how to use xpath in python what is the library is there full implementation how is the library used where is its website
the lxml package supports xpath it seems to work pretty well although have had some trouble with the self axis there is also amara but have not used it personally
QA
accessing mp meta data with python what is the best way to retrieve mp metadata in python have seen couple frameworks out there but am unsure as to which would be the best to use any ideas
this toolkit may do what you need cannot say if it is the best but really if it does what you need that is all that matters right hth
QA
accessing mp meta data with python what is the best way to retrieve mp metadata in python have seen couple frameworks out there but am unsure as to which would be the best to use any ideas
simple example from the book dive into python works ok for me this is the download link the example is fileinfo py do not know if it is the best but it can do the basic job the entire book is available online here
QA
accessing mp meta data with python what is the best way to retrieve mp metadata in python have seen couple frameworks out there but am unsure as to which would be the best to use any ideas
it can depend on exactly what you want to do in addition to reading the metadata if it is just simply the bitrate name etc that you need and nothing else something lightweight is probably best if you are manipulating the mp past that pymedia may be suitable there are quite few whatever you do get make sure and test it out on plenty of sample media there are few different versions of id tags in particular so make sure it is not too out of date personally have used this small mp info class with luck it is quite old though http www omniscia org vivake python mp info py
QA
best way to abstract season show episode data basically have written an api to www thetvdb com in python the current code can be found here it grabs data from the api as requested and has to store the data somehow and make it available by doing print tvdbinstance episodename get the name of episode of season what is the best way to abstract this data within the tvdb class originally used extended dict that automatically created sub dicts so you could do something without having to do if has key and so on then just stored the data by doing self data show id season number episode number attribute name something this worked okay but there was no easy way of checking if was supposed to exist or not so could not raise the season not found exception currently it is using four classes showcontainer show season and episode each one is very basic dict which can easily add extra functionality in the search function on show for example each has setitem getitem and has key this works mostly fine can check in shows if it has that season in it is self data dict if not raise season not found check in season if it has that episode and so on the problem now is it is presenting itself as dict but does not have all the functionality and because am overriding the getitem and setitem functions it is easy to accidently recursively call getitem so am not sure if extending the dict class will cause problems the other slight problem is adding data into the dict is lot more work than the old ddict method which was self data seas no ep no attribute something see setitem and setdata it is not too bad since it is currently only read only api interface so the users of the api should only ever retrieve data not add more but it is hardly elegant think the series of classes system is probably the best way but does anyone have better idea for storing the data and would extending the showcontainer etc classes with dict because problems
bartosz to clarify this worked okay but there was no easy way of checking if was supposed to exist or not some show would return season episode of some show if there was no season want the pseudo dict to raise tvdbseasonnotfound if some show does not exist then raise tvdbshownotfound the current system of series of classes each with getitem show checks if self seasons has key requested season number the season class checks if self episodes has key requested episode number and so on it works but it there seems to be lot of repeated code each class is basically the same but raises different error
QA
how to use xpath in python what is the library is there full implementation how is the library used where is its website
pyxml works well you did not say what platform you are using however if you are on ubuntu you can get it with sudo apt get install python xml am sure other linux distros have it as well if you are on mac xpath is already installed but not immediately accessible you can set py use xmlplus in your environment or do it the python way before you import xml xpath if sys platform startswith darwin os environ py use xmlplus in the worst case you may have to build it yourself this package is no longer maintained but still builds fine and works with modern pythons basic docs are here
QA
accessing mp meta data with python what is the best way to retrieve mp metadata in python have seen couple frameworks out there but am unsure as to which would be the best to use any ideas
what you are after is the id module it is very simple and will give you exactly what you need just copy the id py file into your site packages directory and you will be able to do something like the following from id import try id info id file mp print id info change the tags id info title green eggs and ham id info artist dr seuss for in id info items print except invalidtagerror message print invalid id tag message
QA
how do treat an integer as an array of bytes in python am trying to decode the result of the python os wait function this returns according to the python docs tuple containing its pid and exit status indication bit number whose low byte is the signal number that killed the process and whose high byte is the exit status if the signal number is zero the high bit of the low byte is set if core file was produced how do decode the exit status indication which is an integer to obtain the high and low byte to be specific how do implement the decode function used in the following code snippet pid status os wait exitstatus signum decode status
this will do what you want signum status xff exitstatus status xff
QA
how do treat an integer as an array of bytes in python am trying to decode the result of the python os wait function this returns according to the python docs tuple containing its pid and exit status indication bit number whose low byte is the signal number that killed the process and whose high byte is the exit status if the signal number is zero the high bit of the low byte is set if core file was produced how do decode the exit status indication which is an integer to obtain the high and low byte to be specific how do implement the decode function used in the following code snippet pid status os wait exitstatus signum decode status
you can unpack the status using bit shifting and masking operators low status ff high status xff am not python programmer so hope got the syntax correct
QA
how do treat an integer as an array of bytes in python am trying to decode the result of the python os wait function this returns according to the python docs tuple containing its pid and exit status indication bit number whose low byte is the signal number that killed the process and whose high byte is the exit status if the signal number is zero the high bit of the low byte is set if core file was produced how do decode the exit status indication which is an integer to obtain the high and low byte to be specific how do implement the decode function used in the following code snippet pid status os wait exitstatus signum decode status
the folks before me ve nailed it but if you really want it on one line you can do this signum exitstatus status xff status xff edit had it backwards
QA
how do treat an integer as an array of bytes in python am trying to decode the result of the python os wait function this returns according to the python docs tuple containing its pid and exit status indication bit number whose low byte is the signal number that killed the process and whose high byte is the exit status if the signal number is zero the high bit of the low byte is set if core file was produced how do decode the exit status indication which is an integer to obtain the high and low byte to be specific how do implement the decode function used in the following code snippet pid status os wait exitstatus signum decode status
to answer your general question you can use bit manipulation techniques pid status os wait exitstatus signum status xff status xff however there are also built in functions for interpreting exit status values pid status os wait exitstatus signum os wexitstatus status os wtermsig status see also os wcoredump os wifcontinued os wifstopped os wifsignaled os wifexited os wstopsig
QA
best way to abstract season show episode data basically have written an api to www thetvdb com in python the current code can be found here it grabs data from the api as requested and has to store the data somehow and make it available by doing print tvdbinstance episodename get the name of episode of season what is the best way to abstract this data within the tvdb class originally used extended dict that automatically created sub dicts so you could do something without having to do if has key and so on then just stored the data by doing self data show id season number episode number attribute name something this worked okay but there was no easy way of checking if was supposed to exist or not so could not raise the season not found exception currently it is using four classes showcontainer show season and episode each one is very basic dict which can easily add extra functionality in the search function on show for example each has setitem getitem and has key this works mostly fine can check in shows if it has that season in it is self data dict if not raise season not found check in season if it has that episode and so on the problem now is it is presenting itself as dict but does not have all the functionality and because am overriding the getitem and setitem functions it is easy to accidently recursively call getitem so am not sure if extending the dict class will cause problems the other slight problem is adding data into the dict is lot more work than the old ddict method which was self data seas no ep no attribute something see setitem and setdata it is not too bad since it is currently only read only api interface so the users of the api should only ever retrieve data not add more but it is hardly elegant think the series of classes system is probably the best way but does anyone have better idea for storing the data and would extending the showcontainer etc classes with dict because problems
ok what you need is classobj from new module that would allow you to construct exception classes dynamically classobj takes string as an argument for the class name import new myexc new classobj excname exception myexc this is the exc message raise this gives you traceback most recent call last file stdin line in module main excname this is the exc message remember that you can always get the class name through self class name so after some string mangling and concatenation you should be able to obtain appropriate exception class name and construct class object using that name and then raise that exception you can also raise strings but this is deprecated raise self class name exception
QA
accessing mp meta data with python what is the best way to retrieve mp metadata in python have seen couple frameworks out there but am unsure as to which would be the best to use any ideas
have used mutagen to edit tags in media files before the nice thing about mutagen is that it can handle other formats such as mp flac etc have written several scripts with lot of success using this api
QA
how to use xpath in python what is the library is there full implementation how is the library used where is its website
the latest version of elementtree supports xpath pretty well not being an xpath expert cannot say for sure if the implementation is full but it has satisfied most of my needs when working in python have also use lxml and pyxml and find etree nice because it is standard module note have since found lxml and for me it is definitely the best xml lib out there for python it does xpath nicely as well though again perhaps not full implementation
QA
how should unit test code generator this is difficult and open ended question know but thought would throw it to the floor and see if anyone had any interesting suggestions have developed code generator that takes our python interface to our code generated via swig and generates code needed to expose this as webservices when developed this code did it using tdd but have found my tests to be brittle as hell because each test essentially wanted to verify that for given bit of input code which happens to be header would get given bit of outputted code wrote small engine that reads test definitions from xml input files and generates test cases from these expectations the problem is dread going in to modify the code at all that and the fact that the unit tests themselves are complex and brittle so am trying to think of alternative approaches to this problem and it strikes me am perhaps tackling it the wrong way maybe need to focus more on the outcome ie does the code generate actually run and do what want it to rather than does the code look the way want it to has anyone got any experiences of something similar to this they would care to share
started writing up summary of my experience with my own code generator then went back and re read your question and found you had already touched upon the same issues yourself focus on the execution results instead of the code layout look problem is this is hard to test the generated code might not be suited to actually run in the environment of the unit test system and how do you encode the expected results have found that you need to break down the code generator into smaller pieces and unit test those unit testing full code generator is more like integration testing than unit testing if you ask me
QA
how should unit test code generator this is difficult and open ended question know but thought would throw it to the floor and see if anyone had any interesting suggestions have developed code generator that takes our python interface to our code generated via swig and generates code needed to expose this as webservices when developed this code did it using tdd but have found my tests to be brittle as hell because each test essentially wanted to verify that for given bit of input code which happens to be header would get given bit of outputted code wrote small engine that reads test definitions from xml input files and generates test cases from these expectations the problem is dread going in to modify the code at all that and the fact that the unit tests themselves are complex and brittle so am trying to think of alternative approaches to this problem and it strikes me am perhaps tackling it the wrong way maybe need to focus more on the outcome ie does the code generate actually run and do what want it to rather than does the code look the way want it to has anyone got any experiences of something similar to this they would care to share
yes results are the only thing that matters the real chore is writing framework that allows your generated code to run independently spend your time there
QA
how should unit test code generator this is difficult and open ended question know but thought would throw it to the floor and see if anyone had any interesting suggestions have developed code generator that takes our python interface to our code generated via swig and generates code needed to expose this as webservices when developed this code did it using tdd but have found my tests to be brittle as hell because each test essentially wanted to verify that for given bit of input code which happens to be header would get given bit of outputted code wrote small engine that reads test definitions from xml input files and generates test cases from these expectations the problem is dread going in to modify the code at all that and the fact that the unit tests themselves are complex and brittle so am trying to think of alternative approaches to this problem and it strikes me am perhaps tackling it the wrong way maybe need to focus more on the outcome ie does the code generate actually run and do what want it to rather than does the code look the way want it to has anyone got any experiences of something similar to this they would care to share
if you are running on nux you might consider dumping the unittest framework in favor of bash script or makefile on windows you might consider building she will app function that runs the generator and then uses the code as another process and unittest that third option would be to generate the code and then build an app from it that includes nothing but unittest again you would need she will script or whatnot to run this for each input as to how to encode the expected behavior it occurs to me that it could be done in much the same way as you would for the code just using the generated interface rather than the one
QA
how should unit test code generator this is difficult and open ended question know but thought would throw it to the floor and see if anyone had any interesting suggestions have developed code generator that takes our python interface to our code generated via swig and generates code needed to expose this as webservices when developed this code did it using tdd but have found my tests to be brittle as hell because each test essentially wanted to verify that for given bit of input code which happens to be header would get given bit of outputted code wrote small engine that reads test definitions from xml input files and generates test cases from these expectations the problem is dread going in to modify the code at all that and the fact that the unit tests themselves are complex and brittle so am trying to think of alternative approaches to this problem and it strikes me am perhaps tackling it the wrong way maybe need to focus more on the outcome ie does the code generate actually run and do what want it to rather than does the code look the way want it to has anyone got any experiences of something similar to this they would care to share
recall that unit testing is only one kind of testing you should be able to unit test the internal pieces of your code generator what you are really looking at here is system level testing regression testing it is not just semantics there are different mindsets approaches expectations etc it is certainly more work but you probably need to bite the bullet and set up an end to end regression test suite fixed files swig interfaces python modules known output you really want to check the known input fixed code against expected output what comes out of the final python program checking the code generator results directly would be like diffing object files
QA
how can create directly executable cross platform gui app using python python works on multiple platforms and can be used for desktop and web applications thus conclude that there is some way to compile it into an executable for mac windows and linux the problem being have no idea where to start or how to write gui with it can anybody she would some light on this and point me in the right direction please
an alternative tool to py exe is bbfreeze which generates executables for windows and linux it is newer than py exe and handles eggs quite well have found it magically works better without configuration for wide variety of applications
QA
how can create directly executable cross platform gui app using python python works on multiple platforms and can be used for desktop and web applications thus conclude that there is some way to compile it into an executable for mac windows and linux the problem being have no idea where to start or how to write gui with it can anybody she would some light on this and point me in the right direction please
am not sure that this is the best way to do it but when am deploying ruby gui apps not python but has the same problem as far as exe are concerned on windows just write short launcher in that calls on my main script it compiles to an executable and then have an application executable
QA
python what is the difference between and and when should use each in many places and can be used interchangeably when should use one or the other and why
whenever need to pass in collection of items to function if want the function to not change the values passed in use tuples else if want to have the function to alter the values use list always if you are using external libraries and need to pass in list of values to function and are unsure about the integrity of the data use tuple
QA
python what is the difference between and and when should use each in many places and can be used interchangeably when should use one or the other and why
the notion of tuples are highly expressive pragmatically they are great for packing and unpacking values coord in combination with dictionaries hash tables they allow forms of mapping that would otherwise require many levels of association for example consider marking that has been found php if isset found found array found true else if isset found found true python found true parens added for clarity lists should be used with the expectation of operations on its contents hence the various mentions of immutability one will want to pop push splice slice search insert before insert after etc with list tuples should be low level representation of an object where simple comparisons are made or operations such as extracting the th element or elements in predictable fashion such as the coordinates example given earlier lastly lists are not hashable so the type of mapping done with dictionaries hash tables in perl associative arrays in php must be done with tuples here is simple example of tuples and dictionaries together at last couple is tuple of two people doeslike is dictionary mapping couples to true or false couple john jane doeslike dict doeslike couple true doeslike jane john false unrequited love
QA
can you check that an exception is thrown with doctest in python is it possible to write doctest unit test that will check that an exception is raised for example if have function foo that is supposed to raise an exception if how would write the doctest for that
yes you can do it the doctest module documentation and wikipedia has an example of it traceback most recent call last nameerror name is not defined
QA
using an xml catalog with python lxml is there way when parse an xml document using lxml to validate that document against its dtd using an external catalog file need to be able to work the fixed attributes defined in document dtd
can you give an example according to the lxml validation docs lxml can handle dtd validation specified in the xml doc or externally in code and system catalogs which covers most cases can think of stringio element empty dtd etree dtd dtd etree dtd external id oasis dtd docbook xml en
QA
how do you express binary literals in python how do you express an integer as binary number with python literals was easily able to find the answer for hex af and octal how do you use literals to express binary in python summary of answers python and earlier can express binary using int but not with literal python and earlier there is no way to express binary literals python beta you can do like so or python beta will also allow or second character is the letter to represent an octal python beta same as but will no longer allow the older syntax for octals
for reference future python possibilities starting with python you can express binary literals using the prefix or you can also use the new bin function to get the binary representation of number bin development version of the documentation what is new in python
QA
replacement for for if array iteration love list comprehensions in python because they concisely represent transformation of list however in other languages frequently find myself writing something along the lines of foreach int in intarray if generic condition on do other processing this example is in where am under the impression linq can help with this but is there some common programming construct which can replace this slightly less than elegant solution perhaps data structure am not considering
depends on the language and what you need to do map as it is called in many languages could be what you are looking for do not know but according to this page net calls map convertall the meaning of map is pretty simple take list and apply function to each element of it returning new list you may also be looking for filter which would give you list of items that satisfy predicate in another list

No dataset card yet

New: Create and edit this dataset card directly on the website!

Contribute a Dataset Card
Downloads last month
0
Add dataset card