prefix
stringclasses
1 value
input_text
stringlengths
19
27.3k
target_text
stringlengths
2
24.8k
QA
replacement for for if array iteration love list comprehensions in python because they concisely represent transformation of list however in other languages frequently find myself writing something along the lines of foreach int in intarray if generic condition on do other processing this example is in where am under the impression linq can help with this but is there some common programming construct which can replace this slightly less than elegant solution perhaps data structure am not considering
in ruby intarray select each do do other processing end or if other processing is short one liner intarray select each something that uses lastly if you want to return new array containing the results of the processing of those elements greater than intarray select map do something to
QA
replacement for for if array iteration love list comprehensions in python because they concisely represent transformation of list however in other languages frequently find myself writing something along the lines of foreach int in intarray if generic condition on do other processing this example is in where am under the impression linq can help with this but is there some common programming construct which can replace this slightly less than elegant solution perhaps data structure am not considering
in python you have filter and map which can so what you want map lambda foo filter lambda intarray there is also list comprehensions which can do both in one easy statement for in intarray if
QA
replacement for for if array iteration love list comprehensions in python because they concisely represent transformation of list however in other languages frequently find myself writing something along the lines of foreach int in intarray if generic condition on do other processing this example is in where am under the impression linq can help with this but is there some common programming construct which can replace this slightly less than elegant solution perhaps data structure am not considering
in you can apply selective processing on anything that lives inside an ienumerable like this intarray where convertall dostuff intarray where etc
QA
replacement for for if array iteration love list comprehensions in python because they concisely represent transformation of list however in other languages frequently find myself writing something along the lines of foreach int in intarray if generic condition on do other processing this example is in where am under the impression linq can help with this but is there some common programming construct which can replace this slightly less than elegant solution perhaps data structure am not considering
the increment in the original foreach loop will not affect the contents of the array the only way to do this remains for loop for int intarray length if intarray intarray linq is not intended to modify existing collections or sequences it creates new sequences based on existing ones it is possible to achieve the above code using linq though it is slightly against its purposes var newarray from in intarray select var newarray intarray select using where or equivalent as shown in some of the other answers will exclude any values less than or equal to from the resulting sequence var intarray new int var newarray from in intarray where select newarray there is foreach method on arrays that will allow you to use lambda function instead of foreach block though for anything more than method call would stick with foreach intarray foreach dosomething
QA
python version of php stripslashes wrote piece of code to convert php striplashes into valid python backslash escapes cleaned stringwithslashes cleaned cleaned replace cleaned cleaned replace cleaned cleaned replace how can condense it
you can obviously concatenate everything together cleaned stringwithslashes replace replace replace is that what you were after or were you hoping for something more terse
QA
python version of php stripslashes wrote piece of code to convert php striplashes into valid python backslash escapes cleaned stringwithslashes cleaned cleaned replace cleaned cleaned replace cleaned cleaned replace how can condense it
not totally sure this is what you want but cleaned stringwithslashes decode string escape
QA
python version of php stripslashes wrote piece of code to convert php striplashes into valid python backslash escapes cleaned stringwithslashes cleaned cleaned replace cleaned cleaned replace cleaned cleaned replace how can condense it
it sounds like what you want could be reasonably efficiently handled through regular expressions import re def stripslashes are re sub are re sub return cleaned stripslashes stringwithslashes
QA
python regular expressions to implement string unescaping am trying to implement string unescaping with python regex and backreferences and it does not seem to want to work very well am sure it is something am doing wrong but cannot figure out what import re mystring this is test re compile sub mystring this is test sub mystring this is test sub mystring this is test would like to replace char with char but backreferences in python do not appear to follow the same rules they do in every other implementation have ever used could someone she would some light
well think you might have missed the or miscounted the backslashes import re mystring this is test re compile print sub mystring this is test are which if understood is what was requested suspect the more common request is this re compile nrfv print sub lambda mo mo group mystring this is test the interested student should also read ken thompson reflections on trusting trust wherein our hero uses similar example to explain the perils of trusting compilers you have not bootstrapped from machine code yourself
QA
python regular expressions to implement string unescaping am trying to implement string unescaping with python regex and backreferences and it does not seem to want to work very well am sure it is something am doing wrong but cannot figure out what import re mystring this is test re compile sub mystring this is test sub mystring this is test sub mystring this is test would like to replace char with char but backreferences in python do not appear to follow the same rules they do in every other implementation have ever used could someone she would some light
you are being tricked by python representation of the result string the python expression this is test represents the string this is test which is think what you wanted try adding print in front of each of your sub calls to print the actual string returned instead of python representation of the string mystring this is test mystring this is test print mystring this is test
QA
can you explain closures as they relate to python have been reading lot about closures and think understand them but without clouding the picture for myself and others am hoping someone can explain closures as succinctly and clearly as possible am looking for simple explanation that might help me understand where and why would want to use them
it is simple function that references variables from containing scope potentially after flow of control has left that scope that last bit is very useful def makeconstantadder constant def adder return constant return adder makeconstantadder makeconstantadder note that and have disappeared inside and respectively this feature is what make and proper closures
QA
python regular expressions to implement string unescaping am trying to implement string unescaping with python regex and backreferences and it does not seem to want to work very well am sure it is something am doing wrong but cannot figure out what import re mystring this is test re compile sub mystring this is test sub mystring this is test sub mystring this is test would like to replace char with char but backreferences in python do not appear to follow the same rules they do in every other implementation have ever used could someone she would some light
the idea is that will read in an escaped string and unescape it feature notably lacking from python which you should not need to resort to regular expressions for in the first place unfortunately am not being tricked by the backslashes another illustrative example mystring this is ridiculous print mystring this is ridiculous re compile print sub bloody mystring this is bloody ridiculous print sub mystring this is ridiculous print sub mystring this is ridiculous print sub mystring this is ridiculous what would like it to print is this is ridiculous
QA
can you explain closures as they relate to python have been reading lot about closures and think understand them but without clouding the picture for myself and others am hoping someone can explain closures as succinctly and clearly as possible am looking for simple explanation that might help me understand where and why would want to use them
have never heard of transactions being used in the same context as explaining what closure is and there really are not any transaction semantics here it is called closure because it closes over the outside variable constant it is not just function but an enclosure of the environment where the function was created in the following example calling the closure after changing will also change the value of within since closes over def def return return closure print closure print closure
QA
can you explain closures as they relate to python have been reading lot about closures and think understand them but without clouding the picture for myself and others am hoping someone can explain closures as succinctly and clearly as possible am looking for simple explanation that might help me understand where and why would want to use them
like this rough succinct definition function that can refer to environments that are no longer active would add closure allows you to bind variables into function without passing them as parameters decorators which accept parameters are common use for closures closures are common implementation mechanism for that sort of function factory frequently choose to use closures in the strategy pattern when the strategy is modified by data at run time in language that allows anonymous block definition ruby closures can be used to implement what amount to novel new control structures the lack of anonymous blocks is among the limitations of closures in python
QA
python regular expressions to implement string unescaping am trying to implement string unescaping with python regex and backreferences and it does not seem to want to work very well am sure it is something am doing wrong but cannot figure out what import re mystring this is test re compile sub mystring this is test sub mystring this is test sub mystring this is test would like to replace char with char but backreferences in python do not appear to follow the same rules they do in every other implementation have ever used could someone she would some light
is not that what anders second example does in there is also string escape encoding you can apply mystring this is test mystring decode string escape this is test print mystring decode string escape this is test
QA
python sound bell would like to have python program alert me when it has completed its task by making beep noise currently use import os and then use command line speech program to say process complete much rather it be simple bell know that there is function that can be used in cocoa apps nsbeep but do not think that has much anything to do with this have also tried print but that did not work am using mac if you could not tell by my cocoa comment so that may help thanks
have you tried import sys sys stdout write sys stdout flush that works for me here on mac os actually think your original attempt works also with little modification print you just need the single quotes around the character sequence
QA
python regular expressions to implement string unescaping am trying to implement string unescaping with python regex and backreferences and it does not seem to want to work very well am sure it is something am doing wrong but cannot figure out what import re mystring this is test re compile sub mystring this is test sub mystring this is test sub mystring this is test would like to replace char with char but backreferences in python do not appear to follow the same rules they do in every other implementation have ever used could someone she would some light
mark his second example requires every escaped character thrown into an array initially which generates keyerror if the escape sequence happens not to be in the array it will die on anything but the three characters provided give try and enumerating every possible escape sequence every time you want to unescape string or keeping global array is really bad solution analogous to php that is using preg replace callback with lambda instead of preg replace which is utterly unnecessary in this situation am sorry if am coming off as dick about it am just utterly frustrated with python this is supported by every other regular expression engine have ever used and cannot understand why this would not work thank you for responding the string decode string escape function is precisely what was looking for initially if someone has general solution to the regex backreference problem feel free to post it and will accept that as an answer as well
QA
python sound bell would like to have python program alert me when it has completed its task by making beep noise currently use import os and then use command line speech program to say process complete much rather it be simple bell know that there is function that can be used in cocoa apps nsbeep but do not think that has much anything to do with this have also tried print but that did not work am using mac if you could not tell by my cocoa comment so that may help thanks
had to turn off the silence terminal bell option in my active terminal profile in iterm for print to work it seemed to work fine by default in terminal you can also use the mac module carbon snd to play the system beep import carbon snd carbon snd sysbeep the carbon modules do not have any documentation so had to use help carbon snd to see what functions were available it seems to be direct interface onto carbon so the docs on apple developer connection probably help
QA
is there python module for regex matching in zip files have over million text files compressed into zip files also have list of about model names of phones want to find out the number of times particular model was mentioned in the text files is there any python module which can do regex match on the files without unzipping it is there simple way to solve this problem without unzipping
you could loop through the zip files reading individual files using the zipfile module and running your regex on those eliminating to unzip all the files at once am fairly certain that you cannot run regex over the zipped data at least not meaningfully
QA
is there python module for regex matching in zip files have over million text files compressed into zip files also have list of about model names of phones want to find out the number of times particular model was mentioned in the text files is there any python module which can do regex match on the files without unzipping it is there simple way to solve this problem without unzipping
to access the contents of zip file you have to unzip it although the zipfile package makes this fairly easy as you can unzip each file within an archive individually python zipfile module
QA
is there python module for regex matching in zip files have over million text files compressed into zip files also have list of about model names of phones want to find out the number of times particular model was mentioned in the text files is there any python module which can do regex match on the files without unzipping it is there simple way to solve this problem without unzipping
there is nothing that will automatically do what you want however there is python zipfile module that will make this easy to do here is how to iterate over the lines in the file usr bin python import zipfile zipfile zipfile myfile zip for subfile in namelist print subfile data read subfile for line in data split print line
QA
regex and unicode have script that parses the filenames of tv episodes show name avi for example grabs the episode name from the www thetvdb com api and automatically renames them into something nicer show name avi the script works fine that is until you try and use it on files that have unicode show names something never really thought about since all the files have are english so mostly pretty much all fall within za how can allow the regular expressions to match accented characters and the likes currently the regex config section looks like config valid filename chars abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz config valid filename chars regex re escape config valid filename chars config name parse foo re compile ss ee config valid filename chars regex foo re compile config valid filename chars regex foo foo re compile ss ee config valid filename chars regex foo re compile config valid filename chars regex foo re compile config valid filename chars regex
use subrange of uffff for what you want you can also use the re unicode compile flag the docs say that if unicode is set will match the characters plus whatever is classified as alphanumeric in the unicode character properties database see also http coding derkeiler com archive python comp lang python html
QA
regex and unicode have script that parses the filenames of tv episodes show name avi for example grabs the episode name from the www thetvdb com api and automatically renames them into something nicer show name avi the script works fine that is until you try and use it on files that have unicode show names something never really thought about since all the files have are english so mostly pretty much all fall within za how can allow the regular expressions to match accented characters and the likes currently the regex config section looks like config valid filename chars abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz config valid filename chars regex re escape config valid filename chars config name parse foo re compile ss ee config valid filename chars regex foo re compile config valid filename chars regex foo foo re compile ss ee config valid filename chars regex foo re compile config valid filename chars regex foo re compile config valid filename chars regex
seems to be available as generic word character in some languages it allows you to match single character disregarding of how many bytes it takes up might be useful
QA
regex and unicode have script that parses the filenames of tv episodes show name avi for example grabs the episode name from the www thetvdb com api and automatically renames them into something nicer show name avi the script works fine that is until you try and use it on files that have unicode show names something never really thought about since all the files have are english so mostly pretty much all fall within za how can allow the regular expressions to match accented characters and the likes currently the regex config section looks like config valid filename chars abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz config valid filename chars regex re escape config valid filename chars config name parse foo re compile ss ee config valid filename chars regex foo re compile config valid filename chars regex foo foo re compile ss ee config valid filename chars regex foo re compile config valid filename chars regex foo re compile config valid filename chars regex
in mastering regular expressions from jeffrey friedl great book it is mentioned that you could use letter which will match unicode stuff that is considered letter
QA
pylons error mysql server has gone away hope this is not too obscure will ask the newsgroup if nobody knows here am using pylons python framework to serve simple web application but it seems to die from time to time with this in the error log mysql server has gone away did bit of checking and saw that this was because the connections to mysql were not being renewed this should not be problem though because the sqlalchemy pool recycle in the config file should automatically keep it alive the default was but dialed it back to because of this problem it helped bit but should be fine according to the docs the errors still happen semi regularly do not want to lower it too much though and dos my own database maybe something in my mysql config is goofy not sure where to look exactly other relevant details python pylons sql alchemy mysql
you might want to check mysql timeout variables show variables like timeout you are probably interested in wait timeout less likely but possible interactive timeout on debian and ubuntu the defaults are mysql kills connections after hours but maybe the default for your platform is different or whoever administrates the server has configured things differently afaict pool recycle does not actually keep the connections alive it expires them on its own before mysql kills them am not familiar with pylons but if causing the connections to intermittently do select is an option that will keep them alive at the cost of basically no server load and minimal network traffic one final thought are you somehow managing to use connection that pylons thinks it has expired
QA
how to sell python to client boss person with lots of cash when asked to create system xyz and you ask to do it in python over php or ruby what are the main features you can mention when they require you to explain it
agree with mreggen tell them by working in python you can get things done faster getting things done faster possibly means money saved by the client in the least it means that you are working with language you more comfortable in meaning faster development debugging and refactoring time there will be less time spent looking up documentation on what function to use to find the length of string etc
QA
how to sell python to client boss person with lots of cash when asked to create system xyz and you ask to do it in python over php or ruby what are the main features you can mention when they require you to explain it
it is one of the preferred languages over at google it is several years ahead of ruby in terms of maturity what ever that really means but managers like that since it is prefered by google you can also run it on the google app engine mircosoft is also embracing python and will have of ironpython coming out shortly they are working on ruby implementation as well but the python version is way ahead and is actually ready for primetime that give you the possibility for easy integration with net code as well as being able to write client side rias in python when silverlight ships
QA
how do validate xml against dtd file in python need to validate an xml string and not file against dtd description file how can that be done in python
another good option is lxml validation which find quite pleasant to use simple example taken from the lxml site from stringio import stringio from lxml import etree dtd etree dtd stringio element foo empty root etree xml foo print dtd validate root true root etree xml foo bar foo print dtd validate root false print dtd error log filter from errors string error valid dtd not empty element foo was declared empty this one has content
QA
how can create directly executable cross platform gui app using python python works on multiple platforms and can be used for desktop and web applications thus conclude that there is some way to compile it into an executable for mac windows and linux the problem being have no idea where to start or how to write gui with it can anybody she would some light on this and point me in the right direction please
for the gui itself pyqt is pretty much the reference another way to develop rapid user interface is to write web app have it run locally and display the app in the browser plus if you go for the tkinter option suggested by lubos hasko you may want to try portablepy to have your app run on windows environment without python
QA
does anyone have experience creating shared library in matlab researcher has created small simulation in matlab and we want to make it accessible to others my plan is to take the simulation clean up few things and turn it into set of functions then plan to compile it into library and use swig to create python wrapper at that point should be able to call the simulation from small django app at least hope so do have the right plan has anyone else done something similar can you let me know if there are some serious pitfalls am not aware of at the moment
perhaps try ctypes instead of swig if it has been included as part of python then it must be good
QA
prototyping with python code before compiling have been mulling over writing peak fitting library for while know python fairly well and plan on implementing everything in python to begin with but envisage that may have to re implement some core routines in compiled language eventually iirc one of python original remits was as prototyping language however python is pretty liberal in allowing functions functors objects to be passed to functions and methods whereas suspect the same is not true of say or fortran what should know about designing functions classes which envisage will have to interface into the compiled language and how much of these potential problems are dealt with by libraries such as ctypes bgen swig boost python cython or python sip for this particular use case fitting library imagine allowing users to define mathematical functions guassian lorentzian etc as python functions which can then to be passed an interpreted by the compiled code fitting library passing and returning arrays is also essential
in my experience there are two easy ways to call into code from python code there are other approaches all of which are more annoying and or verbose the first and easiest is to compile bunch of code as separate shared library and then call functions in that library using ctypes unfortunately passing anything other than basic data types is non trivial the second easiest way is to write python module in and then call functions in that module you can pass anything you want to these functions without having to jump through any hoops and it is easy to call python functions or methods from these functions as described here https docs python org extending extending html calling python functions from do not have enough experience with swig to offer intelligent commentary and while it is possible to do things like pass custom python objects to functions through ctypes or to define new python classes in these things are annoying and verbose and recommend taking one of the two approaches described above
QA
sanitising user input using python what is the best way to sanitise user input for python based web application is there single function to remove html characters and any other necessary characters combinations to prevent an xss or sql injection attack
if you are using framework like django the framework can easily do this for you using standard filters in fact am pretty sure django automatically does it unless you tell it not to otherwise would recommend using some sort of regex validation before accepting inputs from forms do not think there is silver bullet for your problem but using the re module you should be able to construct what you need
QA
sanitising user input using python what is the best way to sanitise user input for python based web application is there single function to remove html characters and any other necessary characters combinations to prevent an xss or sql injection attack
jeff atwood himself described how stackoverflow com sanitizes user input in non language specific terms on the stack overflow blog http blog stackoverflow com safe html and xss however as justin points out if you use django templates or something similar then they probably sanitize your html output anyway sql injection also should not be concern all of python database libraries mysqldb cx oracle etc always sanitize the parameters you pass these libraries are used by all of python object relational mappers such as django models so you do not need to worry about sanitation there either
QA
create an encrypted zip file in python am creating an zip file with zipfile in python it works ok so far import zipfile os locfile test txt loczip os path splitext locfile zip zip zipfile zipfile loczip zip write locfile zip close but could not find how to encrypt the files in the zip file could use system and call pkzip but suppose there must be more pythonic way am looking for an open source solution
you can use the chilkat library it is commercial but has free evaluation and seems pretty nice here is an example got from here import chilkat demonstrates how to create winzip compatible bit aes strong encrypted zip zip chilkat ckzip zip unlockcomponent anything for day trial zip newzip strongencrypted zip set the encryption property which indicates winzip compatible aes encryption zip put encryption the key length can be or zip put encryptkeylength zip setpassword secret zip appendfiles exampledata true zip writezip
QA
prototyping with python code before compiling have been mulling over writing peak fitting library for while know python fairly well and plan on implementing everything in python to begin with but envisage that may have to re implement some core routines in compiled language eventually iirc one of python original remits was as prototyping language however python is pretty liberal in allowing functions functors objects to be passed to functions and methods whereas suspect the same is not true of say or fortran what should know about designing functions classes which envisage will have to interface into the compiled language and how much of these potential problems are dealt with by libraries such as ctypes bgen swig boost python cython or python sip for this particular use case fitting library imagine allowing users to define mathematical functions guassian lorentzian etc as python functions which can then to be passed an interpreted by the compiled code fitting library passing and returning arrays is also essential
the best way to plan for an eventual transition to compiled code is to write the performance sensitive portions as module of simple functions in functional style stateless and without side effects which accept and return basic data types this will provide one to one mapping from your python prototype code to the eventual compiled code and will let you use ctypes easily and avoid whole bunch of headaches for peak fitting you will almost certainly need to use arrays which will complicate things little but is still very doable with ctypes if you really want to use more complicated data structures or modify the passed arguments swig or python standard extension interface will let you do what you want but with some amount of hassle for what you are doing you may also want to check out numpy which might do some of the work you would want to push to as well as offering some additional help in moving data back and forth between python and
QA
what is the best way to distribute python command line tools my current setup py script works okay but it installs tvnamer py the tool as tvnamer py into site packages or somewhere similar can make setup py install tvnamer py as tvnamer and or is there better way of installing command line applications
try the entry points console scripts parameter in the setup call as described in the setuptools docs this should do what think you want to reproduce here from setuptools import setup setup other arguments here entry points console scripts foo package module func bar othermodule somefunc
QA
build basic python iterator how would one create an iterative function or iterator object in python
first of all the itertools module is incredibly useful for all sorts of cases in which an iterator would be useful but here is all you need to create an iterator in python yield is not that cool yield can be used to replace normal return in function it returns the object just the same but instead of destroying state and exiting it saves state for when you want to execute the next iteration here is an example of it in action pulled directly from the itertools function list def count while true yield as stated in the functions description it is the count function from the itertools module it produces an iterator that returns consecutive integers starting with generator expressions are whole other can of worms awesome worms they may be used in place of list comprehension to save memory list comprehensions create list in memory that is destroyed after use if not assigned to variable but generator expressions can create generator object which is fancy way of saying iterator here is an example of generator expression definition gen for in xrange this is very similar to our iterator definition above except the full range is predetermined to be between and just found xrange suprised had not seen it before and added it to the above example xrange is an iterable version of range which has the advantage of not prebuilding the list it would be very useful if you had giant corpus of data to iterate over and only had so much memory to do it in
QA
transpose unzip function in python inverse of zip have list of item tuples and would like to convert them to lists where the first contains the first item in each tuple and the second list holds the second item for example original would and want to become result would is there builtin function that does that
zip is its own inverse provided you use the special operator zip would would the way this works is by calling zip with the arguments zip would except the arguments are passed to zip directly after being converted to tuple so there is no need to worry about the number of arguments getting too big
QA
how to check set of files conform to naming scheme have bunch of files tv episodes although that is fairly arbitrary that want to check match specific naming organisation scheme currently have three arrays of regex one for valid filenames one for files missing an episode name and one for valid paths then loop though each valid filename regex if it matches append it to valid dict if not do the same with the missing ep name regexs if it matches this append it to an invalid dict with an error code missing epsiode name if it matches neither it gets added to invalid with the malformed name error code the current code can be found here want to add rule that checks for the presence of folder jpg file in each directory but to add this would make the code substantially more messy in it is current state how could write this system in more expandable way the rules it needs to check would be file is in the format show name episode name avi or show name xspecial special name avi or show name xextra extra name avi if filename is in the format show name avi display it missing episode name section of the output the path should be in the format show name season the file avi where season should be the correct season number in the filename each show name season folder should contain folder jpg any ideas while am trying to check tv episodes this concept code should be able to apply to many things the only thought had was list of dicts in the format checker name valid files type file function check valid runs check valid on all files status if it returns true this is the status the file gets
maybe you should take the approach of defaulting to the filename is correct and work from there to disprove that statement with the fact that you only allow filenames with show name season number episode number and episode name you know for certain that these items should be separated by dash so you have to have of those for filename to be correct if that checks out you can use your code to check that the show name matches the show name as seen in the parent parent folder case insensitive assume the season number matches the parents folder numeric value with or without an extra prepended if however you do not see the correct amount of dashes you instantly know that there is something wrong and stop before the rest of the tests etc and separately you can check if the file folder jpg exists and take the necessary actions or do that first and filter that file from the rest of the files in that folder
QA
introducing python the company used to work with has two developers working fulltime and handful of freelancers they are in the process of hiring new lead developer to try to bring order and management to the development but currently one of the developers has seen the light of django the company has only developed in php to date while the other developer is concerned that introducing new language python is bad idea right now how should they approach introducing this new technology obviously with only one of the developers actually knowing python there will be no redundancy when that dev is away or leaves the company should they bother to introduce python or should they look for php only solutions until such time when the team actually have more than one pythonion without team leader the decisions are having to fall to them
well python is high level language its not hard to learn and if the guys already have programming knowledge it should be much easier to learn like django think it should be nice try to use django
QA
introducing python the company used to work with has two developers working fulltime and handful of freelancers they are in the process of hiring new lead developer to try to bring order and management to the development but currently one of the developers has seen the light of django the company has only developed in php to date while the other developer is concerned that introducing new language python is bad idea right now how should they approach introducing this new technology obviously with only one of the developers actually knowing python there will be no redundancy when that dev is away or leaves the company should they bother to introduce python or should they look for php only solutions until such time when the team actually have more than one pythonion without team leader the decisions are having to fall to them
if the mandate of the new lead is to put the house in order the current situation should likely be simplified as much as possible prior if had to bring things to order would not want to have to manage an ongoing language conversion project on top of everything else or at least would like some choice when initiating the project when making your recommendation did you think about the additional managerial complexity that coming into the middle of conversion would entail
QA
introducing python the company used to work with has two developers working fulltime and handful of freelancers they are in the process of hiring new lead developer to try to bring order and management to the development but currently one of the developers has seen the light of django the company has only developed in php to date while the other developer is concerned that introducing new language python is bad idea right now how should they approach introducing this new technology obviously with only one of the developers actually knowing python there will be no redundancy when that dev is away or leaves the company should they bother to introduce python or should they look for php only solutions until such time when the team actually have more than one pythonion without team leader the decisions are having to fall to them
do not think it is matter of programming language as such what is the proficiency level of php in the team you are talking about are they doing spaghetti code or using some structured framework like zend if this is the first case then absolutely understand the guy interest in python and django it this is the latter it is just hype
QA
introducing python the company used to work with has two developers working fulltime and handful of freelancers they are in the process of hiring new lead developer to try to bring order and management to the development but currently one of the developers has seen the light of django the company has only developed in php to date while the other developer is concerned that introducing new language python is bad idea right now how should they approach introducing this new technology obviously with only one of the developers actually knowing python there will be no redundancy when that dev is away or leaves the company should they bother to introduce python or should they look for php only solutions until such time when the team actually have more than one pythonion without team leader the decisions are having to fall to them
darkdog using new language in production code is about more than easy syntax and high level capability you want to be familiar with core apis and feel like you can fix something through logic instead of having to comb through the documentation am not saying transitioning to python would be bad idea for this company but am with john keep things simple during the transition the new lead will appreciate having say in such decisions if you would really really really like to introduce python consider writing some extensions or utilities in straight up python or in the framework you will not be upsetting your core initiatives so it will be low no risk opportunity to prove the merits of switch
QA
introducing python the company used to work with has two developers working fulltime and handful of freelancers they are in the process of hiring new lead developer to try to bring order and management to the development but currently one of the developers has seen the light of django the company has only developed in php to date while the other developer is concerned that introducing new language python is bad idea right now how should they approach introducing this new technology obviously with only one of the developers actually knowing python there will be no redundancy when that dev is away or leaves the company should they bother to introduce python or should they look for php only solutions until such time when the team actually have more than one pythonion without team leader the decisions are having to fall to them
think the language itself is not an issue here as python is really nice high level language with good and easy to find thorough documentation from what have seen the django framework is also great tooklit for web development giving much the same developer performance boost rails is touted to give the real issue is at the maintenance and management level how will this move fragment the maintenance between php and python code is there need to migrate existing code from one platform to another what problems will adopting python and django solve that you have in your current development workflow and frameworks etc
QA
introducing python the company used to work with has two developers working fulltime and handful of freelancers they are in the process of hiring new lead developer to try to bring order and management to the development but currently one of the developers has seen the light of django the company has only developed in php to date while the other developer is concerned that introducing new language python is bad idea right now how should they approach introducing this new technology obviously with only one of the developers actually knowing python there will be no redundancy when that dev is away or leaves the company should they bother to introduce python or should they look for php only solutions until such time when the team actually have more than one pythonion without team leader the decisions are having to fall to them
recently introduced python to my company which does consulting work for the post office did this by waiting until there was project for which would be the only programmer then getting permission to do this new project in python then did another small project in python with similarly impressive results in addition used python for all of my small throwaway assignments can you parse the stats in these files into csv file organized by date and site etc and had quick turnaround time on all of them also evangelized python bit went out of my way to not be obnoxious about it but would occasionally describe why liked it so much talked about the personal projects use it for in my free time and why it is awesome for me etc eventually we started another project and convinced everyone to use python for it took care to point everyone to lot of documentation including the specific webpages relating to what they were working on and every time they had question would explain how to do things properly by explaining the pythonic approach to things etc this has worked really well however this might be somewhat different than what you are describing in my case started with moderately small projects and python is only being used for new projects also none of my co workers were really perl or php gurus they all knew those languages and had been using them for awhile but it did not take much effort for them to become more productive in python than they would been before so if you are talking about new projects with people who currently use php but are not super experts and do not love that language then think switching to python is no brainer however if you are talking about working with large existing php code base with lot of very experienced php programmers who are happy with their current setup then switching languages is probably not good idea you are probably somewhere in between so you will have to weigh the tradeoffs hopefully my answer will help you do that
QA
introducing python the company used to work with has two developers working fulltime and handful of freelancers they are in the process of hiring new lead developer to try to bring order and management to the development but currently one of the developers has seen the light of django the company has only developed in php to date while the other developer is concerned that introducing new language python is bad idea right now how should they approach introducing this new technology obviously with only one of the developers actually knowing python there will be no redundancy when that dev is away or leaves the company should they bother to introduce python or should they look for php only solutions until such time when the team actually have more than one pythonion without team leader the decisions are having to fall to them
love python and django and use both to develop the our core webapps that said it is hard to make business case for switching at this point specifically any new platform is risky compared to staying with the tried and true you will have the developer fragmentation you mentioned it is far easier to find php programmers than python programmers moreover as other posters have mention if the issue is more with spaghetti code than php itself there are plenty of nice php frameworks that could be used to refactor the code that said if this developer is excited about python stopping them outright is probably demoralizing my suggestion would be to encourage them to develop in python but not the mission critical parts of the app instead they could write some utility scripts some small internal application that needs doing etc in conclusion do not recommend switching from php but do recommend accommodating the developer interest in some way at work
QA
introducing python the company used to work with has two developers working fulltime and handful of freelancers they are in the process of hiring new lead developer to try to bring order and management to the development but currently one of the developers has seen the light of django the company has only developed in php to date while the other developer is concerned that introducing new language python is bad idea right now how should they approach introducing this new technology obviously with only one of the developers actually knowing python there will be no redundancy when that dev is away or leaves the company should they bother to introduce python or should they look for php only solutions until such time when the team actually have more than one pythonion without team leader the decisions are having to fall to them
it is really all about schedules to me the break should be with specific project if you decide your direction is django then start new projects with that before you start new project with new language framework either make sure that you have scheduled time to get up to speed in this new direction or get up to speed before using on new projects would avoid going with tool of the month make sure you want it to be your direction and commit some time resources to learning enough to make good decision
QA
what is the best way to grab parse command line arguments passed to python script what is the easiest tersest and most flexible method or library for parsing python command line arguments
use optparse which comes with the standard library for example usr bin env python import optparse def main optparse optionparser add option person default world options arguments parse args print hello options person if name main main source using python to create unix command line tools however as of python optparse is deprecated see why use argparse rather than optparse
QA
what is the best way to grab parse command line arguments passed to python script what is the easiest tersest and most flexible method or library for parsing python command line arguments
pretty much everybody is using getopt here is the example code for the doc import getopt sys def main try opts args getopt getopt sys argv ho help output except getopt getopterror print help information and exit usage sys exit output none verbose false for in opts if verbose true if in help usage sys exit if in output output so in word here is how it works you have got two types of options those who are receiving arguments and those who are just like switches sys argv is pretty much your char argv in like in you skip the first element which is the name of your program and parse only the arguments sys argv getopt getopt will parse it according to the rule you give in argument ho here describes the short arguments oneletter the means that accepts one argument finally help output describes long arguments morethanoneletter the after output once again means that output accepts one arguments the result is list of couple option argument if an option does not accept any argument like help here the arg part is an empty string you then usually want to loop on this list and test the option name as in the example hope this helped you
QA
what is the best way to grab parse command line arguments passed to python script what is the easiest tersest and most flexible method or library for parsing python command line arguments
just in case you might need to this may help if you need to grab unicode arguments on win xp etc from ctypes import def wmain argc argv print argc for in argv print return def startup size int ptr windll shell commandlinetoargvw windll kernel getcommandlinew byref size ref wchar size value raw ref from address ptr args arg for arg in raw windll kernel localfree ptr exit wmain len args args startup
QA
what is the best way to grab parse command line arguments passed to python script what is the easiest tersest and most flexible method or library for parsing python command line arguments
prefer optparse to getopt it is very declarative you tell it the names of the options and the effects they should have setting boolean field and it hands you back dictionary populated according to your specifications http docs python org lib module optparse html
QA
find broken symlinks with python if call os stat on broken symlink python throws an oserror exception this makes it useful for finding them however there are few other reasons that os stat might throw similar exception is there more precise way of detecting broken symlinks with python under linux
can mention testing for hardlinks without python bin test has the file ef file condition that is true when files share an inode therefore something like find type exec test ef path to file print works for hard link testing to specific file which brings me to reading man test and the mentions of and which both work on one file and return true if that file is symbolic link however that does not tell you if the target is missing did find that head file would return an exit code of if the file can be opened and if it cannot which in the case of symbolic link to regular file works as test for whether it is target can be read
QA
find broken symlinks with python if call os stat on broken symlink python throws an oserror exception this makes it useful for finding them however there are few other reasons that os stat might throw similar exception is there more precise way of detecting broken symlinks with python under linux
am not python guy but it looks like os readlink the logic would use in perl is to use readlink to find the target and the use stat to test to see if the target exists edit banged out some perl that demos readlink believe perl stat and readlink and python os stat and os readlink are both wrappers for the system calls so this should translate reasonable well as proof of concept code wembley home jj swap cat my shift while my readlink print if print does not exist wembley home jj swap ls grep lrwxrwxrwx jj users aug link non existant file lrwxrwxrwx root users oct mm systems mm rewrite lrwxrwxrwx jj users aug mmm mm wembley home jj swap perl mm mm systems mm rewrite wembley home jj swap perl mmm mmm mm mm systems mm rewrite wembley home jj swap perl link link non existant file non existant file does not exist wembley home jj swap
QA
find broken symlinks with python if call os stat on broken symlink python throws an oserror exception this makes it useful for finding them however there are few other reasons that os stat might throw similar exception is there more precise way of detecting broken symlinks with python under linux
os lstat may be helpful if lstat succeeds and stat fails then it is probably broken link
QA
find broken symlinks with python if call os stat on broken symlink python throws an oserror exception this makes it useful for finding them however there are few other reasons that os stat might throw similar exception is there more precise way of detecting broken symlinks with python under linux
os path you may try using realpath to get what the symlink points to then trying to determine if it is valid file using is file am not able to try that out at the moment so you will have to play around with it and see what you get
QA
updating an auto now datetimefield in parent model django have got two models message and attachment each attachment is attached to specific message using foreignkey on the attachment model both models have an auto now datetimefield called updated am trying to make it so that when any attachment is saved it also sets the updated field on the associated message to now here is my code def save self super attachment self save self message updated self updated will this work and if you can explain it to me why if not how would accomplish this
you would also need to then save the message then it that should work
QA
how to sell python to client boss person with lots of cash when asked to create system xyz and you ask to do it in python over php or ruby what are the main features you can mention when they require you to explain it
the best sell of python have ever seen was by manager in our group who had young daughter he used quote attributed to einstein if you cannot explain something to six year old you really do not understand it yourself the next few slides of his presentation demonstrated how he was able to teach his young daughter some basic python in less than minutes with examples of the code she wrote and an explanation of what it did he ended the presentation with picture of his daughter and her quote programming is fun would focus on python user friendliness and wealth of libraries and frameworks there are also lot of little libraries that you might not get in other languages and would have to write yourself how developer writes python good luck
QA
how to check set of files conform to naming scheme have bunch of files tv episodes although that is fairly arbitrary that want to check match specific naming organisation scheme currently have three arrays of regex one for valid filenames one for files missing an episode name and one for valid paths then loop though each valid filename regex if it matches append it to valid dict if not do the same with the missing ep name regexs if it matches this append it to an invalid dict with an error code missing epsiode name if it matches neither it gets added to invalid with the malformed name error code the current code can be found here want to add rule that checks for the presence of folder jpg file in each directory but to add this would make the code substantially more messy in it is current state how could write this system in more expandable way the rules it needs to check would be file is in the format show name episode name avi or show name xspecial special name avi or show name xextra extra name avi if filename is in the format show name avi display it missing episode name section of the output the path should be in the format show name season the file avi where season should be the correct season number in the filename each show name season folder should contain folder jpg any ideas while am trying to check tv episodes this concept code should be able to apply to many things the only thought had was list of dicts in the format checker name valid files type file function check valid runs check valid on all files status if it returns true this is the status the file gets
want to add rule that checks for the presence of folder jpg file in each directory but to add this would make the code substantially more messy in it is current state this does not look bad in fact your current code does it very nicely and sven mentioned good way to do it as well get list of all the files check for required files you would just have have add to your dictionary list of required files checker required file list for required as far as there being better extensible way to do this am not exactly sure could only really think of way to possibly drop the multiple regular expressions and build off of sven idea for using delimiter so my strategy would be defining dictionary as follows and am sorry do not know python syntax and am tad to lazy to look it up but it should make sense the regex is shorthand for regex check dict delim parts show name episode name episode number patterns valid name valid episode name valid number required list of files ignored hidden txt start dir path to dir to test split the filename based on the delimiter check each of the parts because its an ordered list you can determine what parts are missing and if section does not match any pattern it is malformed here the parts and patterns have to ratio two arrays instead of dictionary enforces the order ignored and required files can be listed the and files should probably be ignored automatically the user should be allowed to input globs which can be she will expanded am thinking here of svn ignore properties but globbing is natural for listing files here start dir would be default to the current directory but if you wanted single file to run automated testing of bunch of directories this would be useful the real loose end here is the path template and along the same lines what path is required for valid files really could not come up with solid idea without writing one large regular expression and taking groups from it to build template it felt lot like writing textmate language grammar but that starts to stray on the ease of use the real problem was that the path template was not composed of parts which makes sense but adds complexity is this strategy in tune with what you were thinking of
QA
specifying mysql enum in django model how do go about specifying and using an enum in django model
from the django documentation maybechoice yes no you unknown and you define charfield in your model married models charfield max length choices maybechoice you can do the same with integer fields if you do not like to have letters in your db in that case rewrite your choices maybechoice yes no unknown
QA
why java and python garbage collection methods are different python uses the reference count method to handle object life time so an object that has no more use will be immediately destroyed but in java the gc garbage collector destroys objects which are no longer used at specific time why does java choose this strategy and what is the benefit from this is this better than the python approach
think the article java theory and practice brief history of garbage collection from ibm should help explain some of the questions you have
QA
why java and python garbage collection methods are different python uses the reference count method to handle object life time so an object that has no more use will be immediately destroyed but in java the gc garbage collector destroys objects which are no longer used at specific time why does java choose this strategy and what is the benefit from this is this better than the python approach
there are drawbacks of using reference counting one of the most mentioned is circular references suppose references references and references if were to drop its reference to both and will still have reference count of and will not be deleted with traditional reference counting cpython reference counting is not part of python itself but part of the implementation thereof catches circular references with separate garbage collection routine that it runs periodically another drawback reference counting can make execution slower each time an object is referenced and dereferenced the interpreter vm must check to see if the count has gone down to and then deallocate if it did garbage collection does not need to do this also garbage collection can be done in separate thread though it can be bit tricky on machines with lots of ram and for processes that use memory only slowly you might not want to be doing gc at all reference counting would be bit of drawback there in terms of performance
QA
why does this python date time conversion seem wrong import time time strptime time mktime seconds in day time mktime should return the number of seconds since the epoch since am giving it time at midnight and the epoch is at midnight should not the result be evenly divisible by the number of seconds in day
mktime mktime tuple floating point number convert time tuple in local time to seconds since the epoch local time fancy that the time tuple the other representation is tuple of integers giving local time the tuple items are year four digits month day hours minutes seconds weekday monday is julian day day in the year dst daylight savings time flag or if the dst flag is the time is given in the regular time zone if it is the time is given in the dst time zone if it is mktime should guess based on the date and time incidentally we seem to be hours apart time mktime
QA
why does this python date time conversion seem wrong import time time strptime time mktime seconds in day time mktime should return the number of seconds since the epoch since am giving it time at midnight and the epoch is at midnight should not the result be evenly divisible by the number of seconds in day
interesting do not know but did try this now time mktime tomorrow time mktime tomorrow now which is what you expected my guess maybe some time correction was done since the epoch this could be only few seconds something like leap year think heard something like this before but cannot remember exactly how and when it is done
QA
why does this python date time conversion seem wrong import time time strptime time mktime seconds in day time mktime should return the number of seconds since the epoch since am giving it time at midnight and the epoch is at midnight should not the result be evenly divisible by the number of seconds in day
short answer because of timezones the epoch is in utc for example am on ist irish stsandard time or gmt time mktime is relative to my timezone so on my system this refers to time mktime because you got the result that would suggest that you are hours behind me have look at the time gmtime function which works off utc
QA
why does this python date time conversion seem wrong import time time strptime time mktime seconds in day time mktime should return the number of seconds since the epoch since am giving it time at midnight and the epoch is at midnight should not the result be evenly divisible by the number of seconds in day
phil answer really solved it but will elaborate little more since the epoch is in utc if want to compare other times to the epoch need to interpret them as utc as well calendar timegm by converting the time tuple to timestamp treating is as utc time get number which is evenly divisible by the number of seconds in day can use this to convert date to days from the epoch representation which is what am ultimately after
QA
unicode vs utf confusion in python django stumbled over this passage in the django tutorial django models have default str method that calls unicode and converts the result to utf bytestring this means that unicode will return unicode string and str will return normal string with characters encoded as utf now am confused because afaik unicode is not any particular representation so what is unicode string in python does that mean ucs googling turned up this python unicode tutorial which boldly states unicode is two byte encoding which covers all of the world common writing systems which is plain wrong or is it have been confused many times by character set and encoding issues but here am quite sure that the documentation am reading is confused does anybody know what is going on in python when it gives me unicode string
python stores unicode as utf str will return the utf representation of the utf string
QA
unicode vs utf confusion in python django stumbled over this passage in the django tutorial django models have default str method that calls unicode and converts the result to utf bytestring this means that unicode will return unicode string and str will return normal string with characters encoded as utf now am confused because afaik unicode is not any particular representation so what is unicode string in python does that mean ucs googling turned up this python unicode tutorial which boldly states unicode is two byte encoding which covers all of the world common writing systems which is plain wrong or is it have been confused many times by character set and encoding issues but here am quite sure that the documentation am reading is confused does anybody know what is going on in python when it gives me unicode string
meanwhile did refined research to verify what the internal representation in python is and also what its limits are the truth about unicode in python is very good article which cites directly from the python developers apparently internal representation is either ucs or ucs depending on compile time switch so jon it is not utf but your answer put me on the right track anyway thanks
QA
why java and python garbage collection methods are different python uses the reference count method to handle object life time so an object that has no more use will be immediately destroyed but in java the gc garbage collector destroys objects which are no longer used at specific time why does java choose this strategy and what is the benefit from this is this better than the python approach
darren thomas gives good answer however one big difference between the java and python approaches is that with reference counting in the common case no circular references objects are cleaned up immediately rather than at some indeterminate later date for example can write sloppy non portable code in cpython such as def parse some attrs fname return open fname read split and the file descriptor for that file opened will be cleaned up immediately because as soon as the reference to the open file goes away the file is garbage collected and the file descriptor is freed of course if run jython or ironpython or possibly pypy then the garbage collector will not necessarily run until much later possibly will run out of file descriptors first and my program will crash so you should be writing code that looks like def parse some attrs fname with open fname as return read split but sometimes people like to rely on reference counting to always free up their resources because it can sometimes make your code little shorter would say that the best garbage collector is the one with the best performance which currently seems to be the java style generational garbage collectors that can run in separate thread and has all these crazy optimizations etc the differences to how you write your code should be negligible and ideally non existent
QA
adding method to an existing object instance have read that it is possible to add method to an existing object not in the class definition in python think this is called monkey patching or in some cases duck punching understand that it is not always good decision to do so but how might one do this update est that looks like good answer john downey tried it but it appears that it ends up being not true method your example defines the new patch function with an argument of self but if you write actual code that way the now patched class method asks for an argument named self it does not automagically recognize it as the object to which it is supposed to bind which is what would happen if defined within the class definition meaning you have to call class patch obj instead of just class patch if you want the same functionality as true method it looks like python is not really treating it as method but more just as variable which happens to be function and as such is callable is there any way to attach an actual method to class oh and ryan that is not exactly what was looking for it is not builtin functionality but it is quite cool nonetheless
what jason pratt posted is correct class test object def self pass def self pass test type type function type test type instancemethod type test type instancemethod as you can see python does not consider any different than in python all methods are just variables that happen to be functions
QA
format numbers to strings in python need to find out how to format numbers as strings my code is here return str hours str minutes str seconds ampm hours and minutes are integers and seconds is float the str function will convert all of these numbers to the tenths place so instead of my string outputting pm it would display something like pm bottom line what library function do need to do this for me
formatting in python is done via the string formatting operator hours minutes seconds edit there is also strftime
QA
format numbers to strings in python need to find out how to format numbers as strings my code is here return str hours str minutes str seconds ampm hours and minutes are integers and seconds is float the str function will convert all of these numbers to the tenths place so instead of my string outputting pm it would display something like pm bottom line what library function do need to do this for me
you can use style string formatting hours minutes seconds see here especially https web archive org web http diveintopython ep io strings html
QA
how do download file over http using python have small utility that use to download mp from website on schedule and then builds updates podcast xml file which have obviously added to itunes the text processing that creates updates the xml file is written in python use wget inside windows bat file to download the actual mp however would prefer to have the entire utility written in python though struggled though to find way to actually down load the file in python thus why resorted to wget so how do download the file using python
in python use urllib which comes with the standard library import urllib response urllib urlopen http www example com html response read this is the most basic way to use the library minus any error handling you can also do more complex stuff such as changing headers the documentation can be found here
QA
how do download file over http using python have small utility that use to download mp from website on schedule and then builds updates podcast xml file which have obviously added to itunes the text processing that creates updates the xml file is written in python use wget inside windows bat file to download the actual mp however would prefer to have the entire utility written in python though struggled though to find way to actually down load the file in python thus why resorted to wget so how do download the file using python
import urllib mp file urllib urlopen http www example com songs mp mp with open test mp wb as output output write mp file read the wb in open test mp wb opens file and erases any existing file in binary mode so you can save data with it instead of just text
QA
how do download file over http using python have small utility that use to download mp from website on schedule and then builds updates podcast xml file which have obviously added to itunes the text processing that creates updates the xml file is written in python use wget inside windows bat file to download the actual mp however would prefer to have the entire utility written in python though struggled though to find way to actually down load the file in python thus why resorted to wget so how do download the file using python
agree with corey urllib is more complete than urllib and should likely be the module used if you want to do more complex things but to make the answers more complete urllib is simpler module if you want just the basics import urllib response urllib urlopen http www example com sound mp mp response read will work fine or if you do not want to deal with the response object you can call read directly import urllib mp urllib urlopen http www example com sound mp read
QA
how do download file over http using python have small utility that use to download mp from website on schedule and then builds updates podcast xml file which have obviously added to itunes the text processing that creates updates the xml file is written in python use wget inside windows bat file to download the actual mp however would prefer to have the entire utility written in python though struggled though to find way to actually down load the file in python thus why resorted to wget so how do download the file using python
one more using urlretrieve import urllib urllib urlretrieve http www example com songs mp mp mp mp for python use import urllib request and urllib request urlretrieve yet another one with progressbar import urllib url http download thinkbroadband com mb zip file name url split you urllib urlopen url open file name wb meta you info file size int meta getheaders content length print downloading bytes file name file size file size dl block sz while true buffer you read block sz if not buffer break file size dl len buffer write buffer status file size dl file size dl file size status status chr len status print status close
QA
how do content discovery engines like zemanta and open calais work was wondering how as semantic service like open calais figures out the names of companies or people tech concepts keywords etc from piece of text is it because they have large database that they match the text against how would service like zemanta know what images to suggest to piece of text for instance
open calais probably use language parsing technology and language statics to guess which words or phrases are names places companies etc then it is just another step to do some kind of search for those entities and return meta data zementa probably does something similar but matches the phrases against meta data attached to images in order to acquire related results it certainly is not easy
QA
what is the best way to duplicate fork in windows how do implement some logic that will allow me to reproduce on windows the functionality that have on linux with the fork system call using python am specifically trying to execute method on the sapi com component while continuing the other logic in the main thread without blocking or waiting
possibly version of spawn for python http en wikipedia org wiki spawn operating system
QA
what is the best way to duplicate fork in windows how do implement some logic that will allow me to reproduce on windows the functionality that have on linux with the fork system call using python am specifically trying to execute method on the sapi com component while continuing the other logic in the main thread without blocking or waiting
have look at the process management functions in the os module there are function for starting new processes in many different ways both synchronously and asynchronously should note also that windows does not provide functionality that is exactly like fork on other systems to do multiprocessing on windows you will need to use the threading module
QA
what is the best way to duplicate fork in windows how do implement some logic that will allow me to reproduce on windows the functionality that have on linux with the fork system call using python am specifically trying to execute method on the sapi com component while continuing the other logic in the main thread without blocking or waiting
in addition to the process management code in the os module that greg pointed out you should also take look at the threading module https docs python org library threading html from threading import thread def separate computations print sum for in range really expensive multiplication thread target separate compuations args start print am continuing while that other function runs in another thread
QA
why java and python garbage collection methods are different python uses the reference count method to handle object life time so an object that has no more use will be immediately destroyed but in java the gc garbage collector destroys objects which are no longer used at specific time why does java choose this strategy and what is the benefit from this is this better than the python approach
the latest sun java vm actually have multiple gc algorithms which you can tweak the java vm specifications intentionally omitted specifying actual gc behaviour to allow different and multiple gc algorithms for different vms for example for all the people who dislike the stop the world approach of the default sun java vm gc behaviour there are vm such as ibm websphere real time which allows real time application to run on java since the java vm spec is publicly available there is theoretically nothing stopping anyone from implementing java vm that uses cpython gc algorithm
QA
can you explain closures as they relate to python have been reading lot about closures and think understand them but without clouding the picture for myself and others am hoping someone can explain closures as succinctly and clearly as possible am looking for simple explanation that might help me understand where and why would want to use them
to be honest understand closures perfectly well except have never been clear about what exactly is the thing which is the closure and what is so closure about it recommend you give up looking for any logic behind the choice of term anyway here is my explanation def foo def bar print return bar bar foo bar print key idea here is that the function object returned from foo retains hook to the local var even though has gone out of scope and should be defunct this hook is to the var itself not just the value that var had at the time so when bar is called it prints not also be clear that python has limited closure there is no way can modify inside bar because writing bla would declare local in bar not assign to of foo this is side effect of python assignment declaration to get around this python introduces the nonlocal keyword def foo def bar print def ack nonlocal return bar ack bar ack foo ack modify of the call to foo bar print
QA
how can graph the lines of code history for git repo basically want to get the number of lines of code in the repository after each commit the only really crappy ways have found is to use git filter branch to run wc and script that run git reset hard on each commit then ran wc to make it bit clearer when the tool is run it would output the lines of code of the very first commit then the second and so on this is what want the tool to output as an example me something gitsloc branch master have played around with the ruby git library but the closest found was using the lines method on different which seems like it should give the added lines but does not it returns when you delete lines for example require rubygems require git total git open working dir users dbr desktop code projects tvdb api last nil log each do cur different different last cur total total different lines puts total last cur end
the first thing that jumps to mind is the possibility of your git history having nonlinear history you might have difficulty determining sensible sequence of commits having said that it seems like you could keep log of commit ids and the corresponding lines of code in that commit in post commit hook starting from the head revision work backwards branching to multiple parents if necessary until all paths reach commit that you have already seen before that should give you the total lines of code for each commit id does that help any have feeling that have misunderstood something about your question
QA
python code generator for visual studio had an idea if add python py file to my project and tag the file with custom generator that would execute the python file and treat the output as the result of the code generation ie put it into file that would allow me to do quite lot of code generation as part of the build process does anyone know if such custom generator for visual studio exists
recall that in previous versions of vs there was way to add custom build steps to the build process used that lot to do exactly the kind of automated code generation you describe imagine the custom build step feature is still there in
QA
python code generator for visual studio had an idea if add python py file to my project and tag the file with custom generator that would execute the python file and treat the output as the result of the code generation ie put it into file that would allow me to do quite lot of code generation as part of the build process does anyone know if such custom generator for visual studio exists
do not understand what you are trying to do here are you trying to execute python script that generates file and then compile that with the project or are you trying to compile python script to
QA
python code generator for visual studio had an idea if add python py file to my project and tag the file with custom generator that would execute the python file and treat the output as the result of the code generation ie put it into file that would allow me to do quite lot of code generation as part of the build process does anyone know if such custom generator for visual studio exists
ok see well as far as know there is not any code generator for python there is good introduction on how to roll your own here actually that is quite an under used part of the environment suppose it is so because it needs you to use the ide to compile the project as it would seem only the ide knows about these generators but msbuild ignores them
QA
build basic python iterator how would one create an iterative function or iterator object in python
iterator objects in python conform to the iterator protocol which basically means they provide two methods iter and next the iter returns the iterator object and is implicitly called at the start of loops the next method returns the next value and is implicitly called at each loop increment next raises stopiteration exception when there are no more value to return which is implicitly captured by looping constructs to stop iterating here is simple example of counter class counter def init self low high self current low self high high def iter self return self def next self python def next self if self current self high raise stopiteration else self current return self current for in counter print this will print this is easier to write using generator as covered in previous answer def counter low high current low while current high yield current current for in counter print the printed output will be the same under the hood the generator object supports the iterator protocol and does something roughly similar to the class counter david mertz article iterators and simple generators is pretty good introduction
QA
how to capture python interpreter and or cmd exe output from python script is it possible to capture python interpreter output from python script is it possible to capture windows cmd output from python script if so which librar ies should look into
in which context are you asking are you trying to capture the output from program you start on the command line if so then this is how to execute it somescript py your capture program here and to read the output just read from standard input if on the other hand you are executing that script or cmd exe or similar from within your program and want to wait until the script program has finished and capture all its output then you need to look at the library calls you use to start that external program most likely there is way to ask it to give you some way to read the output and wait for completion
QA
how to capture python interpreter and or cmd exe output from python script is it possible to capture python interpreter output from python script is it possible to capture windows cmd output from python script if so which librar ies should look into
you want subprocess look specifically at popen in and communicate in
QA
how to capture python interpreter and or cmd exe output from python script is it possible to capture python interpreter output from python script is it possible to capture windows cmd output from python script if so which librar ies should look into
if you are talking about the python interpreter or cmd exe that is the parent of your script then no it is not possible in every posix like system now you are running windows it seems and that might have some quirk do not know about ymmv each process has three streams standard input standard output and standard error bu default when running in console these are directed to the console but redirection is possible using the pipe notation python script py python script py this ties the standard output stream of script to the standard input stream of script standard error still goes to the console in this example see the article on standard streams on wikipedia if you are talking about child process you can launch it from python like so stdin is also an option if you want two way communication import subprocess of course you can open things other than python here process subprocess popen python main py stdout subprocess pipe stderr subprocess pipe process stderr readline process stdout readline process wait see the python subprocess module for information on managing the process for communication the process stdin and process stdout pipes are considered standard file objects for use with pipes reading from standard input as lassevk suggested you would do something like this import sys sys stderr readline sys stdin readline sys stdin and sys stdout are standard file objects as noted above defined in the sys module you might also want to take look at the pipes module reading data with readline as in my example is pretty na ve way of getting data though if the output is not line oriented or indeterministic you probably want to look into polling which unfortunately does not work in windows but am sure there is some alternative out there
QA
format numbers to strings in python need to find out how to format numbers as strings my code is here return str hours str minutes str seconds ampm hours and minutes are integers and seconds is float the str function will convert all of these numbers to the tenths place so instead of my string outputting pm it would display something like pm bottom line what library function do need to do this for me
str in python on an integer will not print any decimal places if you have float that you want to ignore the decimal part then you can use str int floatvalue perhaps the following code will demonstrate str int
QA
what is the best way to duplicate fork in windows how do implement some logic that will allow me to reproduce on windows the functionality that have on linux with the fork system call using python am specifically trying to execute method on the sapi com component while continuing the other logic in the main thread without blocking or waiting
you might also like using the processing module http pypi python org pypi processing it has lot of functionality for writing parallel systems with the same api as the threading module
QA
binary buffer in python in python you can use stringio for file like buffer for character data memory mapped file basically does similar thing for binary data but it requires file that is used as the basis does python have file object that is intended for binary data and is memory only equivalent to java bytearrayoutputstream the use case have is want to create zip file in memory and zipfile requires file like object
look at the struct package https docs python org library struct html it allows you to interpret strings as packed binary data not sure if this will completely answer your question but you can use struct unpack to convert binary data to python objects import struct open filename rb read struct unpack hl int this example the tells to read big endian the reads byte short and the is for byte long you can obviously change these to whatever you need to read out of the binary data
QA
sanitising user input using python what is the best way to sanitise user input for python based web application is there single function to remove html characters and any other necessary characters combinations to prevent an xss or sql injection attack
here is snippet that will remove all tags not on the white list and all tag attributes not on the attribues whitelist so you cannot use onclick it is modified version of http www djangosnippets org snippets with the regex on the attribute values to prevent people from using href javascript and other cases described at http ha ckers org xss html href ja vascript alert hi or href ja vascript alert hi etc as you can see it uses the awesome beautifulsoup library import re from urlparse import urljoin from beautifulsoup import beautifulsoup comment def sanitizehtml value base url none rjs join list javascript rvb join list vbscript re scripts re compile rjs rvb re ignorecase validtags strong you pre br img split validattrs href src width height split urlattrs href src split attributes which should have url soup beautifulsoup value for comment in soup findall text lambda text isinstance text comment get rid of comments comment extract for tag in soup findall true if tag name not in validtags tag hidden true attrs tag attrs tag attrs for attr val in attrs if attr in validattrs val re scripts sub val remove scripts vbs js if attr in urlattrs val urljoin base url val calculate the absolute url tag attrs append attr val return soup rendercontents decode utf as the other posters have said pretty much all python db libraries take care of sql injection so this should pretty much cover you
QA
sanitising user input using python what is the best way to sanitise user input for python based web application is there single function to remove html characters and any other necessary characters combinations to prevent an xss or sql injection attack
do not do web development much any longer but when did did something like so when no parsing is supposed to happen usually just escape the data to not interfere with the database when store it and escape everything read up from the database to not interfere with html when display it cgi escape in python chances are if someone tried to input html characters or stuff they actually wanted that to be displayed as text anyway if they did not well tough in short always escape what can affect the current target for the data when did need some parsing markup or whatever usually tried to keep that language in non intersecting set with html so could still just store it suitably escaped after validating for syntax errors and parse it to html when displaying without having to worry about the data the user put in there interfering with your html see also escaping html
QA
binary buffer in python in python you can use stringio for file like buffer for character data memory mapped file basically does similar thing for binary data but it requires file that is used as the basis does python have file object that is intended for binary data and is memory only equivalent to java bytearrayoutputstream the use case have is want to create zip file in memory and zipfile requires file like object
as long as you do not try to put any unicode data into your stringio and you are careful not to use cstringio you should be fine according to the stringio documentation as long as you keep to either unicode or bits everything works as expected presumably stringio does something special when someone does write you asdf which zipfile does not do to my knowledge anyway import zipfile import stringio stringio stringio zipfile zipfile write test txt close file zip write getvalue close close works just as expected and there is no difference between the file in the resulting archive and the original file if you know of particular case where this approach does not work would be most interested to hear about it
QA
transpose unzip function in python inverse of zip have list of item tuples and would like to convert them to lists where the first contains the first item in each tuple and the second list holds the second item for example original would and want to become result would is there builtin function that does that
you could also do result for in original for in original it should scale better especially if python makes good on not expanding the list comprehensions unless needed incidentally it makes tuple pair of lists rather than list of tuples like zip does if generators instead of actual lists are ok this would do that result for in original for in original the generators do not munch through the list until you ask for each element but on the other hand they do keep references to the original list
QA
cx oracle how do iterate over result set there are several ways to iterate over result set what are the tradeoff of each
there is also the way psyco pg seems to do it from what gather it seems to create dictionary like row proxies to map key lookup into the memory block returned by the query in that case fetching the whole answer and working with similar proxy factory over the rows seems like useful idea come to think of it though it feels more like lua than python also this should be applicable to all pep dbapi interfaces not just oracle or did you mean just fastest using oracle
QA
pygame within pygtk application what is the best way to use pygame sdl within pygtk application am searching for method that allows me to have drawing area in the gtk window and at the same time being able to manage both gtk and sdl events
you may be interested in this message thread looks like they recommend against it
QA
python super class reflection if have python code class pass class pass class pass and have class is there way to iterate through it is super classed and something like pseudocode magicgetsuperclasses type type one solution seems to be inspect module and getclasstree function def magicgetsuperclasses cls return for in inspect getclasstree cls if type type but is this pythonian way to achieve the goal
bases is an array of the super classes so you could implement your hypothetical function like so def magicgetsuperclasses cls return cls bases but imagine it would be easier to just reference cls bases directly in most cases
QA
is there any difference between foo is none and foo none is there any difference between if foo is none pass and if foo none pass the convention that have seen in most python code and the code myself write is the former but recently came across code which uses the latter none is an instance and the only instance iirc of nonetype so it should not matter right are there any circumstances in which it might
is always returns true if it compares the same object instance whereas is ultimately determined by the eq method class foo object def eq self other return true foo none true is none false
QA
is there any difference between foo is none and foo none is there any difference between if foo is none pass and if foo none pass the convention that have seen in most python code and the code myself write is the former but recently came across code which uses the latter none is an instance and the only instance iirc of nonetype so it should not matter right are there any circumstances in which it might
you may want to read this object identity and equivalence the statement is is used for object identity it checks if objects refer to the same instance same address in memory and the statement refers to equality same value