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 t... | 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 t... | 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 t... | 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 t... | 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 ... |
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 su... | 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 sh... |
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 su... | 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... |
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 w... | 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 f... |
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 su... | 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 ridi... |
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 w... | 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 th... |
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 w... | 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 ... |
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 su... | 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 ... | 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 su... | 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 ... |
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 ... | 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 h... |
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 unzip... | 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 unzip... | 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 unzip... | 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 ... |
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 ne... | 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 ne... | 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 ne... | 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 ... | 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... |
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 lo... |
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... |
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... |
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 wit... | 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 py... |
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 a... | 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... | 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... |
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 yo... |
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... |
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 pkz... | 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 enc... |
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... | 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 eventu... |
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 an... |
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 ea... | 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 tho... |
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 ... | 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 ... | 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... |
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 ... | 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 ... |
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 ... | 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... |
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 ... | 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 t... |
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 ... | 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 ... |
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 ... | 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 t... |
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 ... | 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 bef... |
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 i... |
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 ... |
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... |
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 o... |
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... |
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 t... | 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 ba... |
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 ea... | 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 req... |
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 strateg... | 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 strateg... | 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... |
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... |
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... |
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 c... |
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 confus... | 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 confus... | 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... |
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 strateg... | 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 de... |
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... | 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 di... | 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 di... | 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... | 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... | 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... | 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 o... |
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... | 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 m... |
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... | 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 attach... |
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 with... | 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 with... | 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... |
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 with... | 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 compuation... |
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 strateg... | 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 v... |
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 w... | 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 ide... |
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 ru... | 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 h... |
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 proc... | 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 proc... | 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 proc... | 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 generator... |
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 ex... |
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 ... |
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 b... |
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 di... | 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 with... | 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 bytearrayoutpu... | 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... |
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 ... |
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 ... |
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 bytearrayoutpu... | 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 ... |
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... |
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 fee... |
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 ... | 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 o... | 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 o... | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.