prefix
stringclasses
1 value
input_text
stringlengths
19
27.3k
target_text
stringlengths
2
24.8k
QA
building full text search engine where to start want to write web application using google app engine so the reference language would be python my application needs simple search engine so the users would be able to find data specifying keywords for example if have one table with those rows office space space odyssey brazil and the user queries for space rows and would be returned if the user queries for office space the result should be rows and too row first what are the technical guidelines algorithms to do this in simple way can you give me good pointers to the theory behind this thanks edit am not looking for anything complex here say indexing tons of data
here is an original idea do not build an index seriously was faced with similar progblem some time ago needed fast method to search megs and megs of text that came from documentation needed to match not just words but word proximity in large documents is this word near that word just ended up writing it in and the speed of it surprised me it was fast enough that it did not need any optimizing or indexing with the speed of today computers if you write code that runs straight on the metal compiled code you often do not need an order log type algorithm to get the performance you need
QA
python list vs array when to use if you are creating array you can implement it as list or else use the array module in the standard library have always used lists for arrays what is the reason or circumstance where would want to use the array module instead is it for performance and memory optimization or am missing something obvious
basically python lists are very flexible and can hold completely heterogeneous arbitrary data and they can be appended to very efficiently in amortized constant time if you need to shrink and grow your array time efficiently and without hassle they are the way to go but they use lot more space than arrays the array array type on the other hand is just thin wrapper on arrays it can hold only homogeneous data all of the same type and so it uses only sizeof one object length bytes of memory mostly you should use it when you need to expose array to an extension or system call for example ioctl or fctnl it is also good way to represent mutable string array bytes until that actually becomes available in python however if you want to do math on homogeneous array of numeric data then you are much better off using numpy which can automatically vectorize operations on complex multi dimensional arrays to make long story short array array is useful when you need homogeneous array of data for reasons other than doing math
QA
django userprofile without password would like to create subset of users that do not have login basically as way to add photographer field to photos without having full blown account associated with that person since in many cases they will never actually log in to the site caveat is that would also like to be able to enable an account for them later so think the question becomes what is the best way to set up people table that ties to the user table without actually extending the user table with userprofile
supply your own authentication routine then you can check or not check anything you like we do this so if they fail on normal username we can also let them in on email password although that is not what am showing below in settings py authentication backends django contrib auth backends modelbackend userprofile my authenticate myloginbackend if they fail the normal test in userprofile my authenticate py from django contrib auth backends import modelbackend from django contrib auth models import user class myloginbackend modelbackend return user record if username some test is valid return none if no match def authenticate self username none password none request none try user user objects get username username plus any other test of user userprofile etc return user indicates success except user doesnotexist return none authenticate class myloginbackend
QA
finding the index of an item given list containing it in python for list foo bar baz and an item in the list bar what is the cleanest way to get its index in python
foo bar baz index bar reference data structures more on lists
QA
building full text search engine where to start want to write web application using google app engine so the reference language would be python my application needs simple search engine so the users would be able to find data specifying keywords for example if have one table with those rows office space space odyssey brazil and the user queries for space rows and would be returned if the user queries for office space the result should be rows and too row first what are the technical guidelines algorithms to do this in simple way can you give me good pointers to the theory behind this thanks edit am not looking for anything complex here say indexing tons of data
read tim bray series of posts on the subject background usage of search engines basics precision and recall search engne intelligence tricky search terms stopwords metadata internationalization ranking results xml robots requirements list
QA
offline access to moinmoin wiki using google gears how to add offline access functionality to moinmoin wiki as minimum would love to have browsing access to all pages on server based wiki while being offline search and other things which do not modify the content are secondary an added bonus would be if this solution allowed to update wiki content while offline and push it back to the wiki when online google gears looks like good candidate for trying to solve this but other solutions are also welcome an interesting property of moinmoin is that it keeps content in regular files instead of the database this can make it easier to port wiki content from one location to another but do not know if that can play any role in answering this question note if you see good reply please rate it up would love to do that but the site does not let me do ratings yet
if you have the freedom to change the wiki software might suggest looking at ikiwiki you can set it up so the pages are backed by real vcs such as git in which case you can clone the whole wiki and read and even update it offline
QA
building full text search engine where to start want to write web application using google app engine so the reference language would be python my application needs simple search engine so the users would be able to find data specifying keywords for example if have one table with those rows office space space odyssey brazil and the user queries for space rows and would be returned if the user queries for office space the result should be rows and too row first what are the technical guidelines algorithms to do this in simple way can you give me good pointers to the theory behind this thanks edit am not looking for anything complex here say indexing tons of data
would not build it yourself if possible app engine includes the basics of full text searching engine and there is great blog post here that describes how to use it there is also feature request in the bug tracker that seems to be getting some attention lately so you may want to hold out if you can until that is implemented
QA
building full text search engine where to start want to write web application using google app engine so the reference language would be python my application needs simple search engine so the users would be able to find data specifying keywords for example if have one table with those rows office space space odyssey brazil and the user queries for space rows and would be returned if the user queries for office space the result should be rows and too row first what are the technical guidelines algorithms to do this in simple way can you give me good pointers to the theory behind this thanks edit am not looking for anything complex here say indexing tons of data
just found this article this weekend http www perl com pub engine html looks not too complicated to do simple one though it would need heavy optimizing to be an enterprise type solution for sure plan on trying proof of concept with some data from project gutenberg if you are just looking for something you can explore and learn from think this is good start
QA
are there any other good alternatives to zc buildout and or virtualenv for installing non python dependencies am member of team that is about to launch beta of python django specifically based web site and accompanying suite of backend tools the team itself has doubled in size from to over the past few weeks and we expect continued growth for the next couple of months at least one issue that has started to plague us is getting everyone up to speed in terms of getting their development environment configured and having all the right eggs installed etc am looking for ways to simplify this process and make it less error prone both zc buildout and virtualenv look like they would be good tools for addressing this problem but both seem to concentrate primarily on the python specific issues we have couple of small subprojects in other languages java and ruby specifically as well as numerous python extensions that have to be compiled natively lxml mysql drivers etc in fact one of the biggest thorns in our side has been getting some of these extensions compiled against appropriate versions of the shared libraries so as to avoid segfaults malloc errors and all sorts of similar issues it does not help that out of people we have different development environments leopard on ppc leopard on intel ubuntu and windows ultimately what would be ideal would be something that works roughly like this from the dos unix prompt git clone repository url python setup env py that then does what zc buildout virtualenv does copy symlink the python interpreter provide clean space to install eggs then installs all required eggs including installing any native shared library dependencies installs the ruby project the java project etc obviously this would be useful for both getting development environments up as well as deploying on staging production servers ideally would like for the tool that accomplishes this to be written in extensible via python since that is and always will be the lingua franca of our team but am open to solutions in other languages so my question then is does anyone have any suggestions for better alternatives or any experiences they can share using one of these solutions to handle larger broader install bases
you might consider creating virtual machine appliances with whatever production os you are running and all of the software dependencies pre built code can be edited either remotely or with shared folder it worked pretty well for me in past life that had fairly complicated development environment
QA
what is the best way to run multiple subprocesses via fork python script need to spawn multiple sub processes via fork all of those child processes should run simultaneously and the parent process should be waiting for all of them to finish having an ability to set some timeout on slow child would be nice the parent process goes on processing the rest of the script after all kids are collected what is the best way to work it out thanks
ephemient each child in your code will stay in the for loop after his job ends he will fork again and again moreover the children that start when children is not empty will try to wait for some of their brothers at the end of the loop eventually someone will crash this is workaround import os time def dothejob job for in xrange print job time sleep ord os urandom random random would be the same for each process jobs imthefather true children for job in jobs child os fork if child children append child else imthefather false dothejob job break in the meanwhile ps aux grep python grep grep wc children the father if imthefather for child in children os waitpid child
QA
sql absolute value across columns have table that looks something like this word big expensive smart fast dog professor ferrari alaska gnat the and values are associated with the word so professor is smart and dog is not smart alaska is big as proportion of the total value associated with its entries and the opposite is true of gnat is there good way to get the absolute value of the number farthest from zero and some token whether absolute value value relatedly how might calculate whether the results for given value are proportionately large with respect to the other values would write something to format the output to the effect of dog not smart probably not expensive professor smart ferrari fast expensive alaska big gnat probably small the formatting is not question just an illustration am stuck on the underlying queries also the rest of the program is python so if there is any python solution with normal dbapi modules or more abstract module any help appreciated
can you use the built in database aggregate functions like max column
QA
sql absolute value across columns have table that looks something like this word big expensive smart fast dog professor ferrari alaska gnat the and values are associated with the word so professor is smart and dog is not smart alaska is big as proportion of the total value associated with its entries and the opposite is true of gnat is there good way to get the absolute value of the number farthest from zero and some token whether absolute value value relatedly how might calculate whether the results for given value are proportionately large with respect to the other values would write something to format the output to the effect of dog not smart probably not expensive professor smart ferrari fast expensive alaska big gnat probably small the formatting is not question just an illustration am stuck on the underlying queries also the rest of the program is python so if there is any python solution with normal dbapi modules or more abstract module any help appreciated
words listed by absolute value of big select word big from mytable order by abs big totals for each category select sum abs big as sumbig sum abs expensive as sumexpensive sum abs smart as sumsmart sum abs fast as sumfast from mytable
QA
sql absolute value across columns have table that looks something like this word big expensive smart fast dog professor ferrari alaska gnat the and values are associated with the word so professor is smart and dog is not smart alaska is big as proportion of the total value associated with its entries and the opposite is true of gnat is there good way to get the absolute value of the number farthest from zero and some token whether absolute value value relatedly how might calculate whether the results for given value are proportionately large with respect to the other values would write something to format the output to the effect of dog not smart probably not expensive professor smart ferrari fast expensive alaska big gnat probably small the formatting is not question just an illustration am stuck on the underlying queries also the rest of the program is python so if there is any python solution with normal dbapi modules or more abstract module any help appreciated
abs value fartherest from zero select max abs mycol from mytbl will be zero if the value is negative select abs mycol from zzz where abs mycol select max abs mycol from mytbl
QA
alert boxes in python is it possible to produce an alert similar to javascript alert message in python with an application running as daemon this will be run in windows most likely xp but and vista are also very real possibilities update this is intended to run in the background and alert the user when certain conditions are met figure that the easiest way to alert the user would be to produce pop up as it needs to be handled immediately and other options such as just logging or sending an email are not efficient enough
what about this import win api win api messagebox hello title additionally win api messagebox hello title will make the box appear on top of other windows for urgent messages see messagebox function for other options
QA
testing socket connection in python this question will expand on http stackoverflow com questions best way to open socket in python when opening socket how can test to see if it has been established and that it did not timeout or generally fail edit tried this try connect address except alert failed address down but the alert function is called even when that connection should have worked
it seems that you catch not the exception you want to catch out there if the is socket socket object then the right way to call connect would be import socket socket socket address port port number is number not string try connect address port originally it was except exception but this syntax is not supported anymore except exception as print something is wrong with exception is address port finally close always try to see what kind of exception is what you are catching in try except loop you can check what types of exceptions in socket module represent what kind of errors timeout unable to resolve address etc and make separate except statement for each one of them this way you will be able to react differently for different kind of problems
QA
parse dicom files in native python what is the simplest and most pythonic way to parse dicom file native python implementation without the use of non python libraries would be much preferred dicom is the standard file format in digital medical imaging look here for more information there are some libraries that support reading subset of dicom files two or three of them even have python bindings native python parser would serve two purposes for me no need to build any external libraries learn about the dicom file format
and as of today there is another pure python package reading dicom files available pydicom
QA
keeping filters in django admin what would like to achive is go to admin site apply some filters to the list of objects click and object edit edit edit hit save site takes me to the list of objects unfiltered would like to have the filter from step remembered and applied is there an easy way to do it
click times back
QA
sql absolute value across columns have table that looks something like this word big expensive smart fast dog professor ferrari alaska gnat the and values are associated with the word so professor is smart and dog is not smart alaska is big as proportion of the total value associated with its entries and the opposite is true of gnat is there good way to get the absolute value of the number farthest from zero and some token whether absolute value value relatedly how might calculate whether the results for given value are proportionately large with respect to the other values would write something to format the output to the effect of dog not smart probably not expensive professor smart ferrari fast expensive alaska big gnat probably small the formatting is not question just an illustration am stuck on the underlying queries also the rest of the program is python so if there is any python solution with normal dbapi modules or more abstract module any help appreciated
asking the question helped clarify the issue here is function that gets more at what am trying to do is there way to represent some of the stuff in above or more efficient way to do in sql or python what am trying to accomplish in show distinct usr bin env python import sqlite conn sqlite connect so question sqlite cur conn cursor cur execute create table soquestion word big expensive smart fast cur execute insert into soquestion values dog cur execute insert into soquestion values professor cur execute insert into soquestion values ferrari cur execute insert into soquestion values alaska cur execute insert into soquestion values gnat cur execute select from soquestion all cur fetchall definition list word big expensive smart fast def show distinct db tuple def list definition list minimum min db tuple maximum max db tuple if abs minimum maximum print db tuple is not def list list db tuple index minimum elif maximum abs minimum print db tuple is def list list db tuple index maximum else print no distinct value for item in all show distinct item running this gives dog is not smart professor is smart ferrari is expensive alaska is big gnat is not big
QA
testing socket connection in python this question will expand on http stackoverflow com questions best way to open socket in python when opening socket how can test to see if it has been established and that it did not timeout or generally fail edit tried this try connect address except alert failed address down but the alert function is called even when that connection should have worked
you should really post the complete source code of your example the actual result of it not summary here is my code which works import socket sys def alert message print sys stderr message sys exit family socktype proto garbage address socket getaddrinfo http use only the first tuple socket socket family socktype proto try connect address except exception alert something is wrong with exception type is address when the server listens get nothing this is normal when it does not get the expected message something is wrong with exception type is connection refused
QA
django userprofile without password would like to create subset of users that do not have login basically as way to add photographer field to photos without having full blown account associated with that person since in many cases they will never actually log in to the site caveat is that would also like to be able to enable an account for them later so think the question becomes what is the best way to set up people table that ties to the user table without actually extending the user table with userprofile
the django contrib auth models user exists solely for the purpose of using default authentication backend database based if you write your own backend you can make some accounts passwordless while keeping normal accounts with passwords django documentation has chapter on this
QA
sql absolute value across columns have table that looks something like this word big expensive smart fast dog professor ferrari alaska gnat the and values are associated with the word so professor is smart and dog is not smart alaska is big as proportion of the total value associated with its entries and the opposite is true of gnat is there good way to get the absolute value of the number farthest from zero and some token whether absolute value value relatedly how might calculate whether the results for given value are proportionately large with respect to the other values would write something to format the output to the effect of dog not smart probably not expensive professor smart ferrari fast expensive alaska big gnat probably small the formatting is not question just an illustration am stuck on the underlying queries also the rest of the program is python so if there is any python solution with normal dbapi modules or more abstract module any help appreciated
the problem seems to be that you mainly want to work within one row and these type of questions are hard to answer in sql would try to turn the structure you mentioned into more atomic fact table like word property value either by redesigning the underlying table if possible and if that makes sense regarding the rest of the application or by defining view that does this for you like select word big as property big as value from soquestion union alll select word expensive expensive from soquestion union all this allows you to ask for the max value for each word select word max value select property from soquestion where word word and value max value from soquestion group by word still little awkward but most logic will be in sql not in your programming language of choice
QA
building full text search engine where to start want to write web application using google app engine so the reference language would be python my application needs simple search engine so the users would be able to find data specifying keywords for example if have one table with those rows office space space odyssey brazil and the user queries for space rows and would be returned if the user queries for office space the result should be rows and too row first what are the technical guidelines algorithms to do this in simple way can you give me good pointers to the theory behind this thanks edit am not looking for anything complex here say indexing tons of data
lucene or autonomy these are not out of the box solutions for you you will have to write wrappers on top of their interfaces they certainly do take care of the stemming grammar relational operators etc
QA
accessing python egg own metadata have produced python egg using setuptools and would like to access it is metadata at runtime currently got working this import pkg resources dist pkg resources get distribution my project print dist version but this would probably work incorrectly if had multiple versions of the same egg installed and if have both installed egg and development version then running this code from development version would pick up version of the installed egg so how do get metadata for my egg not some random matching egg installed on my system
am somewhat new to python as well but from what understand although you can install multiple versions of the same egg having the same name only one of them will be available to any particular piece of code at runtime based on your discovery method so if your egg is the one calling this code it must have already been selected as the version of my project for this code and your access will be to your own version
QA
accessing python egg own metadata have produced python egg using setuptools and would like to access it is metadata at runtime currently got working this import pkg resources dist pkg resources get distribution my project print dist version but this would probably work incorrectly if had multiple versions of the same egg installed and if have both installed egg and development version then running this code from development version would pick up version of the installed egg so how do get metadata for my egg not some random matching egg installed on my system
exactly so you should only be able to get the information for the currently available egg singular of library if you have multiple eggs of the same library in your site packages folder check the easy install pth in the same folder to see which egg is really used on site note this is exactly the point of systems like zc buildout which let us you define the exact version of library that will be made available to you for example while developing an application or serving web application so you can for example use version for one project and for another
QA
writing optimization function am trying to write tennis reservation system and got stucked with this problem let us say you have players with their prefs regarding court number day and hour also every player is ranked so if there is day hour slot and there are several players with preferences for this slot the one with top priority should be chosen am thinking about using some optimization algorithms to solve this problem but am not sure what would be the best cost function and or algorithm to use any advice one more thing would prefer to use python but some language agnostic advice would be welcome also thanks edit some clarifications the one with better priority wins and loser is moved to nearest slot rather flexible time slots question yes maximizing the number of people getting their most highly preffered times
the basic algorithm would sort the players by their rank as the high ranked ones always push away the low ranked ones then you start with the player with the highest rank give him what he asked for if he really is the highest he will always win thus you can as well give him whatever he requested then would start with the second highest one if he requested something already taken by the highest try to find slot nearby and assign this slot to him now comes the third highest one if he requested something already taken by the highest one move him to slot nearby if this slot is already taken by the second highest one move him to slot some further away continue with all other players some tunings to consider if multiple players can have the same rank you may need to implement some fairness all players with equal rank will have random order to each other if you sort them using quicksort you can get some some fairness if you do not do it player for player but rank for rank you start with highest rank and the first player of this rank process his first request however before you process his second request process the first request of the next player having highest rank and then of the third player having highest rank the algorithm is the same as above but assuming you have players and player are highest rank and players are low and players are very low and every player made requests you process them as player request player request player request player request player request player request that way you have some fairness you could also choose randomly within ranking class each time this could also provide some fairness you could implement fairness even across ranks if you have ranks you could say rank rank rank rank just example values you may use different key than always multiplying by multiplying by causing the numbers to decrease slower now you can say you start processing with rank however once of all rank requests have been fulfilled you move on to rank and make sure of their requests are fulfilled and so on this way even rank user can win over rank user somewhat defeating the initial algorithm however you offer some fairness even rank player can sometimes gets his request he will not run dry otherwise rank player scheduling every request on the same time as rank player will make sure rank player has no chance to ever get single request this way there is at least small chance he may get one after you made sure everyone had their minimal percentage processed and the higher the rank the more this is you go back to top starting with rank again and process the rest of their requests then the rest of the rank requests and so on last but not least you may want to define maximum slot offset if slot is taken the application should search for the nearest slot still free however what if this nearest slot is very far away if request slot monday at pm and the application finds the next free one to be wednesday on am that is not really helpful for me is it might have no time on wednesday at all so you may limit slot search to the same day and saying the slot might be at most hours off if no slot is found within that range cancel the request in that case you need to inform the player we are sorry but we could not find any nearby slot for you please request slot on another date time and we will see if we can find suitable slot there for you
QA
offline access to moinmoin wiki using google gears how to add offline access functionality to moinmoin wiki as minimum would love to have browsing access to all pages on server based wiki while being offline search and other things which do not modify the content are secondary an added bonus would be if this solution allowed to update wiki content while offline and push it back to the wiki when online google gears looks like good candidate for trying to solve this but other solutions are also welcome an interesting property of moinmoin is that it keeps content in regular files instead of the database this can make it easier to port wiki content from one location to another but do not know if that can play any role in answering this question note if you see good reply please rate it up would love to do that but the site does not let me do ratings yet
by using gears with the firefox greasemonkey plugin you can inject gears code into any website that you want do not wait for your favorite website to enable offline support do it yourself http code google com apis gears articles gearsmonkey html
QA
python can have list with named indices in php can name my array indicies so that may have something like shows array array id name sesaeme street array id name dora the explorer is this possible in python
yes id name sesame street
QA
python can have list with named indices in php can name my array indicies so that may have something like shows array array id name sesaeme street array id name dora the explorer is this possible in python
this sounds like the php array using named indices is very similar to python dict shows id name sesaeme street id name dora the explorer see http docs python org tutorial datastructures html dictionaries for more on this
QA
python can have list with named indices in php can name my array indicies so that may have something like shows array array id name sesaeme street array id name dora the explorer is this possible in python
php arrays are actually maps which is equivalent to dicts in python thus this is the python equivalent showlist id name sesaeme street id name dora the explorer sorting example from operator import attrgetter showlist sort key attrgetter id but with the example you provided simpler datastructure would be better shows sesaeme street dora the explorer
QA
python can have list with named indices in php can name my array indicies so that may have something like shows array array id name sesaeme street array id name dora the explorer is this possible in python
you should read the python tutorial and esp the section about datastructures which also covers dictionaries
QA
python can have list with named indices in php can name my array indicies so that may have something like shows array array id name sesaeme street array id name dora the explorer is this possible in python
to assist future googling these are usually called associative arrays in php and dictionaries in python
QA
python can have list with named indices in php can name my array indicies so that may have something like shows array array id name sesaeme street array id name dora the explorer is this possible in python
not exactly the same syntax but there are number of dictionary extensions out there which respect the order in which the key value pairs have been added seqdict
QA
finding the index of an item given list containing it in python for list foo bar baz and an item in the list bar what is the cleanest way to get its index in python
one thing that is really helpful in learning python is to use the interactive help function help foo bar baz help on list object class list object index index value start stop integer return first index of value which will often lead you to the method you are looking for
QA
python list vs array when to use if you are creating array you can implement it as list or else use the array module in the standard library have always used lists for arrays what is the reason or circumstance where would want to use the array module instead is it for performance and memory optimization or am missing something obvious
the standard library arrays are useful for binary such as translating list of ints to string to write to say wave file that said as many have already noted if you are going to do any real work then you should consider using numpy
QA
python unit testing and mocking imports am in project where we are starting refactoring some massive code base one problem that immediately sprang up is that each file imports lot of other files how do in an elegant way mock this in my unit test without having to alter the actual code so can start to write unit tests as an example the file with the functions want to test imports ten other files which is part of our software and not python core libs want to be able to run the unit tests as separately as possible and for now am only going to test functions that does not depend on things from the files that are being imported thanks for all the answers did not really know what wanted to do from the start but now think know problem was that some imports was only possible when the whole application was running because of some third party auto magic so had to make some stubs for these modules in directory which pointed out with sys path now can import the file which contains the functions want to write tests for in my unit test file without complaints about missing modules
imports lot of other files imports lot of other files that are part of your customized code base or imports lot of other files that are part of the python distribution or imports lot of other open source project files if your imports do not work you have simple pythonpath problem get all of your various project directories onto pythonpath that you can use for testing we have rather complex path in windows we manage it like this set part blah blah blah set part some other path set that shared stuff set pythonpath part part that we keep each piece of the path separate so that we know where things come from and can manage change when we move things around since the pythonpath is searched in order we can control what gets used by adjusting the order on the path once you have everything it becomes question of trust either you trust something the python code base and just import it or you do not trust something your own code and you test it separately and mock it for stand alone testing would you test the python libraries if so you have got lot of work if not then you should perhaps only mock out the things you are actually going to test
QA
python list vs array when to use if you are creating array you can implement it as list or else use the array module in the standard library have always used lists for arrays what is the reason or circumstance where would want to use the array module instead is it for performance and memory optimization or am missing something obvious
the array module is kind of one of those things that you probably do not have need for if you do not know why you would use it and take note that am not trying to say that in condescending manner most of the time the array module is used to interface with code to give you more direct answer to your question about performance arrays are more efficient than lists for some uses if you need to allocate an array that you know will not change then arrays can be faster and use less memory gvr has an optimization anecdote in which the array module comes out to be the winner long read but worth it on the other hand part of the reason why lists eat up more memory than arrays is because python will allocate few extra elements when all allocated elements get used this means that appending items to lists is faster so if you plan on adding items list is the way to go tl dr would only use an array if you had an exceptional optimization need or you need to interface with code and cannot use pyrex
QA
python unit testing and mocking imports am in project where we are starting refactoring some massive code base one problem that immediately sprang up is that each file imports lot of other files how do in an elegant way mock this in my unit test without having to alter the actual code so can start to write unit tests as an example the file with the functions want to test imports ten other files which is part of our software and not python core libs want to be able to run the unit tests as separately as possible and for now am only going to test functions that does not depend on things from the files that are being imported thanks for all the answers did not really know what wanted to do from the start but now think know problem was that some imports was only possible when the whole application was running because of some third party auto magic so had to make some stubs for these modules in directory which pointed out with sys path now can import the file which contains the functions want to write tests for in my unit test file without complaints about missing modules
if you really want to muck around with the python import mechanism take look at the ihooks module it provides tools for changing the behavior of the import built in but it is not clear from your question why you need to do this
QA
django python grouping objects by common set from many to many relationships this is part algorithm logic question how to do it part implementation question how to do it best am working with django so thought would share with that in python it is worth mentioning that the problem is somewhat related to how do use pythons itertoolsgroupby suppose you are given two django model derived classes from django db import models class car models model mods models manytomanyfield representative and from django db import models class mods models model how does one get list of cars grouped by cars with common set of mods want to get class likeso cars by common mods mods cars mods cars mods cars mods cars have been thinking of something like def cars by common mods cars cars objects all mod list for car in cars mod list append car car mods list car mods all ret for key mods group in groupby list mods lambda set mods ret append mods group return ret however that does not work because perhaps among other reasons the groupby does not seem to group by the mods sets guess the mod list has to be sorted to work with groupby all to say am confident there is something simple and elegant out there that will be both enlightening and illuminating cheers thanks
thank you all for the helpful replies have been plugging away at this problem best solution still eludes me but have some thoughts should mention that the statistics of the data set am working with in of the cases there will be one mod in of the cases two in of the cases there will be zero or three or more for every mod there is at least one unique car though mod may be applied to numerous cars having said that have considered but not implemented something like so class modset models model mods models manytomanyfield mod and change cars to class car models model modset models foreignkey modset it is trivial to group by car modset can use regroup as suggested by javier for example it seems simpler and reasonably elegant solution thoughts would be much appreciated
QA
python can have list with named indices in php can name my array indicies so that may have something like shows array array id name sesaeme street array id name dora the explorer is this possible in python
unkwntech what you want is available in the just released python in the form of named tuples they allow you to do this import collections person collections namedtuple person id name age me person id age name dan you person somebody assert me age me can access fields by either name or position
QA
python unit testing and mocking imports am in project where we are starting refactoring some massive code base one problem that immediately sprang up is that each file imports lot of other files how do in an elegant way mock this in my unit test without having to alter the actual code so can start to write unit tests as an example the file with the functions want to test imports ten other files which is part of our software and not python core libs want to be able to run the unit tests as separately as possible and for now am only going to test functions that does not depend on things from the files that are being imported thanks for all the answers did not really know what wanted to do from the start but now think know problem was that some imports was only possible when the whole application was running because of some third party auto magic so had to make some stubs for these modules in directory which pointed out with sys path now can import the file which contains the functions want to write tests for in my unit test file without complaints about missing modules
no difficult manipulation is necessary if you want quick and dirty fix before your unit tests if the unit tests are in the same file as the code you wish to test simply delete unwanted module from the globals dictionary here is rather lengthy example suppose you have module impp py with contents value now in your test file you can write import impp print globals keys def printval print impp value printval builtins file impp name doc note that impp is among the globals because it was imported calling the function printval that uses impp module still works printval but now if you remove impp key from globals del globals impp print globals keys printval builtins file name doc and try to call printval you will get printval traceback most recent call last file test imp py line in module printval file test imp py line in printval print impp value nameerror global name impp is not defined which is probably exactly what you are trying to achieve to use it in your unit tests you can delete the globals just before running the test suite in main if name main del globals impp unittest main
QA
python dictionary update method have list string tag am trying to initialize dictionary with the key as the tag string and values as the array index for ithtag in enumerate tag tagdict update ithtag the above returns me ithtag is the th index my problem is that while the is being interpreted as variable python is treating the ithtag as string instead of variable am confused it is kind of hard to google these kind of specific questions hope worded the title of this question correctly thanks
it is one liner tagdict dict for in enumerate tag
QA
what symmetric cypher to use for encrypting messages have not clue about encryption at all but need it how say you have system of nodes communicating with each other on network via asynchronous messages the nodes do not maintain session information about other nodes this is design restriction say you want to make sure only your nodes can read the messages being sent believe encryption is the sollution to that since the nodes are not maintaining session and communication must work in stateless connectionless fashion am guessing that asymmetric encryption is ruled out so here is what would like to do messages are sent as udp datagrams each message contains timestamp to make messages differ counter replay attacks each message is encrypted with shared secret symmetric key and sent over the network other end can decrypt with shared secret symmetric key keys can obviously be compromised by compromising any single node at the same time in this scenario access to any single compromised node reveals all interesting information anyway so the key is not the weakest link what cypher should use for this encryption what key length would prefer to use something supported by ezpycrypto assuming as most point out go with aes what modes should be using could not figure out how to do it with ezpycrypto pycrypto seems to be hung on moderator swap and googles keyczar does not explain how to set this up fear if do not just get it then run risk of introducing insecurity so barebones would be better this guy claims to have nice module for aes in python but he also asserts that this is his first python project allthough he is probably loads smarter than maybe he got tripped up edit moved the search for the python implementation to another question to stop clobber
have not clue about encryption at all but need it how danger if you do not know much about cryptography do not try to implement it yourself cryptography is hard to get right there are many many different ways to break the security of cryptographic system beyond actually cracking the key which is usually very hard if you just slap cipher on your streaming data without careful key management and other understanding of the subtleties of cryptographic systems you will likely open yourself up to all kinds of vulnerabilities for example the scheme you describe will be vulnerable to man in the middle attacks without some specific plan for key distribution among the nodes and may be vulnerable to chosen plaintext and or known plaintext attacks depending on how your distributed system communicates with the outside world and the exact choice of cipher and mode of operation so you will have to read up on crypto in general before you can use it securely
QA
python unit testing and mocking imports am in project where we are starting refactoring some massive code base one problem that immediately sprang up is that each file imports lot of other files how do in an elegant way mock this in my unit test without having to alter the actual code so can start to write unit tests as an example the file with the functions want to test imports ten other files which is part of our software and not python core libs want to be able to run the unit tests as separately as possible and for now am only going to test functions that does not depend on things from the files that are being imported thanks for all the answers did not really know what wanted to do from the start but now think know problem was that some imports was only possible when the whole application was running because of some third party auto magic so had to make some stubs for these modules in directory which pointed out with sys path now can import the file which contains the functions want to write tests for in my unit test file without complaints about missing modules
in your comment above you say you want to convince python that certain modules have already been imported this still seems like strange goal but if that is really what you want to do in principle you can sneak around behind the import mechanism back and change sys modules not sure how this would work for package imports but should be fine for absolute imports
QA
python can have list with named indices in php can name my array indicies so that may have something like shows array array id name sesaeme street array id name dora the explorer is this possible in python
python has lists and dicts as separate data structures php mixes both into one you should use dicts in this case
QA
what is the best way to change text contained in an xml file using python let us say have an existing trivial xml file named mydata xml that contains the following xml version encoding utf myelement foo myelement want to change the text value of foo to bar resulting in the following xml version encoding utf myelement bar myelement once am done want to save the changes what is the easiest and simplest way to accomplish all this
for quick non critical xml manipulations really like it let us you write like this import doc open file read doc myelement bar
QA
what is the best way to change text contained in an xml file using python let us say have an existing trivial xml file named mydata xml that contains the following xml version encoding utf myelement foo myelement want to change the text value of foo to bar resulting in the following xml version encoding utf myelement bar myelement once am done want to save the changes what is the easiest and simplest way to accomplish all this
use python minidom basically you will take the following steps read xml data into dom object use dom methods to modify the document save new dom object to new xml document the python spec should hold your hand rather nicely though this process
QA
how do perform an imap search in python using gmail and imaplib in gmail have bunch of labeled messages would like to use an imap client to get those messages but am not sure what the search incantation is imaplib imap ssl imap gmail com list ok hasnochildren gm search am not finding many examples for this sort of thing
labels are accessed exactly like imap folders according to google
QA
python unit testing and mocking imports am in project where we are starting refactoring some massive code base one problem that immediately sprang up is that each file imports lot of other files how do in an elegant way mock this in my unit test without having to alter the actual code so can start to write unit tests as an example the file with the functions want to test imports ten other files which is part of our software and not python core libs want to be able to run the unit tests as separately as possible and for now am only going to test functions that does not depend on things from the files that are being imported thanks for all the answers did not really know what wanted to do from the start but now think know problem was that some imports was only possible when the whole application was running because of some third party auto magic so had to make some stubs for these modules in directory which pointed out with sys path now can import the file which contains the functions want to write tests for in my unit test file without complaints about missing modules
if you want to import module while at the same time ensuring that it does not import anything you can replace the import builtin function for example use this class class importwrapper object def init self real import self real import real import def wrapper self wantedmodules def inner modulename args kwargs if modulename in wantedmodules print importing module modulename self real import args kwargs else print not importing module modulename return inner def mock import self modulename wantedmodules builtins import self wrapper wantedmodules try import modulename globals locals finally builtins import self real import and in your test code instead of writing import mymodule write wrapper importwrapper import wrapper mock import mymodule the second argument to mock import is list of module names you do want to import in inner module this example can be modified further to import other module than desired instead of just not importing it or even mocking the module object with some custom object of your own
QA
average difference between dates in python have series of datetime objects and would like to calculate the average delta between them for example if the input was then the average delta would be exactly or minutes any suggestions on how to calculate this using python
as far as algorithms go that is an easy one just find the max and min datetimes take the difference and divide by the number of datetimes you looked at if you have an array of datetimes you can do mx max mn min average mx mn len to get back the average difference edit fixed the off by one error
QA
average difference between dates in python have series of datetime objects and would like to calculate the average delta between them for example if the input was then the average delta would be exactly or minutes any suggestions on how to calculate this using python
since you seem to be throwing out the minute delta between times and in your example would say you should just sort the list of datetimes add up the deltas between adjacent times then divide by do you have any code you can share with us so we can help you debug it
QA
average difference between dates in python have series of datetime objects and would like to calculate the average delta between them for example if the input was then the average delta would be exactly or minutes any suggestions on how to calculate this using python
you can subtract each successive date from the one prior resulting in timedelta object which represents the difference in days seconds you can then average the timedelta objects to find your answer
QA
python class factory or we have database library in that we can use like this databaseconnection conn databaseconnection fromconnectionstring this library hides many of the differences between different database engines like sql function names parameter names and specifications etc internally the databaseconnection class is an abstract class implementing some of the basic methods but the fromconnectionstring method runs through list of registered specialized types that handles the actual differences and constructs an object of the right class in other words do not get databaseconnection object back get mssqldatabaseconnection or oracledatabaseconnection object back instead which of course inherit from databaseconnection the connection string contains information about what kind of database engine and version this connection is for would like to create similar library in python is the right approach to make something that can be constructed like this conn databaseconnection or using class method conn databaseconnection fromconnectionstring is the first even possible that is constructing an object like this and getting back something else specialized object depending on data in the passed string ok let me ask different question what is the pythonic way of doing this basically want to have the databaseconnection base class in python as well implementing the common methods and specialize in derived classes and have method or function somewhere that based on the connection string constructs and returns the right type of object
this is possible in python but is probably not the best way to do it the class factory pattern is essentially workaround for languages that do not have first class classes since python does have first class classes you can store class in variable and use that class directly to create instances to change what class is created store different class in the variable for example class class def greet self print hi class class def greet self print hello maker class obj maker maker class obj maker obj greet prints hi obj greet prints hello
QA
python class factory or we have database library in that we can use like this databaseconnection conn databaseconnection fromconnectionstring this library hides many of the differences between different database engines like sql function names parameter names and specifications etc internally the databaseconnection class is an abstract class implementing some of the basic methods but the fromconnectionstring method runs through list of registered specialized types that handles the actual differences and constructs an object of the right class in other words do not get databaseconnection object back get mssqldatabaseconnection or oracledatabaseconnection object back instead which of course inherit from databaseconnection the connection string contains information about what kind of database engine and version this connection is for would like to create similar library in python is the right approach to make something that can be constructed like this conn databaseconnection or using class method conn databaseconnection fromconnectionstring is the first even possible that is constructing an object like this and getting back something else specialized object depending on data in the passed string ok let me ask different question what is the pythonic way of doing this basically want to have the databaseconnection base class in python as well implementing the common methods and specialize in derived classes and have method or function somewhere that based on the connection string constructs and returns the right type of object
the first one is absolutely possible and preferable in my opinion in python there is really not whole lot of magic behind constructors for all intents and purposes they are just like any other function have used this design pattern few times to indicate that class should not be instantiated directly for example def databaseconnectionfromstring connection string return databaseconnection connection string def databaseconnectionfromsomethingelse something else connection string convert something else into string something else return databaseconnection connection string class databaseconnection object def init self connection string self connection string connection string of course that is contrived example but that should give you general idea edit this is also one of the areas where inheritance is not quite as frowned upon in python as well you can also do this databaseconnection object def init self connection string self connection string connection string databaseconnectionfromsomethingelse object def init self something else self connection string convert something else into string something else sorry that is so verbose but wanted to make it clear
QA
python class factory or we have database library in that we can use like this databaseconnection conn databaseconnection fromconnectionstring this library hides many of the differences between different database engines like sql function names parameter names and specifications etc internally the databaseconnection class is an abstract class implementing some of the basic methods but the fromconnectionstring method runs through list of registered specialized types that handles the actual differences and constructs an object of the right class in other words do not get databaseconnection object back get mssqldatabaseconnection or oracledatabaseconnection object back instead which of course inherit from databaseconnection the connection string contains information about what kind of database engine and version this connection is for would like to create similar library in python is the right approach to make something that can be constructed like this conn databaseconnection or using class method conn databaseconnection fromconnectionstring is the first even possible that is constructing an object like this and getting back something else specialized object depending on data in the passed string ok let me ask different question what is the pythonic way of doing this basically want to have the databaseconnection base class in python as well implementing the common methods and specialize in derived classes and have method or function somewhere that based on the connection string constructs and returns the right type of object
python does not care why type you return def databaseconnection str if isoracle str return oracleconnection str else return someotherconnection str
QA
are there any other good alternatives to zc buildout and or virtualenv for installing non python dependencies am member of team that is about to launch beta of python django specifically based web site and accompanying suite of backend tools the team itself has doubled in size from to over the past few weeks and we expect continued growth for the next couple of months at least one issue that has started to plague us is getting everyone up to speed in terms of getting their development environment configured and having all the right eggs installed etc am looking for ways to simplify this process and make it less error prone both zc buildout and virtualenv look like they would be good tools for addressing this problem but both seem to concentrate primarily on the python specific issues we have couple of small subprojects in other languages java and ruby specifically as well as numerous python extensions that have to be compiled natively lxml mysql drivers etc in fact one of the biggest thorns in our side has been getting some of these extensions compiled against appropriate versions of the shared libraries so as to avoid segfaults malloc errors and all sorts of similar issues it does not help that out of people we have different development environments leopard on ppc leopard on intel ubuntu and windows ultimately what would be ideal would be something that works roughly like this from the dos unix prompt git clone repository url python setup env py that then does what zc buildout virtualenv does copy symlink the python interpreter provide clean space to install eggs then installs all required eggs including installing any native shared library dependencies installs the ruby project the java project etc obviously this would be useful for both getting development environments up as well as deploying on staging production servers ideally would like for the tool that accomplishes this to be written in extensible via python since that is and always will be the lingua franca of our team but am open to solutions in other languages so my question then is does anyone have any suggestions for better alternatives or any experiences they can share using one of these solutions to handle larger broader install bases
puppet does not easily support the win world either if you are looking for deployment mechanism and not just dev setup tool you might consider looking into controltier http open controltier com which has open source cross platform solution beyond that you are looking at enterprise software such as bladelogic or opsware and typically an outrageous pricetag for the functionality offered my opinion obviously lot of folks have been aggressively using combination of puppet and capistrano even non rails developers for deployment automation tools to pretty good effect downside again is that it is expecting somewhat homogeneous environment
QA
how to handle broken pipe sigpipe in python have written simple multi threaded game server in python that creates new thread for each client connection am finding that every now and then the server will crash because of broken pipe sigpipe error am pretty sure it is happening when the program tries to send response back to client that is no longer present what is good way to deal with this my preferred resolution would simply close the server side connection to the client and move on rather than exit the entire program ps this question answer deals with the problem in generic way how specifically should solve it
read up on the try statement try do something except socket error socket error except ioerror if errno errno epipe epipe error else other error
QA
how to handle broken pipe sigpipe in python have written simple multi threaded game server in python that creates new thread for each client connection am finding that every now and then the server will crash because of broken pipe sigpipe error am pretty sure it is happening when the program tries to send response back to client that is no longer present what is good way to deal with this my preferred resolution would simply close the server side connection to the client and move on rather than exit the entire program ps this question answer deals with the problem in generic way how specifically should solve it
sigpipe although think maybe you mean epipe occurs on sockets when you shut down socket and then send data to it the simple solution is not to shut the socket down before trying to send it data this can also happen on pipes but it does not sound like that is what you are experiencing since it is network server you can also just apply the band aid of catching the exception in some top level handler in each thread of course if you used twisted rather than spawning new thread for each client connection you probably would not have this problem it is really hard maybe impossible depending on your application to get the ordering of close and write operations correct if multiple threads are dealing with the same channel
QA
what is the best way to change text contained in an xml file using python let us say have an existing trivial xml file named mydata xml that contains the following xml version encoding utf myelement foo myelement want to change the text value of foo to bar resulting in the following xml version encoding utf myelement bar myelement once am done want to save the changes what is the easiest and simplest way to accomplish all this
this is what wrote based on ryan answer from xml dom minidom import parse import os create backup of original file new file name mydata xml old file name new file name os rename new file name old file name change text value of element doc parse old file name node doc getelementsbytagname myelement node firstchild nodevalue bar persist changes to new file xml file open new file name doc writexml xml file encoding utf xml file close not sure if this was the easiest and simplest approach but it does work javier answer has less lines of code but requires non standard library
QA
what is the best way to change text contained in an xml file using python let us say have an existing trivial xml file named mydata xml that contains the following xml version encoding utf myelement foo myelement want to change the text value of foo to bar resulting in the following xml version encoding utf myelement bar myelement once am done want to save the changes what is the easiest and simplest way to accomplish all this
you also might want to check out uche ogbuji excellent xml data binding library amara http uche ogbuji net tech suite amara documentation here http platea pntic mec es jmorilla amara manual the cool thing about amara is that it turns an xml document in to python object so you can just do stuff like record doc xml create element you record nameelem doc xml create element you name content unicode name record xml append nameelem valueelem doc xml create element you value content unicode value record xml append valueelem which creates record element that contains name and value elements which in turn contain the values of the name and value variables
QA
how do convert list of ascii values to string in python have got list in python program that contains series of numbers which are themselves ascii values how do convert this into regular string that can echo to the screen
you are probably looking for chr join chr for in hello world
QA
how do convert list of ascii values to string in python have got list in python program that contains series of numbers which are themselves ascii values how do convert this into regular string that can echo to the screen
join chr for in print
QA
django userprofile without password would like to create subset of users that do not have login basically as way to add photographer field to photos without having full blown account associated with that person since in many cases they will never actually log in to the site caveat is that would also like to be able to enable an account for them later so think the question becomes what is the best way to set up people table that ties to the user table without actually extending the user table with userprofile
another upvote for insin answer handle this through userprofile james bennett has great article about extending django contrib auth models user he walks through couple methods explains their pros cons and lands on the userprofile way as ideal
QA
in the django admin interface is there way to duplicate an item just wondering if there is an easy way to add the functionality to duplicate an existing listing in the admin interface in data entry we have run into situation where lot of items share generic data with another item and to save time it would be very nice to quickly duplicate an existing listing and only alter the changed data using better model structure would be one way of reducing the duplication of the data but there may be situation where the duplicated data needs to be changed on an individual basis in the future
you can save as by just enabling adding this to your modeladmin save as true this replaces the save and add another button with save as button save as means the object will be saved as new object with new id rather than the old object
QA
keeping filters in django admin what would like to achive is go to admin site apply some filters to the list of objects click and object edit edit edit hit save site takes me to the list of objects unfiltered would like to have the filter from step remembered and applied is there an easy way to do it
unfortunately there is no easy way to do this the filtering does not seem to be saved in any session variable clicking back twice is the normal method but it can be unweildy and annoying if you have just changed an object so that it should no longer be shown using your filter if it is just one off click back twice or go through the filtering again it is the easiest way if you are going to be filtering more often or you just want to learn about hacking the admin which is pretty open and easy you will want to write filterspec have look here and here for examples of people writing their own really really terrible way to do this would be to edit the admin interface so that after you click save you are redirected to you filtered url would not recommend this at all but it is an option another fairly simple way to do this would be to write generic view to show your filtered objects then use django forms to edit the items from there would have look at this you will be stunned just how little code you have to write to get simple view edit page going
QA
how to handle broken pipe sigpipe in python have written simple multi threaded game server in python that creates new thread for each client connection am finding that every now and then the server will crash because of broken pipe sigpipe error am pretty sure it is happening when the program tries to send response back to client that is no longer present what is good way to deal with this my preferred resolution would simply close the server side connection to the client and move on rather than exit the entire program ps this question answer deals with the problem in generic way how specifically should solve it
assuming that you are using the standard socket module you should be catching the socket error broken pipe exception not ioerror as others have suggested this will be raised in the case that you have described sending writing to socket for which the remote side has disconnected import socket errno time setup socket to listen for incoming connections socket socket bind localhost listen remote address accept print got connection from address while try remote send message to peer time sleep except socket error if isinstance args tuple print errno is if errno epipe remote peer disconnected print detected remote disconnect else determine and handle different error pass else print socket error remote close break except ioerror hmmm can ioerror actually be raised by the socket module print got ioerror break note that this exception will not always be raised on the first write to closed socket more usually the second write unless the number of bytes written in the first write is larger than the socket buffer size you need to keep this in mind in case your application thinks that the remote end received the data from the first write when it may have already disconnected you can reduce the incidence but not entirely eliminate of this by using select select or poll check for data ready to read from the peer before attempting write if select reports that there is data available to read from the peer socket read it using socket recv if this returns an empty string the remote peer has closed the connection because there is still race condition here you will still need to catch and handle the exception twisted is great for this sort of thing however it sounds like you have already written fair bit of code
QA
what is the difference between python re search and re match what is the difference between the search and match functions in the python re module have read the documentation current documentation but never seem to remember it keep having to look it up and re learn it am hoping that someone will answer it clearly with examples so that perhaps it will stick in my head or at least will have better place to return with my question and it will take less time to re learn it
re match is anchored at the beginning of the string that has nothing to do with newlines so it is not the same as using in the pattern as re match documentation says if zero or more characters at the beginning of string match the regular expression pattern return corresponding matchobject instance return none if the string does not match the pattern note that this is different from zero length match note if you want to locate match anywhere in string use search instead re search searches the entire string as the documentation says scan through string looking for location where the regular expression pattern produces match and return corresponding matchobject instance return none if no position in the string matches the pattern note that this is different from finding zero length match at some point in the string so if you need to match at the beginning of the string or to match the entire string use match it is faster otherwise use search the documentation has specific section for match vs search that also covers multiline strings python offers two different primitive operations based on regular expressions match checks for match only at the beginning of the string while search checks for match anywhere in the string this is what perl does by default note that match may differ from search even when using regular expression beginning with matches only at the start of the string or in multiline mode also immediately following newline the match operation succeeds only if the pattern matches at the start of the string regardless of mode or at the starting position given by the optional pos argument regardless of whether newline precedes it now enough talk time to some example code example code string with newlines something someotherthing import re print re match some string with newlines matches print re match someother string with newlines will not match print re match someother string with newlines re multiline also will not match print re search someother string with newlines finds something print re search someother string with newlines re multiline also finds something re compile thing re multiline print match string with newlines no match print match string with newlines pos matches print search string with newlines re multiline also matches
QA
what is the difference between python re search and re match what is the difference between the search and match functions in the python re module have read the documentation current documentation but never seem to remember it keep having to look it up and re learn it am hoping that someone will answer it clearly with examples so that perhaps it will stick in my head or at least will have better place to return with my question and it will take less time to re learn it
re match attempts to match pattern at the beginning of the string re search attempts to match the pattern throughout the string until it finds match
QA
what is the difference between python re search and re match what is the difference between the search and match functions in the python re module have read the documentation current documentation but never seem to remember it keep having to look it up and re learn it am hoping that someone will answer it clearly with examples so that perhaps it will stick in my head or at least will have better place to return with my question and it will take less time to re learn it
have you had look at the documentation python offers two different primitive operations based on regular expressions match checks for match only at the beginning of the string while search checks for match anywhere in the string this is what perl does by default
QA
what is the difference between python re search and re match what is the difference between the search and match functions in the python re module have read the documentation current documentation but never seem to remember it keep having to look it up and re learn it am hoping that someone will answer it clearly with examples so that perhaps it will stick in my head or at least will have better place to return with my question and it will take less time to re learn it
re search searches for the pattern throughout the string whereas re match does not search the pattern if it does not it has no other choice than to match it at start of the string
QA
how do convert list of ascii values to string in python have got list in python program that contains series of numbers which are themselves ascii values how do convert this into regular string that can echo to the screen
same basic solution as others but personally prefer to use map instead of the list comprehension join map chr hello world
QA
python beyond the basics have gotten to grips with the basics of python and have got small holiday which want to use some of to learn little more python the problem is that have no idea what to learn or where to start am primarily web development but in this case do not know how much difference it will make
search alex martelli alex martelli patterns and thomas wouters on google video there is plenty of interesting talks on andvanced python design patterns in python and so on
QA
building full text search engine where to start want to write web application using google app engine so the reference language would be python my application needs simple search engine so the users would be able to find data specifying keywords for example if have one table with those rows office space space odyssey brazil and the user queries for space rows and would be returned if the user queries for office space the result should be rows and too row first what are the technical guidelines algorithms to do this in simple way can you give me good pointers to the theory behind this thanks edit am not looking for anything complex here say indexing tons of data
the book introduction to information retrieval provides good introduction to the field dead tree version is published by cambridge university press but you can also find free online edition in html and pdf following the link above
QA
building full text search engine where to start want to write web application using google app engine so the reference language would be python my application needs simple search engine so the users would be able to find data specifying keywords for example if have one table with those rows office space space odyssey brazil and the user queries for space rows and would be returned if the user queries for office space the result should be rows and too row first what are the technical guidelines algorithms to do this in simple way can you give me good pointers to the theory behind this thanks edit am not looking for anything complex here say indexing tons of data
look into the book managing gigabytes it covers storage and retrieval of huge amounts of plain text data eg both compression and actual searching and variety of the algorithms that can be used for each also for plain text retrieval you are best off using vector based search system rather than keyword document indexing system as vector based systems can be much faster and more importantly can provide relevancy ranking relatively trivially
QA
average difference between dates in python have series of datetime objects and would like to calculate the average delta between them for example if the input was then the average delta would be exactly or minutes any suggestions on how to calculate this using python
say is your list sumdeltas timedelta seconds while len sumdeltas avg delta sumdeltas len this will indeed average your deltas together
QA
how do use owfs to read an ibutton temperature logger have installed owfs and am trying to read the data off ibutton temperature logger owfs let us me mount the ibutton as fuse filesystem and can see all the data am having trouble figuring out what is the best way to access the data though can get individual readings by catting the files cat onewire deviceid log temperature but the onewire deviceid log temperature all file is broken possible too large as histogram temperature all work fine python script to read all files seems to work but takes very long time is there better way to do it does anyone have any examples am using ubuntu and could not get the java one wire viewer app to run update using owpython installed with owfs can get the current temperature but cannot figure out how to get access to the recorded logs import ow ow init you initialize usb ow sensor sensorlist sensor fd sensor ow sensor print type temperature ds log gives an attributeerror
have also had problems with owfs found it to be an overengineered solution to what is simple problem now am using the digitemp code without problem found it to be flexible and reliable for instance store the room temperature in log file every minute by running usr local bin digitemp ds usr local etc digitemp conf var log temperature to reach that point downloaded the source file untarred it and then did the following compile the hardware specific command make ds initialize the configuration file digitemp ds dev ttys run command to obtain temperature and verify your setup digitemp ds copy the configuration file to an accessible place cp digitemprc usr local etc digitemp conf also hand edited my configuration file to adjust it to my setup this is how it ended up tty dev ttys read time log type log format sensor cnt format sensor hum format sensor sensors rom xd in my case also created etc init digitemp file and enabled it to run at startup bin sh system startup script for the temperature monitoring daemon begin init info provides digitemp required start should start required stop should stop default start default stop description start the temperature monitoring daemon end init info digitemp usr local bin digitemp ds test digitemp exit digitemp config root digitemp conf test digitemp config exit digitemp logfile var log temperature source suse config etc rc status rc reset case in start echo starting temperature monitoring daemon startproc digitemp digitemp config digitemp logfile rc status stop echo shutting down temperature monitoring daemon killproc term digitemp rc status try restart status dev null restart rc status restart stop start rc status force reload try restart rc status reload try restart rc status status echo checking for temperature monitoring service checkproc digitemp rc status echo usage start stop status try restart restart force reload reload exit esac rc exit
QA
python style multiple line conditions in ifs sometimes break long conditions in ifs to several lines the most obvious way to do this is if cond val and cond val and cond val and cond val do something is not very very appealing visually because the action blends with the conditions however it is the natural way using correct python indentation of spaces for the moment am using if cond val and cond val and cond val and cond val do something but this is not very pretty can you recommend an alternative way
this does not improve so much but allcondsareok cond val and cond val and cond val and cond val if allcondsareok do something
QA
python style multiple line conditions in ifs sometimes break long conditions in ifs to several lines the most obvious way to do this is if cond val and cond val and cond val and cond val do something is not very very appealing visually because the action blends with the conditions however it is the natural way using correct python indentation of spaces for the moment am using if cond val and cond val and cond val and cond val do something but this is not very pretty can you recommend an alternative way
you do not need to use spaces on your second conditional line maybe use if cond val and cond val and cond val and cond val do something also do not forget the whitespace is more flexible than you might think if cond val and cond val and cond val and cond val do something if cond val and cond val and cond val and cond val do something both of those are fairly ugly though maybe lose the brackets the style guide discourages this though if cond val and cond val and cond val and cond val do something this at least gives you some differentiation or even if cond val and cond val and cond val and cond val do something think prefer if cond val and cond val and cond val and cond val do something here is the style guide which since recommends using brackets
QA
py exe including msvc dlls in the exe when using py exe to distribute python applications with wxpython some msvc dlls are usually needed to make the exe work on freshly installed machines in particular the two most common dlls are msvcp dll and msvcr dll the former can be included in the exe using this tip however the latter is just placed in the dist dir by py exe and not into the executable even if specifically ask to include it any idea how to cause py exe to include both inside the exe
would not it fail to launch then you want msvcr dll in the same directory as the exe so that the library loader will be able to find and link it into the application memory map it is needed for basic operation so you cannot just let py exe unpack it with the rest of the dlls
QA
wxpython displaying multiple widgets in same frame would like to be able to display notebook and txtctrl wx widgets in single frame below is an example adapted from the wxpython wiki is it possible to change their layout maybe with something like wx splitterwindow to display the text box below the notebook in the same frame import wx import wx lib sheet as sheet class mysheet sheet csheet def init self parent sheet csheet init self parent self setlabelbackgroundcolour ccff self setnumberrows self setnumbercols class notebook wx frame def init self parent id title wx frame init self parent id title size menubar wx menubar file wx menu file append quit menubar append file file self setmenubar menubar wx evt menu self self onquit nb wx notebook self style wx nb bottom self sheet mysheet nb self sheet mysheet nb self sheet mysheet nb nb addpage self sheet sheet nb addpage self sheet sheet nb addpage self sheet sheet self sheet setfocus self statusbar def statusbar self self statusbar self createstatusbar def onquit self event self close class myframe wx frame def init self parent id title wx frame init self parent id title wx defaultposition wx size self text wx textctrl self style wx te multiline self center class myapp wx app def oninit self frame notebook none notebook py frame show true frame center frame myframe none frame show true self settopwindow frame return true app myapp app mainloop
you can use splitter yes also it makes sense to create panel place your widgets in it with sizers and add this panel to the frame
QA
what is the problem with reduce there seems to be lot of heated discussion on the net about the changes to the reduce function in python and how it should be removed am having little difficulty understanding why this is the case find it quite reasonable to use it in variety of cases if the contempt was simply subjective cannot imagine that such large number of people would care about it what am missing what is the problem with reduce
people worry it encourages an obfuscated style of programming doing something that can be achieved with clearer methods am not against reduce myself also find it useful tool sometimes
QA
wxpython displaying multiple widgets in same frame would like to be able to display notebook and txtctrl wx widgets in single frame below is an example adapted from the wxpython wiki is it possible to change their layout maybe with something like wx splitterwindow to display the text box below the notebook in the same frame import wx import wx lib sheet as sheet class mysheet sheet csheet def init self parent sheet csheet init self parent self setlabelbackgroundcolour ccff self setnumberrows self setnumbercols class notebook wx frame def init self parent id title wx frame init self parent id title size menubar wx menubar file wx menu file append quit menubar append file file self setmenubar menubar wx evt menu self self onquit nb wx notebook self style wx nb bottom self sheet mysheet nb self sheet mysheet nb self sheet mysheet nb nb addpage self sheet sheet nb addpage self sheet sheet nb addpage self sheet sheet self sheet setfocus self statusbar def statusbar self self statusbar self createstatusbar def onquit self event self close class myframe wx frame def init self parent id title wx frame init self parent id title wx defaultposition wx size self text wx textctrl self style wx te multiline self center class myapp wx app def oninit self frame notebook none notebook py frame show true frame center frame myframe none frame show true self settopwindow frame return true app myapp app mainloop
making two widgets appear on the same frame is easy actually you should use sizers to accomplish this in your example you can change your notebook class implementation to something like this class notebook wx frame def init self parent id title wx frame init self parent id title size menubar wx menubar file wx menu file append quit menubar append file file self setmenubar menubar wx evt menu self self onquit nb wx notebook self style wx nb bottom self sheet mysheet nb self sheet mysheet nb self sheet mysheet nb nb addpage self sheet sheet nb addpage self sheet sheet nb addpage self sheet sheet self sheet setfocus self statusbar new code begins here add your text ctrl self text wx textctrl self style wx te multiline create new sizer for both controls sizer wx boxsizer wx vertical add notebook first with size factor sizer add nb then text size factor maximized sizer add self text wx expand assign the sizer to frame self setsizerandfit sizer only the init method is changed note that you can manipulate the proportions between the notebook and text control by changing the second argument of the add method you can learn more about sizers from the official sizer overview article
QA
python style multiple line conditions in ifs sometimes break long conditions in ifs to several lines the most obvious way to do this is if cond val and cond val and cond val and cond val do something is not very very appealing visually because the action blends with the conditions however it is the natural way using correct python indentation of spaces for the moment am using if cond val and cond val and cond val and cond val do something but this is not very pretty can you recommend an alternative way
suggest moving the and keyword to the second line and indenting all lines containing conditions with two spaces instead of four if cond val and cond val and cond val and cond val do something this is exactly how solve this problem in my code having keyword as the first word in the line makes the condition lot more readable and reducing the number of spaces further distinguishes condition from action
QA
what is the problem with reduce there seems to be lot of heated discussion on the net about the changes to the reduce function in python and how it should be removed am having little difficulty understanding why this is the case find it quite reasonable to use it in variety of cases if the contempt was simply subjective cannot imagine that such large number of people would care about it what am missing what is the problem with reduce
reduce is not being removed it is simply being moved into the functools module guido reasoning is that except for trivial cases like summation code written using reduce is usually clearer when written as an accumulation loop
QA
disable output buffering is output buffering enabled by default in python interpreter for sys stdout if the answer is positive what are all the ways to disable it suggestions so far use the you command line switch wrap sys stdout in an object that flushes after every write set pythonunbuffered env var sys stdout os fdopen sys stdout fileno is there any other way to set some global flag in sys sys stdout programmatically during execution
reopen stdout file descriptor with write mode and as the buffer size unbuffered sys stdout os fdopen sys stdout fileno credits sebastian somewhere on the python mailing list
QA
what is the problem with reduce there seems to be lot of heated discussion on the net about the changes to the reduce function in python and how it should be removed am having little difficulty understanding why this is the case find it quite reasonable to use it in variety of cases if the contempt was simply subjective cannot imagine that such large number of people would care about it what am missing what is the problem with reduce
as guido says in his the fate of reduce in python post so now reduce this is actually the one have always hated most because apart from few examples involving or almost every time see reduce call with non trivial function argument need to grab pen and paper to diagram what is actually being fed into that function before understand what the reduce is supposed to do so in my mind the applicability of reduce is pretty much limited to associative operators and in all other cases it is better to write out the accumulation loop explicitly there is an excellent example of confusing reduce in the functional programming howto article quick what is the following code doing total reduce lambda items you can figure it out but it takes time to disentangle the expression to figure out what is going on using short nested def statements makes things little bit better def combine return total reduce combine items but it would be best of all if had simply used for loop total for in items total or the sum built in and generator expression total sum for in items many uses of reduce are clearer when written as for loops
QA
when to use the python debugger since python is dynamic interpreted language you do not have to compile your code before running it hence it is very easy to simply write your code run it see what problems occur and fix them using hotkeys or macros can make this incredibly quick so because it is so easy to immediately see the output of your program and any errors that may occur have not uses debugger tool yet what situations may call for using real debugger vs the method currently use would like to know before get into situation and get frustrated because do not know how to fix the problem
any time you want to inspect the contents of variables that may have caused the error the only way you can do that is to stop execution and take look at the stack pydev in eclipse is pretty good ide if you are looking for one
QA
when to use the python debugger since python is dynamic interpreted language you do not have to compile your code before running it hence it is very easy to simply write your code run it see what problems occur and fix them using hotkeys or macros can make this incredibly quick so because it is so easy to immediately see the output of your program and any errors that may occur have not uses debugger tool yet what situations may call for using real debugger vs the method currently use would like to know before get into situation and get frustrated because do not know how to fix the problem
use pdb for basic python debugging some of the situations use it are when you have loop iterating over entries and want to break at specific point it becomes really helpful conditional breaks trace the control flow of someone else code its always better to use debugger than litter the code with prints normally there can be more than one point of failures resulting in bug all are not obvious in the first look so you look for obvious places if nothing is wrong there you move ahead and add some more prints debugger can save you time here you do not need to add the print and run again
QA
when to use the python debugger since python is dynamic interpreted language you do not have to compile your code before running it hence it is very easy to simply write your code run it see what problems occur and fix them using hotkeys or macros can make this incredibly quick so because it is so easy to immediately see the output of your program and any errors that may occur have not uses debugger tool yet what situations may call for using real debugger vs the method currently use would like to know before get into situation and get frustrated because do not know how to fix the problem
usually when the error is buried in some function but do not know exactly what or where either insert dozens of log debug calls and then have to take them back out or just put in import pdb pdb set trace and then run the program the debugger will launch when it reaches that point and give me full repl to poke around in
QA
how do turn an rss feed back into rss according to the feedparser documentation can turn an rss feed into parsed object like this import feedparser feedparser parse http feedparser org docs examples atom xml but cannot find anything showing how to go the other way would like to be able do manipulate would and then output the result as xml print toxml but there does not seem to be anything in feedparser for going in that direction am going to have to loop through various elements or is there quicker way
from xml dom import minidom doc minidom parse your file xml print doc toxml the only problem is that it do not download feeds from the internet
QA
python style multiple line conditions in ifs sometimes break long conditions in ifs to several lines the most obvious way to do this is if cond val and cond val and cond val and cond val do something is not very very appealing visually because the action blends with the conditions however it is the natural way using correct python indentation of spaces for the moment am using if cond val and cond val and cond val and cond val do something but this is not very pretty can you recommend an alternative way
prefer this style when have terribly large if condition if expr and expr or expr and hasattr thingy eq or status happytimes do stuff else do other stuff
QA
how do turn an rss feed back into rss according to the feedparser documentation can turn an rss feed into parsed object like this import feedparser feedparser parse http feedparser org docs examples atom xml but cannot find anything showing how to go the other way would like to be able do manipulate would and then output the result as xml print toxml but there does not seem to be anything in feedparser for going in that direction am going to have to loop through various elements or is there quicker way
as method of making feed how about pyrss gen have not played with feedparser but have you tried just doing str yourfeedparserobject have often been suprised by various modules that have str methods to just output the object as text edit just tried the str method and it does not work on this one worth shot though
QA
how do turn an rss feed back into rss according to the feedparser documentation can turn an rss feed into parsed object like this import feedparser feedparser parse http feedparser org docs examples atom xml but cannot find anything showing how to go the other way would like to be able do manipulate would and then output the result as xml print toxml but there does not seem to be anything in feedparser for going in that direction am going to have to loop through various elements or is there quicker way
if you are looking to read in an xml feed modify it and then output it again there is page on the main python wiki indicating that the rss py library might support what you are after it reads most rss and is able to output rss have not looked at it in much detail though
QA
when to use the python debugger since python is dynamic interpreted language you do not have to compile your code before running it hence it is very easy to simply write your code run it see what problems occur and fix them using hotkeys or macros can make this incredibly quick so because it is so easy to immediately see the output of your program and any errors that may occur have not uses debugger tool yet what situations may call for using real debugger vs the method currently use would like to know before get into situation and get frustrated because do not know how to fix the problem
in years of programming have used debugger exactly times all four times were to read the core file produced from program crashing to locate the traceback information that is buried in there do not think debuggers help much even in compiled languages many people like debuggers there are some reasons for using them am sure or people would not lavish such love and care on them here is the point software is knowledge capture yes it does have to run more importantly however software has meaning this is not an indictment of your use of debugger however find that the folks who rely on debugging will sometimes produce really odd looking code and will not have good justification for what it means they can only say it may be hack but it works my suggestion on debuggers is do not bother but what if am totally stumped you ask should learn the debugger then totally stumped by what the language python too simple for utter befuddlement some library perhaps here is what you do with or without debugger you have the source read it you write small tests to exercise the library using the interactive she will if possible all the really good libraries seem to show their features using the interactive python mode strive for this level of tight clear simplicity you have the source add print functions
QA
python style multiple line conditions in ifs sometimes break long conditions in ifs to several lines the most obvious way to do this is if cond val and cond val and cond val and cond val do something is not very very appealing visually because the action blends with the conditions however it is the natural way using correct python indentation of spaces for the moment am using if cond val and cond val and cond val and cond val do something but this is not very pretty can you recommend an alternative way
have resorted to the following in the degenerate case where it is simply and or or if all cond val cond val cond val cond val if any cond val cond val cond val cond val it shaves few characters and makes it clear that there is no subtlety to the condition
QA
setup python enviroment on windows how do setup python enviroment on windows computer so can start writing and running python scripts is there an install bundle also which database should use thanks sorry should of mentioned that am using this for web based applications does it require apache or does it use another http server what is the standard setup for python running web apps
download the python windows installer from python org direct link if you are just learning use the included sqlite library so you do not have to fiddle with database servers most web development frameworks django turbogears etc come with built in webserver command that runs on the local computer without apache
QA
py exe including msvc dlls in the exe when using py exe to distribute python applications with wxpython some msvc dlls are usually needed to make the exe work on freshly installed machines in particular the two most common dlls are msvcp dll and msvcr dll the former can be included in the exe using this tip however the latter is just placed in the dist dir by py exe and not into the executable even if specifically ask to include it any idea how to cause py exe to include both inside the exe
py exe cannot do this you can wrap py exe there is an example on the wiki showing how to do that with nsis you could build your own wrapper if using nsis or innosetup was not an option alternatively if you are positive that your users will have compatible copy of msvcr dll installed iirc vista or xp sp users then you could get away without including it more usefully perhaps if you use python or older then python links against msvcr dll rather than msvcr dll and any windows user will have that installed so you can just not worry about it
QA
python style multiple line conditions in ifs sometimes break long conditions in ifs to several lines the most obvious way to do this is if cond val and cond val and cond val and cond val do something is not very very appealing visually because the action blends with the conditions however it is the natural way using correct python indentation of spaces for the moment am using if cond val and cond val and cond val and cond val do something but this is not very pretty can you recommend an alternative way
all and any are nice for the many conditions of same type case but they always evaluates all conditions as shown in this example def print executed return false def print executed return false print simple and aborts early if and pass print print all executes all if all pass print
QA
code to verify updates from the google safe browsing api in order to verify the data coming from the google safe browsing api you can calculate message authentication code mac for each update the instructions to do this from google are the mac is computed from an md digest over the following information client key separator table data separator client key the separator is the string coolgoog that is colon followed by coolgoog followed by colon the resulting bit md digest is websafe base encoded there is also example data to check against client key eirwn ktwczgwa hxtarq response goog black hash update mac dralftu bxwuhlk ncgjtq bdf ad ef fa bc ac bbbd cbb ec ed bc note that there are tabs at the end of each line am unable to get match please either point out where am going wrong or just write the couple of lines of python code necessary to do this fwiw expected to be able to do something like this bdf ad ef fa bc ac bbbd cbb ec ed bc eirwn ktwczgwa hxtarq hashlib md coolgoog coolgoog digest encode base qfb mxphrs ytofpkceg but as you can see qfb mxphrs ytofpkceg dralftu bxwuhlk ncgjtq
eirwn ktwczgwa hxtarq decode base
QA
setup python enviroment on windows how do setup python enviroment on windows computer so can start writing and running python scripts is there an install bundle also which database should use thanks sorry should of mentioned that am using this for web based applications does it require apache or does it use another http server what is the standard setup for python running web apps
do not forget to install pywin after installing the official command line installer this will define additional start menu items and the highly useful pythonwin ide an installer for both is available at activestate no yet the activestate distribution contains additional documentation
QA
setup python enviroment on windows how do setup python enviroment on windows computer so can start writing and running python scripts is there an install bundle also which database should use thanks sorry should of mentioned that am using this for web based applications does it require apache or does it use another http server what is the standard setup for python running web apps
django tutorial how to install django provides good example how web development python environment may look