prefix
stringclasses 1
value | input_text
stringlengths 19
27.3k
⌀ | target_text
stringlengths 2
24.8k
⌀ |
---|---|---|
QA
|
am looking for pythonic way to insert space before capital letters have got file whose format am altering via python script have several camel cased strings in this file where just want to insert single space before the capital letter so wordwordword becomes word word word my limited regex experience just stalled out on me can someone think of decent regex to do this or better yet is there more pythonic way to do this that am missing
|
perhaps shorter re sub doithinkthisisabetteranswer
|
QA
|
recommended data format for describing the rules of chess am going to be writing chess server and one or more clients for chess and want to describe the rules of chess allowable moves based on game state rules for when game is complete in programming language independant way this is bit tricky since some of the chess rules king castling en passent draws based on or more repeated moves are based not only on the board layout but also on the history of moves would prefer the format to be textual human readable based on standard yaml xml easily parsable in variety of languages but am willing to sacrifice any of these for suitable solution my main question is how can build algorithms of such complexity that operate on such complex state from data format followup queston is can you provide an example of similar problem solved in similar manner that can act as starting point edit in response to request for clarity consider that will have server written in python one client written in and another client written in java would like to avoid specifying the rules for allowable piece movement circumstances for check etc in each place would prefer to specify these rules once in language independant manner
|
what have gathered from the responses so far for chess board data representations see the wikipedia article on chess board representations http en wikipedia org wiki board representation chess for chess move data representations see the wikipedia articles on portable game notation and algebraic chess notation for chess rules representations this must be done using programming language if one wants to reduce the amount of code written in the case where the rules will be implemented in more than one language then there are few options use language where an embedable interpreter exists for the target languages lua python use virtual machine that the common languages can compile to ironpython for jpython for java use background daemon or sub process for the rules with which the target languages can communicate reimplement the rules algorithms in each target language although would have liked declarative syntax that could have been interpreted by mutliple languages to enforce the rules of chess my research has lead me to no likely candidate have suspicion that constraint based programming may be possible route given that solvers exist for many languages but am not sure they would truly fulfill this requirement thanks for all the attention and perhaps in the future an answer will appear
|
QA
|
what are some strategies to write python code that works in cpython jython and ironpython having tries to target two of these environments at the same time can safely say the if you have to use database etc you end up having to write unique code for that environment have you got great way to handle this situation
|
write code for cpython and ironpython but tip should work for jython as well basically write all the platform specific code in separate modules packages and then import the appropriate one based on platform am running on see cdleary comment above this is especially important when it comes to the differences between the sqlite implementations and if you are implementing any gui code
|
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
|
there is simple solution that might work for you write the pygtk stuff and pygame stuff as separate applications then from the pygtk application call the pygame application using os system to call the pygame application if you need to share data between the two then either use database pipes or ipc
|
QA
|
can pickle python dictionary into sqlite text field any gotchas should be aware of can store it in text field or do need to use blob am not overly familiar with either pickle or sqlite so wanted to make sure am barking up the right tree with some of my high level design ideas
|
the other option considering that your requirement is to save dict and then spit it back out for the user viewing pleasure is to use the shelve module which will let you persist any pickleable data to file the python docs are here
|
QA
|
can pickle python dictionary into sqlite text field any gotchas should be aware of can store it in text field or do need to use blob am not overly familiar with either pickle or sqlite so wanted to make sure am barking up the right tree with some of my high level design ideas
|
depending on what you are working on you might want to look into the shove module it does something similar where it auto stores python objects inside sqlite database and all sorts of other options and pretends to be dictionary just like the shelve module
|
QA
|
how can port legacy java ee website to modern scripting language php python django etc want to move legacy java web application ee to scripting language any scripting language in order to improve programming efficiency what is the easiest way to do this are there any automated tools that can convert the bulk of the business logic
|
using an automated tool to port the web application will almost certainly guarantee that future programming efficiency will be minimised not improved good scripting language can help programming efficiency when used by good programmers who understand good coding practices in that language automated tools are usually not designed to output code that is elegent or well written only code that works you will only get an improvement in programming efficiency after you have put in the effort to re implement the web app which due to the time required for the reimplementation may or may not result in an improvement overall
|
QA
|
how can port legacy java ee website to modern scripting language php python django etc want to move legacy java web application ee to scripting language any scripting language in order to improve programming efficiency what is the easiest way to do this are there any automated tools that can convert the bulk of the business logic
|
if you already have large amount of business logic implemented in java then see two possibilities for you the first is to use high level language that runs within the jvm and has web framework such as groovy grails or jruby and rails this allows you to directly leverage all of the business logic you have implemented in java without having to re architect the entire site you should be able to take advantage of the framework improved productivity with respect to the web development and still leverage your existing business logic an alternative approach is to turn your business logic layer into set of services available over standard rpc mechanisim rest soap xml rpc or some other simple xml yaml or json over http protocol see also dwr so that the front end can make these rpc calls to your business logic the first approach using high level language on the jvm is probably less re architecture than the second if your goal is complete migration off of java then either of these approaches allow you to do so in smaller steps you may find that this kind of hybrid is better than whole sale deprecation the jvm has lot of libraries and integrates well into lot of other systems
|
QA
|
is there any way to get python omnicomplete to work with non system modules in vim the only thing can get python omnicomplete to work with are system modules get nothing for help with modules in my site packages or modules that am currently working on
|
just ran across this on python reddit tonight pysmell looks like what you are looking for pysmell is python ide completion helper it tries to statically analyze python source code without executing it and generates information about project structure that ide tools can use
|
QA
|
how can port legacy java ee website to modern scripting language php python django etc want to move legacy java web application ee to scripting language any scripting language in order to improve programming efficiency what is the easiest way to do this are there any automated tools that can convert the bulk of the business logic
|
here is what you have to do first be sure you can walk before you run build something simple possibly tangentially related to your main project do not build piece of the final project and hope it will evolve into the final project this never works out well why you will make dumb mistakes but you cannot delete or rework them because you are supposed to evolve that mistake into the final project next pick framework what second yes second until you actually do something with some scripting languages and frameworks you have no real useful concept of what you are doing once you have built something you now have an informed opinion wait you say to do step had to pick framework true step however contains decisions you are allowed to revoke pick the wrong framework for step has no long term bad effects it was just learning third with your strategic framework and some experience break down your existing site into pieces you can build with your new framework prioritize those pieces from most important to least important do not plan the entire conversion as one massive project it never works it makes big job more complex than necessary we will use django as the example framework you will have templates view functions model definitions url mapping and other details for each build do the following convert your existing model to django model this will not ever fit your legacy sql you will have to rethink your model fix old mistakes correct old bugs that you have always wanted to correct write unit tests build conversion utility to export old data and import into the new model build django admin pages to touch and feel the new data pick representative pages and rework them into the appropriate templates you might make use of some legacy jsp pages however do not waste too much time with this use the html to create django templates plan your url and view functions sometimes these view functions will leverage legacy action classes do not convert rewrite from scratch use your new language and framework the only thing that is worth preserving is the data and the operational concept do not try to preserve or convert the code it is misleading you might convert unittests from junit to python unittest gave this advice few months ago had to do some coaching and review during the processing the revised site is up and running no conversion from the old technology they did the suggested rewrite from scratch developer happy site works well
|
QA
|
how to find out whether subversion working directory is locked by svn python script is running two parallel python processes created via os fork each of which eventually tries to check out subversion repository leaf into the same working copy dir before running svn co command in sub process via python subprocess module the parent python code checks if the working copy dir already exists if os path isdir checkout dir working copy dir already exists return checkout dir so that if it does there should not be any svn co running but rather immediate return from the parent function nevertheless some collision happened and one of the python processes failed on svn co with the following error checked out failed svn working copy tmp qm locked svn run svn cleanup to remove locks type svn help cleanup for details so the first question is why the working copy dir existence check did not work and the second is there way to find out that working copy dir is locked by svn and loop until it is unlocked thanks
|
this sounds like potential race condition in that something like the following can happen process checks to see if the directory exists it does not yet process checks to see if the directory exists it does not yet process invokes svn which creates the directory process invokes svn which subsequently fails an easy way to avoid this is to have each process attempt to create the directory rather than checking for its existence if the other process has already created the directory the other process is guaranteed to get well defined error code under very wide variety of platforms and filesystems for instance this is one of the only reliable ways to do synchronization on many implementations of nfs luckily svn will not care if the working directory already exists the python code would look something like this import os errno try os mkdir dirname except oserror if errno errno eexist raise some other error print directory already exists else print successfully created new directory this technique is easy to implement very reliable and useful in wide variety of situations
|
QA
|
get last answer in many symbolic math systems such as matlab or mathematica you can use variable like ans or to retrieve the last computed value is there similar facility in the python she will
|
underscore
|
QA
|
get last answer in many symbolic math systems such as matlab or mathematica you can use variable like ans or to retrieve the last computed value is there similar facility in the python she will
|
just for the record ipython takes this one step further and you can access every result with and its numeric value in out in out in out in out in out in out in out and it is possible to edit ranges of lines with the ed macro too in def foo print bar in foo bar in ed
|
QA
|
am looking for pythonic way to insert space before capital letters have got file whose format am altering via python script have several camel cased strings in this file where just want to insert single space before the capital letter so wordwordword becomes word word word my limited regex experience just stalled out on me can someone think of decent regex to do this or better yet is there more pythonic way to do this that am missing
|
agree that the regex solution is the easiest but would not say it is the most pythonic how about text wordwordword new text is first letter true for letter in text if not is first letter and letter isupper new text letter else new text letter isfirstletter false
|
QA
|
can pickle python dictionary into sqlite text field any gotchas should be aware of can store it in text field or do need to use blob am not overly familiar with either pickle or sqlite so wanted to make sure am barking up the right tree with some of my high level design ideas
|
have to agree with some of the comments here be careful and make sure you really want to save pickle data in db there is probably better way in any case had trouble in the past trying to save binary data in the sqlite db apparently you have to use the sqlite binary to prep the data for sqlite here is some sample code query you insert into testtable values sqlite binary binarydata cur execute query con commit
|
QA
|
how to check if os is vista in python how in the simplest possible way distinguish between windows xp and windows vista using python and pywin or wxpython essentially need function that called will return true iff current os is vista iswindowsvista true
|
python has the lovely platform module to help you out import platform platform win ver xp sp multiprocessor free platform system windows platform version platform release xp note as mentioned in the comments proper values may not be returned when using older versions of python
|
QA
|
is there any way to get python omnicomplete to work with non system modules in vim the only thing can get python omnicomplete to work with are system modules get nothing for help with modules in my site packages or modules that am currently working on
|
think your after the pydiction script it let us you add your own stuff and site packages to omni complete while your at it add the following to your python vim file set iskeyword this will let you auto complete package functions if you enter os path and then ctrl you will get list of the functions for os path
|
QA
|
how do remove cookie that have set on someone is computer have got web system where users log in and it stores cookie of their session when they log in as someone else or log out want to remove that original cookie that stored what is the best way to do that am using python and apache though suppose the answer will remain the same for most languages
|
guess the best way is to set the expiration to date of the cookie to some date in the past
|
QA
|
how do remove cookie that have set on someone is computer have got web system where users log in and it stores cookie of their session when they log in as someone else or log out want to remove that original cookie that stored what is the best way to do that am using python and apache though suppose the answer will remain the same for most languages
|
set the cookie again as if you had not set it the first time but specify an expiration date that is in the past
|
QA
|
how to check if string in python is in ascii want to check whether string is in ascii or not am aware of ord however when try ord have typeerror ord expected character but string of length found understood it is caused by the way built python as explained in ord documentation is there another way to check
|
your question is incorrect the error you see is not result of how you built python but of confusion between byte strings and unicode strings byte strings foo or bar in python syntax are sequences of octets numbers from unicode strings you foo or you bar are sequences of unicode code points numbers from but you appear to be interested in the character which in your terminal is multi byte sequence that represents single character instead of ord you try this ord for in you that tells you which sequence of code points represents it may give you or it may give you instead of chr to reverse this there is unichr unichr you xe this character may actually be represented either single or multiple unicode code points which themselves represent either graphemes or characters it is either with an acute accent code point or code point followed by an acute accent on the previous character code point so this exact same character may be presented as the python data structure you or you most of the time you should not have to care about this but it can become an issue if you are iterating over unicode string as iteration works by code point not by decomposable character in other words len you and len you if this matters to you you can convert between composed and decomposed forms by using unicodedata normalize the unicode glossary can be helpful guide to understanding some of these issues by pointing how how each specific term refers to different part of the representation of text which is far more complicated than many programmers realize
|
QA
|
how do remove cookie that have set on someone is computer have got web system where users log in and it stores cookie of their session when they log in as someone else or log out want to remove that original cookie that stored what is the best way to do that am using python and apache though suppose the answer will remain the same for most languages
|
return the header set cookie token opaque domain your domain expires thu jan gmt path the domain and path must match the original attributes that the cookie was issued under
|
QA
|
how to check if string in python is in ascii want to check whether string is in ascii or not am aware of ord however when try ord have typeerror ord expected character but string of length found understood it is caused by the way built python as explained in ord documentation is there another way to check
|
sting str type in python is series of bytes there is no way of telling just from looking at the string whether this series of bytes represent an ascii string string in bit charset like iso or string encoded with utf or utf or whatever however if you know the encoding used then you can decode the str into unicode string and then use regular expression or loop to check if it contains characters outside of the range you are concerned about
|
QA
|
what is the best way to escape python strings in php have php application which needs to output python script more specifically bunch of variable assignment statements eg subject prefix this string from user input msg footer this one too the contents of subject prefix et al need to be written to take user input as such need to escape the contents of the strings writing something like the following is not going to cut it we are stuffed as soon as someone uses quote or newline or anything else that am not aware of that could be hazardous echo subject prefix subject prefix so any ideas rewriting the app in python is not possible due to time constraints edit years later this was for integration between web app written in php and mailman written in python could not modify the install of the latter so needed to come up with way to talk in its language to manage its configuration this was also really bad idea
|
do not try write this function in php you will inevitably get it wrong and your application will inevitably have an arbitrary remote execution exploit first consider what problem you are actually solving presume you are just trying to get data from php to python you might try to write ini file rather than py file python has an excellent ini syntax parser configparser you can write the obvious and potentially incorrect quoting function in php and nothing serious will happen if read when you get it wrong you could also write an xml file there are too many xml parsers and emitters for php and python for me to even list here if really cannot convince you that this is terrible terrible idea then you can at least use the pre existing function that python has for doing such thing repr here is handy php function which will run python script to do this for you php function py escape input descriptorspec array array pipe array pipe process proc open python import sys sys stdout write repr sys stdin read descriptorspec pipes fwrite pipes input fclose pipes chunk size escaped fread pipes chunk size if strlen escaped chunk size this is important for security die that string too big proc close process return escaped example usage string rfull nof crappy stuff print py escape the chunk size check is intended to prevent an attack whereby your input ends up being two really long strings which look like hello chunk size and os system do bad stuff respectively now that naive attack will not work exactly because python will not let single quoted string end in the middle of line and those quotes in the system call will themselves be quoted but if the attacker manages to get line continuation into the right place and use something like os system map chr then they can inject some code that will run opted to simply read one chunk and give up if there was more output rather than continuing to read and accumulate because there are also limits on python source file line length for all know that could be another attack vector python is not intended to be secure against arbitrary people writing arbitrary source code on your system so this area is unlikely to be audited the fact that had to think of all this for this trivial example is just another example of why you should not use python source code as data interchange format
|
QA
| null |
guess filter is as fast as you can possibly get without having to code the filtering function in and in that case you better code the whole filtering process in why do not you paste the function you are filtering on that might lead to easier optimizations read this about optimization in python and this about the python api
|
QA
|
am looking for pythonic way to insert space before capital letters have got file whose format am altering via python script have several camel cased strings in this file where just want to insert single space before the capital letter so wordwordword becomes word word word my limited regex experience just stalled out on me can someone think of decent regex to do this or better yet is there more pythonic way to do this that am missing
|
think regexes are the way to go here but just to give pure python version without hopefully any of the problems has pointed out def splitcaps result for ch next in window result append ch if next isupper and not ch isspace result append return join result window is utility function use to operate on sliding window of items defined as import collections itertools def window it winsize step it iter it ensure we have an iterator collections deque itertools islice it winsize while continue till stopiteration gets raised yield tuple for in range step append it next popleft
|
QA
|
store simple user settings in python am programming website in which users will have number of settings such as their choice of colour scheme etc am happy to store these as plain text files and security is not an issue the way currently see it is there is dictionary where all the keys are users and the values are dictionaries with the users settings in them for example userdb bob colour scheme would have the value blue what is the best way to store it on file pickling the dictionary are there better ways of doing what am trying to do
|
using cpickle on the dictionary would be my choice dictionaries are natural fit for these kind of data so given your requirements see no reason not to use them that unless you are thinking about reading them from non python applications in which case you would have to use language neutral text format and even here you could get away with the pickle plus an export tool
|
QA
|
store simple user settings in python am programming website in which users will have number of settings such as their choice of colour scheme etc am happy to store these as plain text files and security is not an issue the way currently see it is there is dictionary where all the keys are users and the values are dictionaries with the users settings in them for example userdb bob colour scheme would have the value blue what is the best way to store it on file pickling the dictionary are there better ways of doing what am trying to do
|
if you have database might suggest storing the settings in the database however it sounds like ordinary files might suit your environment better you probably do not want to store all the users settings in the same file because you might run into trouble with concurrent access to that one file if you stored each user settings as dictionary in their own pickled file then they would be able to act independently pickling is reasonable way to store such data but unfortunately the pickle data format is notoriously not human readable you might be better off storing it as repr dictionary which will be more readable format to reload the user settings use eval open file read or something like that
|
QA
|
store simple user settings in python am programming website in which users will have number of settings such as their choice of colour scheme etc am happy to store these as plain text files and security is not an issue the way currently see it is there is dictionary where all the keys are users and the values are dictionaries with the users settings in them for example userdb bob colour scheme would have the value blue what is the best way to store it on file pickling the dictionary are there better ways of doing what am trying to do
|
do not tackle the question which one is best if you want to handle text files would consider configparser module another you could give try would be simplejson or yaml you could also consider real db table for instance you could have table called userattrs with three columns int user id string attribute name string attribute value if there is only few you could store them into cookies for quick retrieval
|
QA
|
store simple user settings in python am programming website in which users will have number of settings such as their choice of colour scheme etc am happy to store these as plain text files and security is not an issue the way currently see it is there is dictionary where all the keys are users and the values are dictionaries with the users settings in them for example userdb bob colour scheme would have the value blue what is the best way to store it on file pickling the dictionary are there better ways of doing what am trying to do
|
here is the simplest way use simple variables and import the settings file call the file userprefs py user prefs file color font times new roman position size in your application you need to be sure that you can import this file you have many choices using pythonpath require pythonpath be set to include the directory with the preferences files an explicit command line parameter to name the file not the best but simple an environment variable to name the file extending sys path to include the user home directory example import sys import os sys path insert os path expanduser import userprefs print userprefs color
|
QA
| null |
maybe your lists are too large and do not fit in memory and you experience thrashing if the sources are in files you do not need the whole list in memory all at once try using itertools from itertools import ifilter def is important return len filtered list ifilter is important open mylist txt note that ifilter returns an iterator that is fast and memory efficient generator tricks is tutorial by david beazley that teaches some interesting uses for generators
|
QA
| null |
before doing it in you could try numpy perhaps you can turn your filtering into number crunching
|
QA
|
store simple user settings in python am programming website in which users will have number of settings such as their choice of colour scheme etc am happy to store these as plain text files and security is not an issue the way currently see it is there is dictionary where all the keys are users and the values are dictionaries with the users settings in them for example userdb bob colour scheme would have the value blue what is the best way to store it on file pickling the dictionary are there better ways of doing what am trying to do
|
if human readablity of configfiles matters an alternative might be the configparser module which allows you to read and write ini like files but then you are restricted to one nesting level
|
QA
| null |
filter will create new list so if your original is very big you could end up using up to twice as much memory if you only need to process the results iteratively rather than use it as real random access list you are probably better off using ifilter instead ie for in itertools ifilter condition func my really big list do something with other speed tips are to use python builtin rather than function you write yourself there is itertools ifilterfalse specifically for the case where you would otherwise need to introduce lambda to negate your check eg ifilter lambda not isalpha should be written ifilterfalse str isalpha
|
QA
|
tracd realm am trying to setup tracd for the project am currently working on after creating password file with the python script given in the site am trying to start the server with authentication on but it throws up warning saying no users found in the realm what actually is realm tried using trac as the value and also tried leaving it empty am using windows xp am using tracd standalone server the command line sent was tracd port auth my test project my test project documents trac digest txt trac my test project documents trac the warning message was warning found no users in realm trac thanks
|
replacing the above said command line with the one bellow helps tracd port auth trac my test project documents trac digest txt trac my test project documents trac the string after auth should be the environment name and not the project name
|
QA
|
how can unpack binary hex formatted data in python using the php pack function have converted string into binary hex representation string md time character length packed pack string the formatting means hex string high nibble first to unpack this in php would simply use the unpack function with the format flag how would unpack this data in python
|
in python you use the struct module for this from struct import pack hhl unpack hhl calcsize hhl hth
|
QA
|
how can unpack binary hex formatted data in python using the php pack function have converted string into binary hex representation string md time character length packed pack string the formatting means hex string high nibble first to unpack this in php would simply use the unpack function with the format flag how would unpack this data in python
|
there is no corresponding hex nibble code for struct pack so you will either need to manually pack into bytes first like hex string abcdef hexdigits int for in hex string data join struct pack high low for high low in zip hexdigits hexdigits or better you can just use the hex codec ie data hex string decode hex data xab xcd xef to unpack you can encode the result back to hex similarly data encode hex abcdef however note that for your example there is probably no need to take the round trip through hex representation at all when encoding just use the md binary digest directly ie md md some string digest xc xfb xee xc xfc xd xbe xe this is equivalent to your pack ed representation to get the hex representation use the same unpack method above digest decode hex acbd db cc cedef fccc hexdigest acbd db cc cedef fccc edit updated to use better method hex codec
|
QA
|
store simple user settings in python am programming website in which users will have number of settings such as their choice of colour scheme etc am happy to store these as plain text files and security is not an issue the way currently see it is there is dictionary where all the keys are users and the values are dictionaries with the users settings in them for example userdb bob colour scheme would have the value blue what is the best way to store it on file pickling the dictionary are there better ways of doing what am trying to do
|
would use shelve or an sqlite database if would have to store these setting on the file system although since you are building website you probably use some kind of database so why not just use that
|
QA
| null |
it may be useful to know that generally conditional list comprehension is much faster than the corresponding lambda import timeit timeit timer for in xrange if timeit timeit lambda timeit timer for in xrange if timeit not sure why needed to put in the timeit namespace there have not really used the module much
|
QA
| null |
if you can avoid creating the lists in the first place you will be happier rather than abiglist somelistmakingfunction filter lambda abiglist you might want to look at your function that makes the list def somelistmakinggenerator for in some source yield then your filter does not involve giant tract of memory def myfilter agenerator for in agenerator if yield by using generators you do not keep much stuff in memory
|
QA
|
store simple user settings in python am programming website in which users will have number of settings such as their choice of colour scheme etc am happy to store these as plain text files and security is not an issue the way currently see it is there is dictionary where all the keys are users and the values are dictionaries with the users settings in them for example userdb bob colour scheme would have the value blue what is the best way to store it on file pickling the dictionary are there better ways of doing what am trying to do
|
is there are particular reason you are not using the database for this it seems the normal and natural thing to do or store pickle of the settings in the db keyed on user id or something you have not described the usage patterns of the website but just thinking of general website but would think that keeping the settings in database would cause much less disk than using files otoh for settings that might be used by client side code storing them as javascript in static file that can be cached would be handy at the expense of having multiple places you might have settings would probably store those settings in the db and rebuild the static files as necessary
|
QA
|
how to avoid computation every time python module is reloaded have python module that makes use of huge dictionary global variable currently put the computation code in the top section every first time import or reload of the module takes more then one minute which is totally unacceptable how can save the computation result somewhere so that the next import reload does not have to compute it tried cpickle but loading the dictionary variable from file takes approximately the same time as computation to give more information about my problem fd freqdist word for word in brown words this line of code takes min
|
factor the computationally intensive part into separate module then at least on reload you will not have to wait try dumping the data structure using protocol the command to try would be cpickle dump fd protocol from the docstring for cpickle pickler protocol is the only protocol that can be written to file opened in text mode and read back successfully when using protocol higher than make sure the file is opened in binary mode both when pickling and unpickling
|
QA
|
store simple user settings in python am programming website in which users will have number of settings such as their choice of colour scheme etc am happy to store these as plain text files and security is not an issue the way currently see it is there is dictionary where all the keys are users and the values are dictionaries with the users settings in them for example userdb bob colour scheme would have the value blue what is the best way to store it on file pickling the dictionary are there better ways of doing what am trying to do
|
agree with the reply about using pickled dictionary very simple and effective for storing simple data in dictionary structure
|
QA
|
store simple user settings in python am programming website in which users will have number of settings such as their choice of colour scheme etc am happy to store these as plain text files and security is not an issue the way currently see it is there is dictionary where all the keys are users and the values are dictionaries with the users settings in them for example userdb bob colour scheme would have the value blue what is the best way to store it on file pickling the dictionary are there better ways of doing what am trying to do
|
if you do not care about being able to edit the file yourself and want quick way to persist python objects go with pickle if you do want the file to be readable by human or readable by some other app use configparser if you need anything more complex go with some sort of database be it relational sqlite or object oriented axiom zodb
|
QA
|
store simple user settings in python am programming website in which users will have number of settings such as their choice of colour scheme etc am happy to store these as plain text files and security is not an issue the way currently see it is there is dictionary where all the keys are users and the values are dictionaries with the users settings in them for example userdb bob colour scheme would have the value blue what is the best way to store it on file pickling the dictionary are there better ways of doing what am trying to do
|
for database driven website of course your best option is db table am assuming that you are not doing the database thing if you do not care about human readable formats then pickle is simple and straightforward way to go have also heard good reports about simplejson if human readability is important two simple options present themselves module just use module if all you need are few globals and nothing fancy then this is the way to go if you really got desperate you could define classes and class variables to emulate sections the downside here if the file will be hand edited by user errors could be hard to catch and debug ini format have been using configobj for this with quite bit of success configobj is essentially replacement for configparser with support for nested sections and much more optionally you can define expected types or values for file and validate it providing safety net and important error feedback for users administrators
|
QA
|
how can unpack binary hex formatted data in python using the php pack function have converted string into binary hex representation string md time character length packed pack string the formatting means hex string high nibble first to unpack this in php would simply use the unpack function with the format flag how would unpack this data in python
|
there is an easy way to do this with the binascii module import binascii print binascii hexlify abcz unless am misunderstanding something about the nibble ordering high nibble first is the default that should be perfectly sufficient furthermore python hashlib md objects have hexdigest method to automatically convert the md digest to an ascii hex string so that this method is not even necessary for md digests hope that helps
|
QA
|
is there any way to get python omnicomplete to work with non system modules in vim the only thing can get python omnicomplete to work with are system modules get nothing for help with modules in my site packages or modules that am currently working on
|
get completion for my own modules in my pythonpath or site packages am not sure what version of the pythoncomplete vim script you are using but you may want to make sure it is the latest edit here is some examples of what am seeing on my system this file mymodule py puth in directory in pythonpath and then in site packages both times was able to get the screenshot below myvar test def myfunction foo test pass class myclass object pass
|
QA
|
shortest sudoku solver in python how does it work was playing around with my own sudoku solver and was looking for some pointers to good and fast design when came across this def find or exit in or for in range or for in from sys import argv my own implementation solves sudokus the same way solve them in my head but how does this cryptic algorithm work http scottkirkwood blogspot com shortest sudoku solver in python html
|
lot of the short sudoku solvers just recursively try every possible legal number left until they have successfully filled the cells have not taken this apart but just skimming it it looks like that is what it does
|
QA
|
shortest sudoku solver in python how does it work was playing around with my own sudoku solver and was looking for some pointers to good and fast design when came across this def find or exit in or for in range or for in from sys import argv my own implementation solves sudokus the same way solve them in my head but how does this cryptic algorithm work http scottkirkwood blogspot com shortest sudoku solver in python html
|
unobfuscating it def find returns on fail index otherwise or exit anthing else is not thus if exit inner lexp or for in range appears to be string of characters with for empty and otherwise in inner lexp or for in recurse trying all possible digits for that empty field if is not in the inner lexp from sys import argv thus is some string so we just need to work out the inner list expression know it collects the digits set in the line otherwise the code around it makes no sense however have no real clue how it does that and am too tired to work out that binary fancyness right now sorry
|
QA
|
urllib urlopen works but urllib urlopen does not have simple website am testing it is running on localhost and can access it in my web browser the index page is simply the word running urllib urlopen will successfully read the page but urllib urlopen will not here is script which demonstrates the problem this is the actual script and not simplification of different test script import urllib urllib print urllib urlopen http read prints running print urllib urlopen http read throws an exception here is the stack trace traceback most recent call last file urltest py line in module print urllib urlopen http read file python lib urllib py line in urlopen return opener open url data file python lib urllib py line in open response meth req response file python lib urllib py line in http response http request response code message hdrs file python lib urllib py line in error result self call chain args file python lib urllib py line in call chain result func args file python lib urllib py line in http error return self parent open new file python lib urllib py line in open response meth req response file python lib urllib py line in http response http request response code message hdrs file python lib urllib py line in error return self call chain args file python lib urllib py line in call chain result func args file python lib urllib py line in http error default raise httperror req get full url code message hdrs fp urllib httperror http error gateway timeout any ideas might end up needing some of the more advanced features of urllib so do not want to just resort to using urllib plus want to understand this problem
|
does calling urlib open first followed by urllib open have the same results just wondering if the first call to open is causing the http server to get busy causing the timeout
|
QA
|
shortest sudoku solver in python how does it work was playing around with my own sudoku solver and was looking for some pointers to good and fast design when came across this def find or exit in or for in range or for in from sys import argv my own implementation solves sudokus the same way solve them in my head but how does this cryptic algorithm work http scottkirkwood blogspot com shortest sudoku solver in python html
|
is recursive function which attempts to fill in in the board in each step find or exit is the on success termination if no more values exist in the board we are done is the current value we will try to fill the with in or for in range evaluates to truthy if it is obivously incorrect to put in the current let us nickname it is bad this is the most tricky bit is bad or is conditional recursive step it will recursively try to evaluate the next in the board iff the current solution candidate appears to be sane for in enumerates all the numbers from to inefficiently
|
QA
|
urllib urlopen works but urllib urlopen does not have simple website am testing it is running on localhost and can access it in my web browser the index page is simply the word running urllib urlopen will successfully read the page but urllib urlopen will not here is script which demonstrates the problem this is the actual script and not simplification of different test script import urllib urllib print urllib urlopen http read prints running print urllib urlopen http read throws an exception here is the stack trace traceback most recent call last file urltest py line in module print urllib urlopen http read file python lib urllib py line in urlopen return opener open url data file python lib urllib py line in open response meth req response file python lib urllib py line in http response http request response code message hdrs file python lib urllib py line in error result self call chain args file python lib urllib py line in call chain result func args file python lib urllib py line in http error return self parent open new file python lib urllib py line in open response meth req response file python lib urllib py line in http response http request response code message hdrs file python lib urllib py line in error return self call chain args file python lib urllib py line in call chain result func args file python lib urllib py line in http error default raise httperror req get full url code message hdrs fp urllib httperror http error gateway timeout any ideas might end up needing some of the more advanced features of urllib so do not want to just resort to using urllib plus want to understand this problem
|
know this answer sucks but it works fine on my machine winxp with python
|
QA
|
urllib urlopen works but urllib urlopen does not have simple website am testing it is running on localhost and can access it in my web browser the index page is simply the word running urllib urlopen will successfully read the page but urllib urlopen will not here is script which demonstrates the problem this is the actual script and not simplification of different test script import urllib urllib print urllib urlopen http read prints running print urllib urlopen http read throws an exception here is the stack trace traceback most recent call last file urltest py line in module print urllib urlopen http read file python lib urllib py line in urlopen return opener open url data file python lib urllib py line in open response meth req response file python lib urllib py line in http response http request response code message hdrs file python lib urllib py line in error result self call chain args file python lib urllib py line in call chain result func args file python lib urllib py line in http error return self parent open new file python lib urllib py line in open response meth req response file python lib urllib py line in http response http request response code message hdrs file python lib urllib py line in error return self call chain args file python lib urllib py line in call chain result func args file python lib urllib py line in http error default raise httperror req get full url code message hdrs fp urllib httperror http error gateway timeout any ideas might end up needing some of the more advanced features of urllib so do not want to just resort to using urllib plus want to understand this problem
|
sounds like you have proxy settings defined that urllib is picking up on when it tries to proxy the proxy gives up and returns error from obscure python urllib proxy gotcha proxy support urllib proxyhandler opener urllib build opener proxy support print opener open http read optional makes this opener default for urlopen etc urllib install opener opener print urllib urlopen http read
|
QA
|
urllib urlopen works but urllib urlopen does not have simple website am testing it is running on localhost and can access it in my web browser the index page is simply the word running urllib urlopen will successfully read the page but urllib urlopen will not here is script which demonstrates the problem this is the actual script and not simplification of different test script import urllib urllib print urllib urlopen http read prints running print urllib urlopen http read throws an exception here is the stack trace traceback most recent call last file urltest py line in module print urllib urlopen http read file python lib urllib py line in urlopen return opener open url data file python lib urllib py line in open response meth req response file python lib urllib py line in http response http request response code message hdrs file python lib urllib py line in error result self call chain args file python lib urllib py line in call chain result func args file python lib urllib py line in http error return self parent open new file python lib urllib py line in open response meth req response file python lib urllib py line in http response http request response code message hdrs file python lib urllib py line in error return self call chain args file python lib urllib py line in call chain result func args file python lib urllib py line in http error default raise httperror req get full url code message hdrs fp urllib httperror http error gateway timeout any ideas might end up needing some of the more advanced features of urllib so do not want to just resort to using urllib plus want to understand this problem
|
do not know what is going on but you may find this helpful in figuring it out import urllib urllib urlopen http mit edu read doctype urllib opener handlers set http debuglevel urllib urlopen http mit edu read connect mit edu send get http naccept encoding identity nhost mit edu nconnection close nuser agent python urllib reply http ok header date tue oct gmt header server mit web server apache mark unix mod ssl openssl header last modified tue oct gmt header etag header accept ranges bytes header content length header connection close header content type text html doctype
|
QA
|
urllib urlopen works but urllib urlopen does not have simple website am testing it is running on localhost and can access it in my web browser the index page is simply the word running urllib urlopen will successfully read the page but urllib urlopen will not here is script which demonstrates the problem this is the actual script and not simplification of different test script import urllib urllib print urllib urlopen http read prints running print urllib urlopen http read throws an exception here is the stack trace traceback most recent call last file urltest py line in module print urllib urlopen http read file python lib urllib py line in urlopen return opener open url data file python lib urllib py line in open response meth req response file python lib urllib py line in http response http request response code message hdrs file python lib urllib py line in error result self call chain args file python lib urllib py line in call chain result func args file python lib urllib py line in http error return self parent open new file python lib urllib py line in open response meth req response file python lib urllib py line in http response http request response code message hdrs file python lib urllib py line in error return self call chain args file python lib urllib py line in call chain result func args file python lib urllib py line in http error default raise httperror req get full url code message hdrs fp urllib httperror http error gateway timeout any ideas might end up needing some of the more advanced features of urllib so do not want to just resort to using urllib plus want to understand this problem
|
urllib urlopen throws the following request at the server get http host user agent python urllib while urllib urlopen throws this get http accept encoding identity host connection close user agent python urllib so your server either does not understand http or the extra header fields
|
QA
|
shortest sudoku solver in python how does it work was playing around with my own sudoku solver and was looking for some pointers to good and fast design when came across this def find or exit in or for in range or for in from sys import argv my own implementation solves sudokus the same way solve them in my head but how does this cryptic algorithm work http scottkirkwood blogspot com shortest sudoku solver in python html
|
well you can make things little easier by fixing up the syntax def find or exit in or for in range or for in from sys import argv cleaning up little from sys import exit argv def find if exit for in in or for in range or argv okay so this script expects command line argument and calls the function on it if there are no zeros in that string exits and prints out its argument if another type of object is passed none is equivalent to passing zero and any other object is printed to sys stderr and results in an exit code of in particular sys exit some error message is quick way to exit program when an error occurs see http www python org doc lib module sys html guess this means that zeros correspond to open spaces and puzzle with no zeros is solved then there is that nasty recursive expression the loop is interesting for in why it turns out that evaluates to this is string that has each digit at least once so maybe it is trying to place each of them in fact it looks like this is what is doing recursively calling with the first blank filled in by digit from that string but this only happens if the earlier expression is false let us look at that in or for in range so the placement is done only if is not in that monster list each element is either number if the first expression is nonzero or character if the first expression is zero is ruled out as possible substitution if it appears as character which can only happen if the first expression is zero when is the expression zero it has three parts that are multiplied which is zero if and are multiple of apart the same column which is zero if the same row which is zero if both of these are zero which is zero if the same block of three rows which is zero if the same block of three columns if any of these three parts is zero the entire expression is zero in other words if and share row column or block then the value of cannot be used as candidate for the blank at aha from sys import exit argv def find if exit for in okay true for in range if or or and if okay false break if okay at this point is not excluded by any row column or block so let us place it and recurse argv note that if none of the placements work out will return and back up to the point where something else can be chosen so it is basic depth first algorithm not using any heuristics it is not particularly efficient took this puzzle from wikipedia http en wikipedia org wiki sudoku time python sudoku py real user sys addendum how would rewrite it as maintenance programmer this version has about speedup import sys def same row return def same col return def same block return and def find if sys exit excluded numbers set for in range if same row or same col or same block excluded numbers add for in if not in excluded numbers at this point is not excluded by any row column or block so let us place it and recurse if name main if len sys argv and len sys argv sys argv else print usage python sudoku py puzzle print where puzzle is an character string representing the puzzle read left to right top to bottom and is blank
|
QA
|
python name file same as lib have the following script import getopt sys opts args getopt getopt sys argv for key value in opts print key value if name this getopt py and run it does not work as it tries to import itself is there way around this so can keep this filename but specify on import that want the standard python lib and not this file solution based on vinko answer import sys sys path reverse from getopt import getopt opts args getopt sys argv for key value in opts print key value
|
you should avoid naming your python files with standard library module names
|
QA
|
python name file same as lib have the following script import getopt sys opts args getopt getopt sys argv for key value in opts print key value if name this getopt py and run it does not work as it tries to import itself is there way around this so can keep this filename but specify on import that want the standard python lib and not this file solution based on vinko answer import sys sys path reverse from getopt import getopt opts args getopt sys argv for key value in opts print key value
|
you should not name your scripts like existing modules especially if standard that said you can touch sys path to modify the library loading order cat getopt py print hi python python jul gcc ubuntu ubuntu on linux type help copyright credits or license for more information import sys import getopt hi python python jul gcc ubuntu ubuntu on linux type help copyright credits or license for more information import sys sys path remove import getopt dir getopt getopterror all builtins doc file name do longs do shorts error getopt gnu getopt long has args os short has arg in addition you may wish to avoid the full import and do it differently like this import sys sys path remove from getopt import getopt sys path insert opts args getopt sys argv for key value in opts print key value
|
QA
|
python name file same as lib have the following script import getopt sys opts args getopt getopt sys argv for key value in opts print key value if name this getopt py and run it does not work as it tries to import itself is there way around this so can keep this filename but specify on import that want the standard python lib and not this file solution based on vinko answer import sys sys path reverse from getopt import getopt opts args getopt sys argv for key value in opts print key value
|
python does not give you way to qualify modules you might be able to accomplish this by removing the entry from sys path or by moving it to the end would not recommend it
|
QA
|
python name file same as lib have the following script import getopt sys opts args getopt getopt sys argv for key value in opts print key value if name this getopt py and run it does not work as it tries to import itself is there way around this so can keep this filename but specify on import that want the standard python lib and not this file solution based on vinko answer import sys sys path reverse from getopt import getopt opts args getopt sys argv for key value in opts print key value
|
well you could re move the current diretory from sys path which contains the modifiable search path for libraries to make it work if you really need that
|
QA
|
framework language for new web sites and know will get thousand depends on what you are trying to do answers but seriously there really is no solid information about this online yet here are my assumptions think they are similar for alot of people right now it is now october want to start writing an application for january am willing to use beta code and such but by january would like site that does not have strange problems with that said if language is simply slower than another do not care about those things as long as the issue is linear my main concern is developer productivity will be using linux apache mysql for the application want the power to do things like run scp and ftp client functions with stable libraries only picked those two because they are not web related but at the same time represent pretty common network protocols that any larger app might use technologies like openid and oauth will be used as well experienced web developers are readily available do not have to find people from financial companies and such whatever the choice is is common and will be around for while here is kicker would like to be able to use advanced presentation layer tools languages similar to haml sass definitively want to use jquery will be creating facebook app and at some point doing things like dealing with sms messages iphone apps etc at this point the choices for language are php cake symfony zend python django ruby merb am really between django and merb at this point mostly because everybody else seems to be going that way please do not put any technologies in here that are not made for mainstream know merb is untested mostly but their stated goal is solid platform and it has alot of momentum behind it so am confident that it is workable please do not answer with how great perl is or net for future references these choices were already made debian lenny for converting cpu cycles into something useful trac for project management gliffy for wireframes and such google docs apps for documentation hosted email etc amazon ec for hosting storage cheers adam
|
it pays not to be biased about your server setup any modern web framework worth it is weight in source code has sql abstraction layer of some sort postgresql gets much better performance and this is coming from former mysql partisan apache is beast both to configure and on your server resources why not go with something light weight like nginx or lighttpd for the record am big django user but as the accepted answer said go with whatever your team knows quick turn arounds are not the time to be learning new frameworks if you are hiring team from scratch go with django
|
QA
|
how to output cdata using elementtree have discovered that celementtree is about times faster than xml dom minidom and am rewriting my xml encoding decoding code however need to output xml that contains cdata sections and there does not seem to be way to do that with elementtree can it be done
|
lxml has support for cdata and api like elementtree
|
QA
|
microphone access in python can access users microphone in python sorry forgot not everyone is mind reader windows at minimum xp but vista support would be very good
|
you might try swmixer
|
QA
|
tracd realm am trying to setup tracd for the project am currently working on after creating password file with the python script given in the site am trying to start the server with authentication on but it throws up warning saying no users found in the realm what actually is realm tried using trac as the value and also tried leaving it empty am using windows xp am using tracd standalone server the command line sent was tracd port auth my test project my test project documents trac digest txt trac my test project documents trac the warning message was warning found no users in realm trac thanks
|
the text referred to says that you must specify the realm name as trac not trac but have no chance of testing whether that makes any difference sorry
|
QA
|
which python framework to use am looking for framework which is appropriate for beginners in python and web development already found out about django and web py think that one of the most important things for me is good documentation thanks for the help dan
|
think django has some of the best documentation of any project have worked on that is the reason we chose it over turbogears two years ago and it is been the best technology choice we have made
|
QA
|
store simple user settings in python am programming website in which users will have number of settings such as their choice of colour scheme etc am happy to store these as plain text files and security is not an issue the way currently see it is there is dictionary where all the keys are users and the values are dictionaries with the users settings in them for example userdb bob colour scheme would have the value blue what is the best way to store it on file pickling the dictionary are there better ways of doing what am trying to do
|
would use the configparser module which produces some pretty readable and user editable output for your example bob colour scheme blue british yes joe color scheme that is color silly british no the following code would produce the config file above and then print it out import sys from configparser import configparser add section bob set bob colour scheme blue set bob british str true add section joe set joe color scheme that is color silly set joe british str false write sys stdout this outputs the configuration to stdout you could put file handle here instead for section in sections this is how you read the options back in print section for option in options section print option get section option print get bob british to access the british attribute for bob directly note that configparser only supports strings so you will have to convert as have above for the booleans see effbot for good run down of the basics
|
QA
|
store simple user settings in python am programming website in which users will have number of settings such as their choice of colour scheme etc am happy to store these as plain text files and security is not an issue the way currently see it is there is dictionary where all the keys are users and the values are dictionaries with the users settings in them for example userdb bob colour scheme would have the value blue what is the best way to store it on file pickling the dictionary are there better ways of doing what am trying to do
|
the built in sqlite module would probably be far simpler than most alternatives and gets you ready to update to full rdbms should you ever want or need to
|
QA
|
which python framework to use am looking for framework which is appropriate for beginners in python and web development already found out about django and web py think that one of the most important things for me is good documentation thanks for the help dan
|
django is amazingly good guido uses it working at google it is the main reason why find myself working more in python than in lua
|
QA
|
which python framework to use am looking for framework which is appropriate for beginners in python and web development already found out about django and web py think that one of the most important things for me is good documentation thanks for the help dan
|
danj here is pretty good list of all the known python frameworks http wiki python org moin webframeworks would recommend looking at the wikipedia articles for django turbogears pylons etc wrote an article on web py once but it got deleted they explain the philosophical and component differences between the frameworks pretty well personally like turbogears lot since it is based on well known components cherrypy for web serving and url routing kid for templates and sqlobject for object relational mapping like that they have resisted the urge to roll your own for all the components and feel that the result is very pythonic and easy to get started with but you should look at some code samples and tutorials and decide what suits you best
|
QA
|
which python framework to use am looking for framework which is appropriate for beginners in python and web development already found out about django and web py think that one of the most important things for me is good documentation thanks for the help dan
|
you should also take look at web py which has good docs and is very nice framework for building wep apps
|
QA
|
creating self contained python applications am trying to create self contained version of pisa html to pdf converter latest version but cannot succeed due to several errors have tried py exe bb freeze and cxfreeze this has to be in windows which makes my life bit harder remember that couple of months ago the author had zip file containing the install but now it is gone leaving me only with the python dependent way how would you work this out
|
check out pyinstaller it makes standalone executables as in one exe file and that is it
|
QA
|
which python framework to use am looking for framework which is appropriate for beginners in python and web development already found out about django and web py think that one of the most important things for me is good documentation thanks for the help dan
|
you might want to look at karrigell it has multiple options for programming syntax pure python pure html python scripts combination etc do not know how well it scales because have not used it for several years but it is good for getting your feet wet web frameworks
|
QA
|
receive socket size limits good am writing program in python that will act as server and accept data from client is it good idea to impose hard limit as to the amount of data if so why more info so certain chat programs limit the amount of text one can send per send per time user presses send so the question comes down to is there legit reason for this and if yes what is it
|
what is your question exactly what happens when you do receive on socket is that the current available data in the socket buffer is immediately returned if you give receive or read guess huge buffer size such as it will likely never return that much data at once if you give it tiny buffer size like then it will return the bytes it has immediately and still have more available either way you are not imposing limit on how much data the client is sending you
|
QA
|
how do get python markdown to additionally urlify links when formatting plain text markdown is great tool for formatting plain text into pretty html but it does not turn plain text links into urls automatically like this one http www google com how do get markdown to add tags to urls when format block of text
|
this is not feature of markdown what you should do is run post processor against the text looking for url like pattern there is good example in the google app engine example code see the autolink transform
|
QA
|
does python support multiprocessor multicore programming what is the difference between multiprocessor programming and multicore programming preferably show examples in python how to write small program for multiprogramming multicore programming
|
you can read about multithreading in python and threading in general multithreading in python http www devshed com python basic threading in python
|
QA
|
does python support multiprocessor multicore programming what is the difference between multiprocessor programming and multicore programming preferably show examples in python how to write small program for multiprogramming multicore programming
|
if understand things correctly python has something called the gil global interpreter lock that effectively makes it impossible to take advantage of multicores when doing multiple threads in python see eg guido van rossum blog entry on the topic as far as know among the mainstream languages only and java have effective support for multicores
|
QA
|
does python support multiprocessor multicore programming what is the difference between multiprocessor programming and multicore programming preferably show examples in python how to write small program for multiprogramming multicore programming
|
the main difference is how you organize and distribute data multicore typically has higher bandwidths between the different cores in cpu and multiprocessor needs to involve the bus between the cpus more python has gotten multiprocess process as in program running and more synchronization and communication objects for multithreaded programming
|
QA
|
receive socket size limits good am writing program in python that will act as server and accept data from client is it good idea to impose hard limit as to the amount of data if so why more info so certain chat programs limit the amount of text one can send per send per time user presses send so the question comes down to is there legit reason for this and if yes what is it
|
most likely you have seen code which protects against extra incoming data this is often due to the possibility of buffer overruns where the extra data being copied into memory overruns the pre allocated array and overwrites executable code with attacker code code written in languages like typically has lot of length checking to prevent this type of attack functions such as gets and strcpy are replaced with their safer counterparts like fgets and strncpy which have length argument to prevent buffer overruns if you use dynamic language like python your arrays resize so they will not overflow and clobber other memory but you still have to be careful about sanitizing foreign data chat programs likely limit the size of message for reasons such as database field size if of your incoming messages are characters or less are characters or less and are characters or less why make your message text field allow characters per message
|
QA
|
does python support multiprocessor multicore programming what is the difference between multiprocessor programming and multicore programming preferably show examples in python how to write small program for multiprogramming multicore programming
|
as mentioned in another post python has the multiprocessing module which can take advantage of multiple cores processors it gets around gil by starting multiple processes transparently it offers some primitives similar to the threading module you will find some simple examples of usage in the documentation pages
|
QA
|
how do get python markdown to additionally urlify links when formatting plain text markdown is great tool for formatting plain text into pretty html but it does not turn plain text links into urls automatically like this one http www google com how do get markdown to add tags to urls when format block of text
|
there is an extra for this in python markdown http code google com python markdown wiki linkpatterns
|
QA
|
which python framework to use am looking for framework which is appropriate for beginners in python and web development already found out about django and web py think that one of the most important things for me is good documentation thanks for the help dan
|
echoing the answer of few suggest django for some simple reasons it follows standard mvc architecture you can modularise your entire application right from db modeling extensive documentation and free online example project based books available many open source web based projects for reference available
|
QA
|
how do execute program from python os system fails due to spaces in path have python script that needs to execute an external program but for some reason fails if have the following script import os os system temp notepad exe raw input then it fails with the following error temp is not recognized as an internal or external command operable program or batch file if escape the program with quotes import os os system temp notepad exe raw input then it works however if add parameter it stops working again import os os system temp notepad exe test txt raw input what is the right way to execute program and wait for it to complete do not need to read output from it as it is visual program that does job and then just exits but need to wait for it to complete also note moving the program to non spaced path is not an option either edit this does not work either import os os system temp notepad exe raw input note the swapped single double quotes with or without parameter to notepad here it fails with the error message the filename directory name or volume label syntax is incorrect
|
suspect it is the same problem as when you use shortcuts in windows try this import os os system temp notepad exe test txt
|
QA
|
how do execute program from python os system fails due to spaces in path have python script that needs to execute an external program but for some reason fails if have the following script import os os system temp notepad exe raw input then it fails with the following error temp is not recognized as an internal or external command operable program or batch file if escape the program with quotes import os os system temp notepad exe raw input then it works however if add parameter it stops working again import os os system temp notepad exe test txt raw input what is the right way to execute program and wait for it to complete do not need to read output from it as it is visual program that does job and then just exits but need to wait for it to complete also note moving the program to non spaced path is not an option either edit this does not work either import os os system temp notepad exe raw input note the swapped single double quotes with or without parameter to notepad here it fails with the error message the filename directory name or volume label syntax is incorrect
|
subprocess call will avoid problems with having to deal with quoting conventions of various shells it accepts list rather than string so arguments are more easily delimited import subprocess subprocess call temp notepad exe test txt
|
QA
|
alert popups from service in python have been using win api messagebox to do alerts and this works for apps running from the interactive prompt and normally executed code however when built python service when messagebox is triggered can hear the beep but the box does not display is it possible to display alerts from services
|
no windows services run on completely separate hidden desktop and have no access to the logged on user desktop there is no way around this from service developer perspective in previous versions of windows it was possible for service to be marked as allowed to interact with the user desktop but this option was removed in xp or vista forget which now services cannot interact with the user desktop one solution to your problem might be to have desktop application that communicates with the service through some ipc method when the service wants to alert the user of some condition it would notify the desktop application which would then display regular message box
|
QA
|
does python support multiprocessor multicore programming what is the difference between multiprocessor programming and multicore programming preferably show examples in python how to write small program for multiprogramming multicore programming
|
there is no such thing as multiprocessor or multicore programming the distinction between multiprocessor and multicore computers is probably not relevant to you as an application programmer it has to do with subtleties of how the cores share access to memory in order to take advantage of multicore or multiprocessor computer you need program written in such way that it can be run in parallel and runtime that will allow the program to actually be executed in parallel on multiple cores and operating system although any operating system you can run on your pc will do this this is really parallel programming although there are different approaches to parallel programming the ones that are relevant to python are multiprocessing and multithreading in languages like java and you can write parallel programs by executing multiple threads the global interpreter lock in the cpython and pypy runtimes preclude this option but only for those runtimes in my personal opinion multithreading is dangerous and tricky and it is generally good thing that python encourages you not to consider it as way to get performance advantage if you want to write parallel program which can run on multiple cores in python you have few different options write multithreaded program using the threading module and run it in the ironpython or jython runtime use the processing module now included in python as the multiprocessing module to run your code in multiple processes at once use the subprocess module to run multiple python interpreters and communicate between them use twisted and ampoule this has the advantage of not just running your code across different processes but if you do not share access to things like files potentially across different computers as well no matter which of these options you choose you will need to understand how to split the work that your program is doing up into chunks that make sense to separate since am not sure what kind of programs you are thinking of writing it would be difficult to provide useful example
|
QA
|
can implement web user authentication system in python without post my university does not support the post cgi method know it is crazy and was hoping to be able to have system where user can have username and password and log in securely is this even possible if it is not how would you do it with post just out of curiosity cheers
|
javascript is the best option in this case along with the request for the username and password it sends unique random string you can then use javascript md library to generate hashed password by combining the random string and the password pwhash md randomstring password the javascript then instantiates the call to http server login cgi username theusername random randomstring pwhash abcdef abcdef the server must then do two things check if the random string has ever been used before and it if has deny the request very important for security lookup the plaintext password for username and do md randomstring password if that matches what the user supplied in the url as pwhash then you know it is the user the reason you check if the random string has ever been used before is to stop repeat attack if somebody is able to see the network traffic or the browser history or logs then they could simply log in again using the same url and it does not matter whether they know the original password or not also recommend putting pragma no cache and cache control no cache at the top of the headers returned by the cgi script just so that the authenticated session is not stored in the browser or your isps web cache an even more secure solution would be using proper encryption and challenge response you tell the server your username the server sends back challenge some random string encrypted with your password and you tell the server what the random string was if you are able to tell the server then obviously you have the password and are who you say you are kerberos does it this way but quite lot more carefully to prevent all sorts of attacks
|
QA
|
does python support multiprocessor multicore programming what is the difference between multiprocessor programming and multicore programming preferably show examples in python how to write small program for multiprogramming multicore programming
|
you can actually write programs which will use multiple processors you cannot do it with threads because of the gil lock but you can do it with different process either use the subprocess module and divide your code to execute process per processor have look at parallelpython module if you use python have look at the multiprocess module
|
QA
|
checking for member existence in python regularly want to check if an object has member or not an example is the creation of singleton in function for that purpose you can use hasattr like this class foo object classmethod def singleton self if not hasattr self instance self instance foo return self instance but you can also do this class foo object classmethod def singleton self try return self instance except attributeerror self instance foo return self instance is one method better of the other edit added the classmethod but note that the question is not about how to make singleton but how to check the presence of member in an object edit for that example typical usage would be foo singleton then is an object of type foo the same each time and typically the method is called many times
|
it depends on which case is typical because exceptions should model well atypical conditions so if the typical case is that the instance attribute should exist then use the second code style if not having instance is as typical as having instance then use the first style in the specific case of creating singleton am inclined to go with the first style because creating singleton the initial time is typical use case
|
QA
|
what are good rules of thumb for python imports am little confused by the multitude of ways in which you can import modules in python import import as from import have been reading up about scoping and namespaces but would like some practical advice on what is the best strategy under which circumstances and why should imports happen at module level or method function level in the init py or in the module code itself my question is not really answered by python packages import by class not file although it is obviously related
|
when you have well written library which is sometimes case in python you ought just import it and use it as it well written library tends to take life and language of its own resulting in pleasant to read code where you rarely reference the library when library is well written you ought not need renaming or anything else too often import gat node gat node child node children sometimes it is not possible to write it this way or then you want to lift down things from library you imported from gat import node subnode node node child subnode node sometimes you do this for lot of things if your import string overflows columns it is good idea to do this from gat import node subnode topnode supernode coolnode powernode upnode the best strategy is to keep all of these imports on the top of the file preferrably ordered alphabetically import statements first then from import statements now tell you why this is the best convention python could perfectly have had an automatic import which look from the main imports for the value when it cannot be found from global namespace but this is not good idea explain shortly why aside it being more complicated to implement than simple import programmers would not be so much thinking about the depedencies and finding out from where you imported things ought be done some other way than just looking into imports need to find out depedencies is one reason why people hate from import some bad examples where you need to do this exist though for example opengl wrappings so the import definitions are actually valuable as defining the depedencies of the program it is the way how you should exploit them from them you can quickly just check where some weird function is imported from
|
QA
|
failed to get separate instances of class under mod python am trying to run some python code under apache mod python eventually the code does os fork and spawns separate long run processes each of those processes has to create separate instance of class in order to avoid any possible collision in the parallel flow class foo object pass kidprocs for kid in kid kid pid os fork if pid parent kidprocs append pid time sleep else child fooobj foo print starting in sub process kid os getpid print kid fooobj repr fooobj os exit for kidproc in kidprocs os waitpid kidproc those print outputs look like this starting kid in sub process foo obj main foo instance at xb da fec starting kid in sub process foo obj main foo instance at xb da fec as you can see got the same object for both sub processes do you have an idea why it is going like this under mod python and is there way to get separate instances anyway thanks lot
|
the memory location given by the repr function is an address in virtual memory not an address in the system global memory each of your processes returned by fork has its own virtual memory space which is completely distinct from other processes they do not share memory edit per brian comments below technically they do share memory until the kernel decides to segregate them when child writes to portion of shared memory the behavior though is effectively the same the structure of your programs is the same so python uses the same virtual memory location in each processes distinct virtual memory store for each of your identical objects for each child if you actually modify the content of the objects and test them you will see that even though the memory location looks the same the two are completely distinct objects because they belong to two distinct processes in reality you cannot modify one from the other without some kind of interprocess communication to mediate
|
QA
|
checking for member existence in python regularly want to check if an object has member or not an example is the creation of singleton in function for that purpose you can use hasattr like this class foo object classmethod def singleton self if not hasattr self instance self instance foo return self instance but you can also do this class foo object classmethod def singleton self try return self instance except attributeerror self instance foo return self instance is one method better of the other edit added the classmethod but note that the question is not about how to make singleton but how to check the presence of member in an object edit for that example typical usage would be foo singleton then is an object of type foo the same each time and typically the method is called many times
|
just tried to measure times class foo object classmethod def singleton self if not hasattr self instance self instance foo return self instance class bar object classmethod def singleton self try return self instance except attributeerror self instance bar return self instance from time import time foo foo for in xrange bar bar for in xrange print objs created print for times in xrange time for in foo singleton print foo pass in times time time for in bar singleton print bar pass in times time print on my machine objs created foo pass in bar pass in foo pass in bar pass in foo pass in bar pass in it seems that try except is faster it seems also more readable to me anyway depends on the case this test was very simple maybe you would need more complex one
|
QA
|
python dependency injection framework is there framework equivalent to guice http code google com google guice for python
|
spring python is an offshoot of the java based spring framework and spring security targeted for python this project currently contains the following features inversion of control dependency injection use either classic xml or the python object decorator similar to the spring javaconfig subproject to wire things together while the object format is not identical to the guice style centralized wiring vs wiring information in each class it is valuable way to wire your python app aspect oriented programming apply interceptors in horizontal programming paradigm instead of vertical oop inheritance for things like transactions security and caching databasetemplate reading from the database requires monotonous cycle of opening cursors reading rows and closing cursors along with exception handlers with this template class all you need is the sql query and row handling function spring python does the rest database transactions wrapping multiple database calls with transactions can make your code hard to read this module provides multiple ways to define transactions without making things complicated security plugin security interceptors to lock down access to your methods utilizing both authentication and domain authorization remoting it is easy to convert your local application into distributed one if you have already built your client and server pieces using the ioc container then going from local to distributed is just configuration change samples to help demonstrate various features of spring python some sample applications have been created petclinic spring framework sample web app has been rebuilt from the ground up using python web containers including cherrypy go check it out for an example of how to use this framework note other python web frameworks will be added to this list in the future spring wiki wikis are powerful ways to store and manage content so we created simple one as demo spring bot use spring python to build tiny bot to manage the irc channel of your open source project
|
QA
|
checking for member existence in python regularly want to check if an object has member or not an example is the creation of singleton in function for that purpose you can use hasattr like this class foo object classmethod def singleton self if not hasattr self instance self instance foo return self instance but you can also do this class foo object classmethod def singleton self try return self instance except attributeerror self instance foo return self instance is one method better of the other edit added the classmethod but note that the question is not about how to make singleton but how to check the presence of member in an object edit for that example typical usage would be foo singleton then is an object of type foo the same each time and typically the method is called many times
|
have to agree with chris remember do not optimize until you actually need to do so really doubt checking for existence is going to be bottleneck in any reasonable program did see http code activestate com recipes as way to do this too uncommented copy of that code spam is just random method the class interface has class singleton class impl def spam self return id self instance none def init self if singleton instance is none singleton instance singleton impl self dict singleton instance singleton instance def getattr self attr return getattr self instance attr def setattr self attr value return setattr self instance attr value
|
QA
|
checking for member existence in python regularly want to check if an object has member or not an example is the creation of singleton in function for that purpose you can use hasattr like this class foo object classmethod def singleton self if not hasattr self instance self instance foo return self instance but you can also do this class foo object classmethod def singleton self try return self instance except attributeerror self instance foo return self instance is one method better of the other edit added the classmethod but note that the question is not about how to make singleton but how to check the presence of member in an object edit for that example typical usage would be foo singleton then is an object of type foo the same each time and typically the method is called many times
|
these are two different methodologies is lbyl look before you leap and is eafp easier to ask forgiveness than permission pythonistas typically suggest that eafp is better with arguments in style of what if process creates the file between the time you test for it and the time you try to create it yourself this argument does not apply here but it is the general idea exceptions should not be treated as too exceptional performance wise in your case since setting up exception managers the try keyword is very cheap in cpython while creating an exception the raise keyword and internal exception creation is what is relatively expensive using method the exception would be raised only once afterwards you just use the property
|
QA
|
checking for member existence in python regularly want to check if an object has member or not an example is the creation of singleton in function for that purpose you can use hasattr like this class foo object classmethod def singleton self if not hasattr self instance self instance foo return self instance but you can also do this class foo object classmethod def singleton self try return self instance except attributeerror self instance foo return self instance is one method better of the other edit added the classmethod but note that the question is not about how to make singleton but how to check the presence of member in an object edit for that example typical usage would be foo singleton then is an object of type foo the same each time and typically the method is called many times
|
little off topic in the way of using it singletons are overrated and shared state method is as effective and mostly very clean in python for example class borg shared state def init self self dict self shared state and whatever else you want in your class that is all now every time you do obj borg it will have the same information or be somewhat the same instance
|
QA
|
any experience with the deliverance system my new boss went to speech where deliverance kind of proxy allowing to add skin to any html output on the fly was presented he decided to use it right after that no matter how young it is more here http www openplans org projects deliverance introduction in theory the system sounds great when you want newbie to tweak your plone theme without having to teach him all the complex mechanisms behind the zope products and apply the same theme on drupal web site in one row but do not believe in theory and would like to know if anybody tried this out in the real world
|
will start answering this question here while we perform tests but would love to have feedback from other users install we have spent small afternoon from tuto to how to to finally install and run the thing on virtual machine this one is ok http www openplans org projects deliverance getting started there are setuptools packages but this does not works out of the box and certainly not without compiling anything we had to install setuptools tested with from http pypi python org pypi setuptools of course compilation implies installing gcc linux header et lib dev libxslt in dev we used libxslt dev linking with zl so zlib we used zlib dev you would better install pastescript before starting the deliverance install installing python nose is not mandatory but it helps to check if everything went fine we did not manage to make it works with python virtualenv to we definitly messed up the debian system but it seems to run ok hope it can help
|
QA
|
which python framework to use am looking for framework which is appropriate for beginners in python and web development already found out about django and web py think that one of the most important things for me is good documentation thanks for the help dan
|
assume you are talking about web framework have used cherrypy and found it quite useful try using each one to code simple solution and see how much it lines up with your style of programming
|
QA
|
which python framework to use am looking for framework which is appropriate for beginners in python and web development already found out about django and web py think that one of the most important things for me is good documentation thanks for the help dan
|
web py it is extremely simple and python basic hello world web application is import web urls hello class hello def get self name web input times if not name name world for in range int times print hello name if name main web run urls globals that is it found django forced lot of it is own conventions and code layout and could never remember the middleware shortcuts imports and all the other magic that is pretty much required to write anything found it was closer to ruby on rails than python web framework with web py you can write an entire functioning web application without using any of web py helper modules the only thing you have to do is import web and setup the urls which is rather unavoidable the last line in the example runs the development web server it has lots of stuff in it like an database api form helpers templating engine and so on but it does not force them on you you could do all your html output by print using string formating strip if you wished oh while have emphasised the simplicity web py is what http reddit com is written in so it is also proven very capable reliable also this post by the web py author is very good explanation of why much prefer web py over django
|
QA
|
what would you recommend for high traffic ajax intensive website for website like reddit with lots of up down votes and lots of comments per topic what should go with lighttpd php or lighttpd cherrypy genshi sqlalchemy and for database what would scale better be fastest mysql or or postgresql
|
cannot speak to the mysql postgresql question as have limited experience with postgres but my masters research project was about high performance websites with cherrypy and do not think you will be disappointed if you use cherrypy for your site it can easily scale to thousands of simultaneous users on commodity hardware of course the same could be said for php and do not know of any reasonable benchmarks comparing php and cherrypy performance but if you were wondering whether cherrypy can handle high traffic site with huge number of requests per second the answer is definitely yes
|
QA
|
what would you recommend for high traffic ajax intensive website for website like reddit with lots of up down votes and lots of comments per topic what should go with lighttpd php or lighttpd cherrypy genshi sqlalchemy and for database what would scale better be fastest mysql or or postgresql
|
going to need more data jeff had few articles on the same problems and the answer was to wait till you hit performance issue to start with who is hosting and what do they have available what is your in house talent skill sets are you going to be hiring an outside firm what do they recommend brand new project team willing to learn new framework nd thing is to do some mockups how is the interface going to work what data does it need to load and persist the idea is to keep your traffic between the web and db side down no chatty pages with lots of queries etc once you have better idea of the data requirements and flow then work on the database design there are plenty of rules to follow but one of the better ones is to follow normalization rules yea am db guy why now you have couple of pages build run your tests are you having problem yes now look at what is it page serving or db pulls measure then pick course of action
|
QA
|
what would you recommend for high traffic ajax intensive website for website like reddit with lots of up down votes and lots of comments per topic what should go with lighttpd php or lighttpd cherrypy genshi sqlalchemy and for database what would scale better be fastest mysql or or postgresql
|
the ideal setup would be close to this in short nginx is fast and light webserver front proxy with unique module that let us it fetch data directly from memcached ram store without hitting the disk or any dynamic webapp of course if the request url was not already cached or if it has expired the request proceeds to the webapp as usual the genius part is that when the webapp has generated the response copy of it goes to memcached ready to be reused all this is perfectly applicable not only to webpages but to ajax query responses in the article the back servers are http and specifically talk about mongrel it would be even better if the back were fastcgi and other faster framework but it is lot less critical since the nginx memcached team absorb the biggest part of the load note that if your url scheme for the ajax traffic is well designed rest is best imho you can put most of the db right in memcached and any post which will pass to the app can preemptively update the cache
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.