prefix
stringclasses 1
value | input_text
stringlengths 19
27.3k
⌀ | target_text
stringlengths 2
24.8k
⌀ |
---|---|---|
QA
|
how to retrieve name of current windows user ad or local using python how can retrieve the name of the currently logged in user using python script the function should work regardless of whether it is domain ad user or local user
|
try this import os print os environ get username that should do the job
|
QA
|
how to retrieve name of current windows user ad or local using python how can retrieve the name of the currently logged in user using python script the function should work regardless of whether it is domain ad user or local user
|
do not know python but for windows the underlying api is getusernameex assume you can call that in python if os environ get username does not tell you everything you need to know
|
QA
|
deploying django how do you do it have tried following guides like this one but it just did not work for me so my question is this what is good guide for deploying django and how do you deploy your django keep hearing that capastrano is pretty nifty to use but have no idea as to how to work it or what it does apart from automation of deploying code or even if want need to use it or not
|
in my previous work we had real genius guy on deployment duties he deployed application python sql perl and java code as set of deb files built for ubuntu unfortunately now have no such support we are deploying apps manually to virtualenv ed environments with separate nginx configs for fastcgi we use paver to deploy to remote servers it is painful but it works
|
QA
|
what is the scope for imported classes in python please excuse the vague title if anyone has suggestion please let me know also please retag with more appropriate tags the problem want to have an instance of an imported class be able to view things in the scope globals locals of the importer since am not sure of the exact mechanism at work here can describe it much better with snippets than words file def print go class object def do eval self maybe this should be do evil given what happens print evaling eval eval globals locals then run this code from an iteractive session there there will be lots of nameerrors interactive class object def do eval self maybe this should be do evil given what happens print evaling eval eval globals locals def print go from file import import file do eval file do eval do eval file do eval file file do eval file do eval do eval do eval file do eval is there common idiom pattern for this sort of task am barking up the wrong tree entirely
|
functions are always executed in the scope they are defined in as are methods and class bodies they are never executed in another scope because importing is just another assignment statement and everything in python is reference the functions classes and modules do not even know where they are imported to you can do two things explicitly pass the environment you want them to use or use stack hackery to access their caller namespace the former is vastly preferred over the latter as it is not as implementation dependent and fragile as the latter you may wish to look at the string template class which tries to do something similar
|
QA
|
what would be the simplest way to daemonize python script in linux what would be the simplest way to daemonize python script in linux need that this works with every flavor of linux so it should only use python based tools
|
if you do not care for actual discussions which tend to go offtopic and do not offer authoritative response you can choose some library that will make your tast easier would recomment taking look at ll xist this library contains large amount of life saving code like cron jobs helper daemon framework and what is not interesting to you but is really great object oriented xsl ll xist itself
|
QA
|
python and post data in php simply write bob post bob how do do the same in python and yes do normally check that it exists etc am just stripping it down specifically to the functionality am after edit am not using framework
|
the simplest method is the cgi module import cgi data cgi fieldstorage data bob but the context you are executing in frameworks you are using wsgi or even heaven forbid mod python may have different more efficient or more direct methods of access
|
QA
|
how do get decimal value when using the division operator in python for example the standard division symbol rounds to zero however want it to return what do use
|
try
|
QA
|
how do get decimal value when using the division operator in python for example the standard division symbol rounds to zero however want it to return what do use
|
simple route or
|
QA
|
how do get decimal value when using the division operator in python for example the standard division symbol rounds to zero however want it to return what do use
|
you need to tell python to use floating point values not integers you can do that simply by using decimal point yourself in the inputs
|
QA
|
how do get decimal value when using the division operator in python for example the standard division symbol rounds to zero however want it to return what do use
|
there are three options float which is the same behavior as the java etc or from future import division you can also activate this behavior by passing the argument qnew to the python interpreter python qnew the second option will be the default in python if you want to have the old integer division you have to use the operator edit added section about qnew thanks to
|
QA
|
how do get decimal value when using the division operator in python for example the standard division symbol rounds to zero however want it to return what do use
|
make one or both of the terms floating point number like so alternatively turn on the feature that will be default in python true division that does what you want at the top of your module or script do from future import division
|
QA
|
how do get decimal value when using the division operator in python for example the standard division symbol rounds to zero however want it to return what do use
|
you cannot get decimal value by dividing one integer with another you will allways get an integer that way result truncated to integer you need at least one value to be decimal number
|
QA
|
using pylint with django would very much like to integrate pylint into the build process for my python projects but have run into one show stopper one of the error types that find extremely useful has no member constantly reports errors when using common django fields for example get user tags class tag has no objects member which is caused by this code def get user tags username gets all the tags that username has used returns query set return tag objects filter this line triggers the error tagownership users username exact username distinct here is the tag class models model is provided by django class tag models model model for user defined strings that help categorize events on on per user basis name models charfield max length null false unique true def unicode self return self name how can tune pylint to properly take fields such as objects into account have also looked into the django source and have been unable to find the implementation of objects so suspect it is not just class field on the other hand am fairly new to python so may very well have overlooked something edit the only way have found to tell pylint to not warn about these warnings is by blocking all errors of the type which is not an acceptable solution since that is in my opinion an extremely useful error if there is another way without augmenting the pylint source please point me to specifics see here for summary of the problems have had with pychecker and pyflakes they have proven to be far to unstable for general use in pychecker case the crashes originated in the pychecker code not source it was loading invoking
|
resigned from using pylint pychecker in favor of using pyflakes with django code it just tries to import module and reports any problem it finds like unused imports or uninitialized local names
|
QA
|
how to update tix combobox text have tix combobox with an editable text field how do force the variable holding the value for the text to update let me give more concrete explanation have combo box and button when click the button it pops up message box with the value of the combo box let us say the combo box text field currently has the value thing if type new into the box and then click on the button with my mouse it will pops up the message thing if type new in the box and then tab focus away from the combo box and then click the button the pop up message says new ho do force the combo box to update it is value to new without requiring that tab away from the combo box have included sample code import tix import tkmessagebox class app object def init self window window winfo toplevel wm title test self window window self combo tix combobox window self combo insert tix end thing self combo insert tix end thing self combo entry state normal self combo editable true self combo pack button tix button window button text go button command self go button pack def go self tkmessagebox showinfo info self combo value if name main root tix tk app root root mainloop
|
woo solved it on my own use self combo selection instead of self combo value
|
QA
|
what is the scope for imported classes in python please excuse the vague title if anyone has suggestion please let me know also please retag with more appropriate tags the problem want to have an instance of an imported class be able to view things in the scope globals locals of the importer since am not sure of the exact mechanism at work here can describe it much better with snippets than words file def print go class object def do eval self maybe this should be do evil given what happens print evaling eval eval globals locals then run this code from an iteractive session there there will be lots of nameerrors interactive class object def do eval self maybe this should be do evil given what happens print evaling eval eval globals locals def print go from file import import file do eval file do eval do eval file do eval file file do eval file do eval do eval do eval file do eval is there common idiom pattern for this sort of task am barking up the wrong tree entirely
|
in this example you can simply hand over functions as objects to the methods in class object def eval self def print go eval go in python you can pass functions and classes to other methods and invoke create them there if you want to actually evaluate code string you have to specify the environment as already mentioned by thomas your module from above slightly changed file def print go class object def do eval self globals globals locals locals eval globals locals now in the interactive interpreter def print go from file import do eval nameerror name is not defined do eval globals locals go do eval globals locals go some annotations here we insert all objects from file into this module namespace is not in the namespace of file therefore we get nameerror now we pass the environment explictly and the code can be evaluated is in the namespace of this module because we imported it edit added code sample on how to explicitly pass environment for eval
|
QA
|
how do use timezones with datetime object in python how do properly represent different timezone in my timezone the below example only works because know that edt is one hour ahead of me so can uncomment the subtraction of mytimezone import datetime re from datetime import tzinfo class mytimezone tzinfo docstring for mytimezone def utfoffset self dt return timedelta hours def mydatehandler adatestring you sat sep edt my date pattern re compile day month year hour minute second my date pattern search adatestring groups month jan feb mar apr may jun jul aug sep oct nov dec index month upper dt datetime datetime int year int month int day int hour int minute int second dt dt datetime timedelta hours dt dt dt tzinfo utfoffset mytimezone return dt year dt month dt day dt hour dt minute dt second def main print mydatehandler sat sep edt if name main main
|
the python standard library does not contain timezone information because unfortunately timezone data changes lot faster than python you need third party module for this the usual choice is pytz
|
QA
|
how do use owfs to read an ibutton temperature logger have installed owfs and am trying to read the data off ibutton temperature logger owfs let us me mount the ibutton as fuse filesystem and can see all the data am having trouble figuring out what is the best way to access the data though can get individual readings by catting the files cat onewire deviceid log temperature but the onewire deviceid log temperature all file is broken possible too large as histogram temperature all work fine python script to read all files seems to work but takes very long time is there better way to do it does anyone have any examples am using ubuntu and could not get the java one wire viewer app to run update using owpython installed with owfs can get the current temperature but cannot figure out how to get access to the recorded logs import ow ow init you initialize usb ow sensor sensorlist sensor fd sensor ow sensor print type temperature ds log gives an attributeerror
|
do not think there is clever way owpython does not support that telling from the api documentation guess proc is your safest bet maybe have look at the source of the owpython module and check if you can find out how it works
|
QA
|
what is the name of the python module that formats arbitrary text to nicely looking html while ago came across python library that formats regular text to html similar to markdown restructuredtext and textile just that it had no syntax at all it detected indentatations quotes links and newlines paragraphs only unfortunately lost the name of the library and was unable to google it anyone any ideas edit restructuredtext aka rst docutils that is not what am looking for
|
sphinx is documentation generator using restructuredtext it is quite nice although have not used it personally the website hazel tree which compiles python text uses sphinx and so does the new python documentation
|
QA
|
how do use timezones with datetime object in python how do properly represent different timezone in my timezone the below example only works because know that edt is one hour ahead of me so can uncomment the subtraction of mytimezone import datetime re from datetime import tzinfo class mytimezone tzinfo docstring for mytimezone def utfoffset self dt return timedelta hours def mydatehandler adatestring you sat sep edt my date pattern re compile day month year hour minute second my date pattern search adatestring groups month jan feb mar apr may jun jul aug sep oct nov dec index month upper dt datetime datetime int year int month int day int hour int minute int second dt dt datetime timedelta hours dt dt dt tzinfo utfoffset mytimezone return dt year dt month dt day dt hour dt minute dt second def main print mydatehandler sat sep edt if name main main
|
recommend babel and pytz when working with timezones keep your internal datetime objects naive and in utc and convert to your timezone for formatting only the reason why you probably want naive objects objects without timezone information is that many libraries and database adapters have no idea about timezones babel pytz
|
QA
|
how do get decimal value when using the division operator in python for example the standard division symbol rounds to zero however want it to return what do use
|
other answers suggest how to get floating point value while this wlil be close to what you want it will not be exact if you actually want decimal value do this import decimal decimal decimal decimal decimal decimal that will give you an object that properly knows that in base is floating point numbers are actually in base binary not decimal
|
QA
|
continuous integration system for python codebase am starting work on hobby project with python codebase and would like to set up some form of continuous integration running battery of test cases each time check in is made and sending nag mails to responsible persons when the tests fail similar to cruisecontrol or teamcity realize could do this with hooks in most vcses but that requires that the tests run on the same machine as the version control server which is not as elegant as would like does anyone have any suggestions for small user friendly open source continuous integration system suitable for python codebase
|
teamcity has some python integration but teamcity is not open source is not small but rather feature rich is free for small mid teams
|
QA
|
best practices for manipulating database result sets in python am writing simple python web application that consists of several pages of business data formatted for the iphone am comfortable programming python but am not very familiar with python idiom especially regarding classes and objects python object oriented design differs somewhat from other languages have worked with so even though my application is working am curious whether there is better way to accomplish my goals specifics how does one typically implement the request transform render database workflow in python currently am using pyodbc to fetch data copying the results into attributes on an object performing some calculations and merges using list of these objects then rendering the output from the list of objects sample code below sql queries redacted is this sane is there better way are there any specific gotchas have stumbled into in my relative ignorance of python am particularly concerned about how have implemented the list of rows using the empty record class class record object pass def calculate pnl records node prices for record in records try fill rt and da prices from the hash retrieved above if hasattr record sink and record sink record da node prices record sink node prices record id record rt node prices record sink node prices record id else record da node prices record id record rt node prices record id calculate dependent values rt da and pnl record rtda record rt record da record pnl record rtda record mw except print sys exc info def map rows cursor mappings callback none records for row in cursor record record for field attr in mappings iteritems setattr record attr getattr row field none if not callback or callback record records append record return records def get positions cursor get the latest position time cursor execute select latest data time time cursor fetchone time hour eelib util get hour ending time fetch the current positions cursor execute select stuff from atable hour read the rows nodes def record callback record if abs record mw if record id nodes record id none return true else return false records util map rows cursor id id name name mw mw record callback query prices for node id in nodes rt price row cursor execute select price where node id time time fetchone rt row lmp if row else none da price row cursor execute select price where node id hour hour fetchone da row da lmp if row else none update the hash value nodes node id da rt calculate the position pricing calculate pnl records nodes sort records sort key lambda name return the records return records
|
depending on how much you want to do with the data you may not need to populate an intermediate object the cursor header data structure will let you get the column names bit of introspection will let you make dictionary with col name value pairs for the row you can pass the dictionary to the operator the docs for the odbc module will explain how to get at the column metadata this snippet of code to shows the application of the operator in this manner col foo col bar col wibble col col col col col col col foo col bar col wibble
|
QA
|
can you do linq like queries in language like python or boo take this simple linq query and imagine that db numbers is an sql table with one column number var result from in db numbers where number select number this will run very efficiently in because it generates an sql query something like select number from numbers where number what it does not do is select all the numbers from the database and then filter them in as it might appear to do at first python supports similar syntax result number for in numbers if number but it the if clause here does the filtering on the client side rather than the server side which is much less efficient is there something as efficient as linq in python am currently evaluating python vs ironpython vs boo so an answer that works in any of those languages is fine
|
look closely at sqlalchemy this can probably do much of what you want it gives you python syntax for plain old sql that runs on the server
|
QA
|
how do get decimal value when using the division operator in python for example the standard division symbol rounds to zero however want it to return what do use
|
you might want to look at python decimal package also this will provide nice decimal results decimal decimal decimal
|
QA
|
can you do linq like queries in language like python or boo take this simple linq query and imagine that db numbers is an sql table with one column number var result from in db numbers where number select number this will run very efficiently in because it generates an sql query something like select number from numbers where number what it does not do is select all the numbers from the database and then filter them in as it might appear to do at first python supports similar syntax result number for in numbers if number but it the if clause here does the filtering on the client side rather than the server side which is much less efficient is there something as efficient as linq in python am currently evaluating python vs ironpython vs boo so an answer that works in any of those languages is fine
|
linq is language feature of and vb net it is special syntax recognized by the compiler and treated specially it is also dependent on another language feature called expression trees expression trees are little different in that they are not special syntax they are written just like any other class instantiation but the compiler does treat them specially under the covers by turning lambda into an instantiation of run time abstract syntax tree these can be manipulated at run time to produce command in another language sql the and vb net compilers take linq syntax and turn it into lambdas then pass those into expression tree instantiations then there are bunch of framework classes that manipulate these trees to produce sql you can also find other libraries both ms produced and third party that offer linq providers which basically pop different ast processer in to produce something from the linq other than sql so one obstacle to doing these things in another language is the question whether they support run time ast building manipulation do not know whether any implementations of python or boo do but have not heard of any such features
|
QA
|
what is the name of the python module that formats arbitrary text to nicely looking html while ago came across python library that formats regular text to html similar to markdown restructuredtext and textile just that it had no syntax at all it detected indentatations quotes links and newlines paragraphs only unfortunately lost the name of the library and was unable to google it anyone any ideas edit restructuredtext aka rst docutils that is not what am looking for
|
markdown in python is python implementation of the perl based markdown utility markown converts various forms of structured text to valid html and one of the supported forms is just plain ascii use is pretty straight forward python markdown py input file txt output file html markdown can be easily called as module too import markdown html markdown markdown your text string
|
QA
|
what is the name of the python module that formats arbitrary text to nicely looking html while ago came across python library that formats regular text to html similar to markdown restructuredtext and textile just that it had no syntax at all it detected indentatations quotes links and newlines paragraphs only unfortunately lost the name of the library and was unable to google it anyone any ideas edit restructuredtext aka rst docutils that is not what am looking for
|
okay found it now it is called pottymouth
|
QA
|
best practices for manipulating database result sets in python am writing simple python web application that consists of several pages of business data formatted for the iphone am comfortable programming python but am not very familiar with python idiom especially regarding classes and objects python object oriented design differs somewhat from other languages have worked with so even though my application is working am curious whether there is better way to accomplish my goals specifics how does one typically implement the request transform render database workflow in python currently am using pyodbc to fetch data copying the results into attributes on an object performing some calculations and merges using list of these objects then rendering the output from the list of objects sample code below sql queries redacted is this sane is there better way are there any specific gotchas have stumbled into in my relative ignorance of python am particularly concerned about how have implemented the list of rows using the empty record class class record object pass def calculate pnl records node prices for record in records try fill rt and da prices from the hash retrieved above if hasattr record sink and record sink record da node prices record sink node prices record id record rt node prices record sink node prices record id else record da node prices record id record rt node prices record id calculate dependent values rt da and pnl record rtda record rt record da record pnl record rtda record mw except print sys exc info def map rows cursor mappings callback none records for row in cursor record record for field attr in mappings iteritems setattr record attr getattr row field none if not callback or callback record records append record return records def get positions cursor get the latest position time cursor execute select latest data time time cursor fetchone time hour eelib util get hour ending time fetch the current positions cursor execute select stuff from atable hour read the rows nodes def record callback record if abs record mw if record id nodes record id none return true else return false records util map rows cursor id id name name mw mw record callback query prices for node id in nodes rt price row cursor execute select price where node id time time fetchone rt row lmp if row else none da price row cursor execute select price where node id hour hour fetchone da row da lmp if row else none update the hash value nodes node id da rt calculate the position pricing calculate pnl records nodes sort records sort key lambda name return the records return records
|
the empty record class and the free floating function that generally applies to an individual record is hint that you have not designed your class properly class record object assuming rtda and pnl must exist def init self self da self rt self rtda or whatever self pnl none self sink none not clear what this is def setpnl self node prices fill rt and da prices from the hash retrieved above calculate dependent values rt da and pnl now your calculate pnl records node prices is simpler and uses the object properly def calculate pnl records node prices for record in records record setpnl node prices the point is not to trivially refactor the code in small ways the point is this class encapsulates responsibility yes an empty looking class is usually problem it means the responsibilities are scattered somewhere else similar analysis holds for the collection of records this is more than simple list since the collection as whole has operations it performs the request transform render is not quite right you have model the record class instances of the model get built possibly because of request the model objects are responsible for their own state transformations and updates perhaps they get displayed or rendered by some object that examines their state it is that transform step that often violates good design by scattering responsibility all over the place transform is hold over from non object design where responsibility was nebulous concept
|
QA
|
debug monitor middleware for python wsgi applications am searching wsgi middleware which can warp around wsgi applications and which let us me monitor incoming and outgoing http requests and header fields something like firefox live headers but for the server side
|
that should not be too hard to write yourself as long as you only need the headers try that import sys def log headers app stream none if stream is none stream sys stdout def proxy environ start response for key value in environ iteritems if key startswith http stream write key title replace value return app environ start response return proxy
|
QA
|
how can parse comma delimited string into list caveat need to be able to take string like foo bar one two three four into foo bar one two three four have an feeling with hints from python that the solution is going to involve the shlex module
|
you may also want to consider the csv module have not tried it but it looks like your input data is closer to csv than to she will syntax which is what shlex parses
|
QA
|
how can parse comma delimited string into list caveat need to be able to take string like foo bar one two three four into foo bar one two three four have an feeling with hints from python that the solution is going to involve the shlex module
|
you could do something like this import re pattern re compile def split line return if else for in pattern findall line rstrip split foo bar baz foo bar baz split foo bar baz blub blah foo bar baz blub blah
|
QA
|
how can search word in word docx file would like to search word file docx for text string some special phrase that could would be found from search within word is there way from python to see the text have no interest in formatting just want to classify documents as having or not having some special phrase
|
ole automation would probably be the easiest you have to consider formatting because the text could look like this in the xml looking for this you phrase you there is no easy way to find that using simple text scan
|
QA
|
debug monitor middleware for python wsgi applications am searching wsgi middleware which can warp around wsgi applications and which let us me monitor incoming and outgoing http requests and header fields something like firefox live headers but for the server side
|
the middleware from wsgiref util import request uri import sys def logging middleware application stream sys stdout def logger environ start response stream write request stream write environ request method request uri environ for name value in environ items if name startswith http stream write name title replace value stream flush def start response code headers stream write response stream write code for data in headers stream write data stream flush start response code headers return application environ start response return logger the test def application environ start response start response ok content type text html return hello world if name main logger logging middleware application from wsgiref simple server import make server httpd make server logger httpd serve forever see also the werkzeug debugger armin wrote it is usefull for interactive debugging
|
QA
|
how can parse comma delimited string into list caveat need to be able to take string like foo bar one two three four into foo bar one two three four have an feeling with hints from python that the solution is going to involve the shlex module
|
it depends how complicated you want to get do you want to allow more than one type of quoting how about escaped quotes your syntax looks very much like the common csv file format which is supported by the python standard library import csv reader csv reader foo bar one two three four skipinitialspace true for in reader print outputs foo bar one two three four hth
|
QA
|
python regex vs php regex no not competition it is instead me trying to find why certain regex works in one but not the other that is my regex and am trying to run it on using pythons regex get nothing using php match it below are the two calls am making just incase it is something to do with that essentially am trying to work out why it works in php but not python re findall regex string preg match all regex string matches solution found it was due to the way that was iterating through the results this regex turned them into groups and then it did not want to print them out in the same way etc etc thank you all for your help it is really appreciated
|
it works for me you must be doing something wrong re match groups do not forget to escape the regex using raw strings regex here as stated in the regex howto
|
QA
|
python regex vs php regex no not competition it is instead me trying to find why certain regex works in one but not the other that is my regex and am trying to run it on using pythons regex get nothing using php match it below are the two calls am making just incase it is something to do with that essentially am trying to work out why it works in php but not python re findall regex string preg match all regex string matches solution found it was due to the way that was iterating through the results this regex turned them into groups and then it did not want to print them out in the same way etc etc thank you all for your help it is really appreciated
|
that regular expression matches here no idea what you are doing wrong import re re compile match sre sre match object at match sre sre match object at match sre sre match object at please note that preg match translates to re search in python and not re match re match is for useful for lexing because it is anchored
|
QA
|
how can search word in word docx file would like to search word file docx for text string some special phrase that could would be found from search within word is there way from python to see the text have no interest in formatting just want to classify documents as having or not having some special phrase
|
in this example course outline docx is word document which does contain the word windows and does not contain the phrase random other string import zipfile zipfile zipfile course outline docx windows in read word document xml true random other string in read word document xml false close basically you just open the docx file which is zip archive using zipfile and find the content in the document xml file in the word folder if you wanted to be more sophisticated you could then parse the xml but if you are just looking for phrase which you know will not be tag then you can just look in the xml for the string
|
QA
|
python regex vs php regex no not competition it is instead me trying to find why certain regex works in one but not the other that is my regex and am trying to run it on using pythons regex get nothing using php match it below are the two calls am making just incase it is something to do with that essentially am trying to work out why it works in php but not python re findall regex string preg match all regex string matches solution found it was due to the way that was iterating through the results this regex turned them into groups and then it did not want to print them out in the same way etc etc thank you all for your help it is really appreciated
|
php uses different flavors of regex while python uses only one do not code in python so make no expert claims on how it uses regex reilly mastering regular expressions is great book as most of their works are
|
QA
|
python regex vs php regex no not competition it is instead me trying to find why certain regex works in one but not the other that is my regex and am trying to run it on using pythons regex get nothing using php match it below are the two calls am making just incase it is something to do with that essentially am trying to work out why it works in php but not python re findall regex string preg match all regex string matches solution found it was due to the way that was iterating through the results this regex turned them into groups and then it did not want to print them out in the same way etc etc thank you all for your help it is really appreciated
|
would suggest that using regex for decimal range validation is not necessarily the correct answer for this problem this is far more readable def valid ip re match if is none return false parts int group for in range if max parts return false return true
|
QA
|
python regex vs php regex no not competition it is instead me trying to find why certain regex works in one but not the other that is my regex and am trying to run it on using pythons regex get nothing using php match it below are the two calls am making just incase it is something to do with that essentially am trying to work out why it works in php but not python re findall regex string preg match all regex string matches solution found it was due to the way that was iterating through the results this regex turned them into groups and then it did not want to print them out in the same way etc etc thank you all for your help it is really appreciated
|
without further details would guess it is quote escaping of some kind both php and python regex objects take strings as arguments these strings will be escaped by the languge before being passed on to the regex engine always using python raw string format when working with regular expressions it ensure that backslashes are not handled in any special way
|
QA
|
how can parse comma delimited string into list caveat need to be able to take string like foo bar one two three four into foo bar one two three four have an feeling with hints from python that the solution is going to involve the shlex module
|
the shlex module solution allows escaped quotes one quote escape another and all fancy stuff she will supports import shlex my splitter shlex shlex foo bar one two three four posix true my splitter whitespace my splitter whitespace split true print list my splitter foo bar one two three four escaped quotes example my splitter shlex shlex test foo bar baz bar xc xa baz posix true my splitter whitespace my splitter whitespace split true print list my splitter test foo bar baz bar xc xa baz
|
QA
|
is there way around coding in python without the tab indent whitespace criteria want to start using python for small projects but the fact that misplaced tab or indent can throw compile error is really getting on my nerves is there some type of setting to turn this off am currently using notepad is there maybe an ide that would take care of the tabs and indenting
|
nope there is no way around it and it is by design from future import braces file stdin line syntaxerror not chance most python programmers simply do not use tabs but use spaces to indent instead that way there is no editor to editor inconsistency
|
QA
|
what is the best dispatcher callback library in python need to allow other python applications to register callback functions for events in my application these need to have priorities associated with them so callback with priority of runs before callback with priority of and callback functions need to be able to signal errors to the dispatcher these are all lightweight callbacks running in the same process so do not need to send signals across process boundaries is there good python library to handle this or do need to write my own
|
are these other applications running in another address space if so you will need to use an interprocess communication library like bus if you are just sending signals in the same process try pydispatcher
|
QA
|
what is the best dispatcher callback library in python need to allow other python applications to register callback functions for events in my application these need to have priorities associated with them so callback with priority of runs before callback with priority of and callback functions need to be able to signal errors to the dispatcher these are all lightweight callbacks running in the same process so do not need to send signals across process boundaries is there good python library to handle this or do need to write my own
|
what platform are you running under gobject is the basis of the gtk gui that is widely used under linux and it supports event loops with prioritizable events like this
|
QA
|
convert mysql timestamp to epoch time in python convert mysql timestamp to epoch time in python is there an easy way to do this
|
if you do not want to have mysql do the work for some reason then you can do this in python easily enough when you get datetime column back from mysqldb you get python datetime datetime object to convert one of these you can use time mktime for example import time connecting to database skipped also closing connection later execute select my datetime field from my table fetchone print time mktime timetuple
|
QA
|
how to start idle python editor without using the shortcut on windows vista am trying to teach komodo to fire up idle when hit the right keystrokes can use the exact path of the shortcut in start menu in the windows explorer location bar to launch idle so was hoping komodo would be able to use it as well but giving this path to komodo causes it to say that is returned this appears to be failure as idle does not start up thought would avoid the shortcut and just use the exact path go to the start menu find the shortcut for idle right click to look at the properties the target is grayed out but says python the start in is set to python the open file location button is also grayed out how do find out where this shortcut is really pointing have tried starting python exe and pythonw exe both in python but neither starts up idle
|
there is file called idle py in your python installation directory in lib idlelib idle py if you run that file with python then idle should start python pythonw exe python lib idlelib idle py
|
QA
|
how to start idle python editor without using the shortcut on windows vista am trying to teach komodo to fire up idle when hit the right keystrokes can use the exact path of the shortcut in start menu in the windows explorer location bar to launch idle so was hoping komodo would be able to use it as well but giving this path to komodo causes it to say that is returned this appears to be failure as idle does not start up thought would avoid the shortcut and just use the exact path go to the start menu find the shortcut for idle right click to look at the properties the target is grayed out but says python the start in is set to python the open file location button is also grayed out how do find out where this shortcut is really pointing have tried starting python exe and pythonw exe both in python but neither starts up idle
|
here is another path you can use am not sure if this is part of the standard distribution or if the file is automatically created on first use of the idle python lib idlelib idle pyw
|
QA
|
can you do linq like queries in language like python or boo take this simple linq query and imagine that db numbers is an sql table with one column number var result from in db numbers where number select number this will run very efficiently in because it generates an sql query something like select number from numbers where number what it does not do is select all the numbers from the database and then filter them in as it might appear to do at first python supports similar syntax result number for in numbers if number but it the if clause here does the filtering on the client side rather than the server side which is much less efficient is there something as efficient as linq in python am currently evaluating python vs ironpython vs boo so an answer that works in any of those languages is fine
|
believe that when ironpython is complete it will have linq support see this thread for some example discussion right now you should be able to write something like queryable select queryable where someinputsequence somepredicate somefuncthatreturnsthesequenceelement something better might have made it into ironpython there is lot of current discussion about how naming conflicts were handled
|
QA
|
using pylint with django would very much like to integrate pylint into the build process for my python projects but have run into one show stopper one of the error types that find extremely useful has no member constantly reports errors when using common django fields for example get user tags class tag has no objects member which is caused by this code def get user tags username gets all the tags that username has used returns query set return tag objects filter this line triggers the error tagownership users username exact username distinct here is the tag class models model is provided by django class tag models model model for user defined strings that help categorize events on on per user basis name models charfield max length null false unique true def unicode self return self name how can tune pylint to properly take fields such as objects into account have also looked into the django source and have been unable to find the implementation of objects so suspect it is not just class field on the other hand am fairly new to python so may very well have overlooked something edit the only way have found to tell pylint to not warn about these warnings is by blocking all errors of the type which is not an acceptable solution since that is in my opinion an extremely useful error if there is another way without augmenting the pylint source please point me to specifics see here for summary of the problems have had with pychecker and pyflakes they have proven to be far to unstable for general use in pychecker case the crashes originated in the pychecker code not source it was loading invoking
|
this is not solution but you can add objects models manager to your django models without changing any behavior myself only use pyflakes primarily due to some dumb defaults in pylint and laziness on my part not wanting to look up how to change the defaults
|
QA
|
how do you use the ellipsis slicing syntax in python this came up in hidden features of python but cannot see good documentation or examples that explain how the feature works
|
you would use it in your own class since no builtin class makes use of it numpy uses it as stated in the documentation some examples here in your own class you would use it like this class testellipsis object def getitem self item if item is ellipsis return returning all items else return return items item testellipsis print return items print returning all items of course there is the python documentation and language reference but those are not very helpful
|
QA
|
how can join list into string caveat along the lines of my previous question how can join list of strings into string such that values get quoted cleanly something like one two three foo bar both into one two three foo bar both suspect that the csv module will come into play here but am not sure how to get the output want
|
using the csv module you can do that way import csv writer csv writer open some csv wb writer writerow the list if you need string just use stringio instance as file stringio stringio writer csv writer writer writerow the list print getvalue the output one two three foo bar both csv will write in way it can read back later you can fine tune its output by defining dialect just set quotechar escapechar etc as needed class somedialect csv excel delimiter quotechar escapechar doublequote false lineterminator quoting csv quote minimal cstringio stringio writer csv writer dialect somedialect writer writerow the list print getvalue the output one two three foo bar both the same dialect can be used with csv module to read the string back later to list
|
QA
|
can you do linq like queries in language like python or boo take this simple linq query and imagine that db numbers is an sql table with one column number var result from in db numbers where number select number this will run very efficiently in because it generates an sql query something like select number from numbers where number what it does not do is select all the numbers from the database and then filter them in as it might appear to do at first python supports similar syntax result number for in numbers if number but it the if clause here does the filtering on the client side rather than the server side which is much less efficient is there something as efficient as linq in python am currently evaluating python vs ironpython vs boo so an answer that works in any of those languages is fine
|
sqlsoup in sqlalchemy gives you the quickest solution in python think if you want clear ish one liner look at the page to see it should be something like result number for in db numbers filter db numbers number all
|
QA
|
how do create non standard type with soappy am calling wsdl web service from python using soappy the call need to make is to the method auth login this has arguments the first string being the api key the second custom type containing username and password the custom type is called auth credentialsdata which contains values as stings one for the username and one for the password how can create this custom type using soappy tried passing list and dictionary none of which work code so far from soappy import wsdl wsdlurl https ws pingdom com soap pingdomapi wsdl client wsdl proxy wsdlurl tried both credentials email example com password client auth login key credentials and credentials username email example com password passsword client auth login key credentials both of which give an authentication failed error
|
the better method is to use the zsi soap module which allows you to take wdsl file and turn it into classes and methods that you can then use to call it the online documentation is on their website but the latest documentation is more easily found in the source package if you install in debian ubuntu package name python zsi the documentation is in usr share doc python zsi in pair of pdfs you can find in there
|
QA
|
how do you use the ellipsis slicing syntax in python this came up in hidden features of python but cannot see good documentation or examples that explain how the feature works
|
the ellipsis is used to slice higher dimensional data structures it is designed to mean at this point insert as many full slices to extend the multi dimensional slice to all dimensions example from numpy import arange arange reshape now you have dimensional matrix of order to select all first elements in the th dimension you can use the ellipsis notation flatten array which is equivalent to flatten array in your own implementations you are free to ignore the contract mentioned above and use it for whatever you see fit
|
QA
|
how do read an excel file into python using xlrd can it read newer office formats my issue is below but would be interested comments from anyone with experience with xlrd just found xlrd and it looks like the perfect solution but am having little problem getting started am attempting to extract data programatically from an excel file pulled from dow jones with current components of the dow jones industrial average link http www djindexes com mdsidx event showaverages when open the file unmodified get nasty biff error binary format not recognized however you can see in this screenshot that excel for mac thinks it is in excel format screenshot http skitch com alok ssa componentreport dji xls properties if instead open it in excel manually and save as excel format explicitly then open in python usig xlrd everything is wonderful remember office thinks the file is already in excel format all files are xls here is pastebin of an ipython session replicating the issue http pastie textmate org private jbawdtrvlrruh mzueqdq any thoughts on how to trick xlrd into recognizing the file so can extract data how to use python to automate the explicit save as format to one that xlrd will accept plan
|
well here is some code that did look down the bottom here not sure about the newer formats if xlrd cannot read it xlrd needs to have new version released
|
QA
|
how can join list into string caveat along the lines of my previous question how can join list of strings into string such that values get quoted cleanly something like one two three foo bar both into one two three foo bar both suspect that the csv module will come into play here but am not sure how to get the output want
|
here is slightly simpler alternative def quote if in or in or in str return repr return we only need to quote value that might have commas or quotes one two three foo bar both print join map quote one two three foo bar both
|
QA
|
what is wrong with my snap to grid code first of all am fairly sure snapping to grid is fairly easy however have run into some odd trouble in this situation and my maths are too weak to work out specifically what is wrong here is the situation have an abstract concept of grid with steps exactly step apart the steps are working fine so ignore them for now the grid is in an abstract coordinate space and to get things to line up have got magic offset in there let us call it offset to snap to the grid have got the following code python def snaptogrid originalpos offset step index int originalpos offset step truncates the remainder away return index gap offset so pass the cursor position offset and step into that function and it returns me the nearest floored position on the grid that appears to work fine in the original scenario however when take into account the fact that the view is scrollable things get little weird scrolling is made as basic as can get it have got viewport that keeps count of the distance scrolled along the axis and just offsets everything that goes through it here is snippet of the cursor mousemotion code def mousemotion self event pixelpos event pos odepos scroll pixelpostoodepos pixelpos self tool positionchanged odepos so there is two things to look at there first the scroll module translation from pixel position to the abstract coordinate space then the tool positionchanged function which takes the abstract coordinate space value and snaps to the nearest step here is the relevant scroll code def pixelpostoodepos pixelpos offsetpixelpos pixelpos self viewportoffset return pixelstoode offsetpixelpos def pixelstoode pixels return float pixels float pixels in an ode unit and the tools update code def positionchanged self newpos self snappedpos snaptogrid originalpos offset step the last relevant chunk is when the tool goes to render itself it goes through the scroll object which transforms the tool snapped coordinate space position into an onscreen pixel position here is the code in tool def render self screen scroll render screen self image self snappedpos in scroll def render self screen image odepos pixelpos self odepostopixelpos odepos screen blit image pixelpos screen is surface from pygame for the curious def odepostopixelpos self odepos offsetpos odepos self viewportoffset return odetopixels offsetpos def odetopixels odeunits return int odeunits pixels in an ode unit whew that was long explanation hope you are still with me the problem am now getting is that when scroll up the drawn image loses alignment with the cursor it starts snapping to the step exactly step below the cursor additionally it appears to phase in and out of allignment at some scrolls it is out by and other scrolls it is spot on it is never out by more than and it is always snapping to valid grid location best guess can come up with is that somewhere am truncating some data in the wrong spot but no idea where or how it ends up with this behavior anyone familiar with coordinate spaces scrolling and snapping
|
do you have typo in positionchanged def positionchanged self newpos self snappedpos snaptogrid newpos offset step guess you are off by one pixel because of the accuracy problems during float division try changing your snaptogrid to this def snaptogrid originalpos offset step eps index int originalpos offset step eps truncates the remainder away return index gap offset
|
QA
|
how to express this bash command in pure python have this line in useful bash script that have not managed to translate into python where is user input number of days worth of files to archive find podcasts current mindepth mtime exec mv podcasts old am familiar with the os name and getpass getuser for the most general cross platform elements also have this function to generate list of the full names of all the files in the equivalent of podcasts current def allfiles filepath depth flist fpath os walk filepath fpath item for item in fpath while depth len fpath for item in fpath depth flist append fpath depth os sep item depth return flist first off there must be better way to do that any suggestion welcome either way for example allfiles users me music itunes itunes music podcasts gives the relevant list on windows presumably should be able to go over this list and call os stat list member st mtime and move all the stuff older than certain number in days to the archive am little stuck on that bit of course anything with the concision of the bash command would also be illuminating
|
that is not bash command it is find command if you really want to port it to python it is possible but you will never be able to write python version that is as concise find has been optimized over years to be excellent at manipulating filesystems while python is general purpose programming language
|
QA
|
is there way to convert indentation in python code to braces am totally blind programmer who would like to learn python unfortunately the fact that code blocks are represented with different levels of indentation is major stumbling block was wondering if there were any tools available that would allow me to write code using braces or some other code block delimiter and then convert that format into properly indented representation that the python interpreter could use
|
personally doubt that there currently is at the moment as lot of the python afficionados love the fact that python is this way whitespace delimited have never actually thought about that as an accessibility issue however maybe it is something to put forward as bug report to python would assume that you use screen reader here however for the output so the tabs would seem invisible to you with braille output it might be easier to read but can understand exactly how confusing this could be in fact this is very interesting to me wish that knew enough to be able to write an app that will do this for you think it is definately something that will put in bug report for unless you have already done so yourself or want to edit also as noted by john millikin there is also pybraces which might be viable solution to you and may be possible to be hacked together dependant on your coding skills to be exactly what you need and hope that if that is the case you release it out for others like yourself to use edit have just reported this to the python bug tracker
|
QA
|
is there way to convert indentation in python code to braces am totally blind programmer who would like to learn python unfortunately the fact that code blocks are represented with different levels of indentation is major stumbling block was wondering if there were any tools available that would allow me to write code using braces or some other code block delimiter and then convert that format into properly indented representation that the python interpreter could use
|
you should be able to configure your editor to speak the tabs and spaces know it is possible to display whitespace in most editors so there must be an accessibility option somewhere to speak them failing that there is pybraces which was written as practical joke but might actually be useful to you with bit of work
|
QA
|
how to express this bash command in pure python have this line in useful bash script that have not managed to translate into python where is user input number of days worth of files to archive find podcasts current mindepth mtime exec mv podcasts old am familiar with the os name and getpass getuser for the most general cross platform elements also have this function to generate list of the full names of all the files in the equivalent of podcasts current def allfiles filepath depth flist fpath os walk filepath fpath item for item in fpath while depth len fpath for item in fpath depth flist append fpath depth os sep item depth return flist first off there must be better way to do that any suggestion welcome either way for example allfiles users me music itunes itunes music podcasts gives the relevant list on windows presumably should be able to go over this list and call os stat list member st mtime and move all the stuff older than certain number in days to the archive am little stuck on that bit of course anything with the concision of the bash command would also be illuminating
|
import os stat os stat test stat st mtime will give you the mtime suggest fixing those in walk results and then recursing calling the function for each dir in walk results
|
QA
|
iron python beautiful soup win app does beautiful soup work with iron python if so with which version of iron python how easy is it to distribute windows desktop app on net using iron python mostly calling some python code for parsing html
|
have not tested it but would say it will most likely work with the latest ipy as for distribution it is very simple use the saveassemblies option to compile your python code down to binary and then ship it with your other dlls and the ipy dependencies
|
QA
|
is there way to convert indentation in python code to braces am totally blind programmer who would like to learn python unfortunately the fact that code blocks are represented with different levels of indentation is major stumbling block was wondering if there were any tools available that would allow me to write code using braces or some other code block delimiter and then convert that format into properly indented representation that the python interpreter could use
|
appreciate your problem but think you are specifying the implementation instead of the problem you need solved instead of converting to braces how about working on way for your screen reader to tell you the indentation level for example some people have worked on vim syntax coloring to represent python indentation levels perhaps modified syntax coloring could produce something your screen reader would read
|
QA
|
iron python beautiful soup win app does beautiful soup work with iron python if so with which version of iron python how easy is it to distribute windows desktop app on net using iron python mostly calling some python code for parsing html
|
if beautifulsoup does not work on ironpython it is because ironpython does not implement the whole python language the same way cpython does beautifulsoup is pure python no extensions so the only problem is the compatibility of ironpython with cpython in terms of python source code there should not be one but if there is the error will be obvious no module named no method named etc google says that only one of bs tests fails with ironpython it probably works and that test may be fixed by now would not know try it out and see would be my advice unless anybody has anything more concrete
|
QA
|
is there way to convert indentation in python code to braces am totally blind programmer who would like to learn python unfortunately the fact that code blocks are represented with different levels of indentation is major stumbling block was wondering if there were any tools available that would allow me to write code using braces or some other code block delimiter and then convert that format into properly indented representation that the python interpreter could use
|
although am not blind have heard good things about emacspeak they have had python mode since their release in they seem to be up to release definitely worth checking out
|
QA
|
iron python beautiful soup win app does beautiful soup work with iron python if so with which version of iron python how easy is it to distribute windows desktop app on net using iron python mostly calling some python code for parsing html
|
have tested and used beautifulsoup with both ipy and forget which beta but this was few months back leave comment if you are still having trouble and will dig out my test code and post it
|
QA
|
is there way to convert indentation in python code to braces am totally blind programmer who would like to learn python unfortunately the fact that code blocks are represented with different levels of indentation is major stumbling block was wondering if there were any tools available that would allow me to write code using braces or some other code block delimiter and then convert that format into properly indented representation that the python interpreter could use
|
python supports braces for defining code blocks and it also supports using begin and end tags please see these code examples class myclass object def myfunction self arg arg for in range arg print and an example with bash style fi endclass enddef endclass done none class myclass object def myfunction self arg arg for in range arg do if then print fi done enddef endclass the best thing about this is is that you can forget to put close bracket in and it is still valid python class myclass object def myfunction self arg arg for in range arg print whoops forgot to close that bracket original gag my real advice is to get braille display if you can afford one source one blind python programmers of my acquaintance really found braille display indispensable for writing python programs it makes the indentation thing much less painful cell display is well worth it
|
QA
|
is there way to convert indentation in python code to braces am totally blind programmer who would like to learn python unfortunately the fact that code blocks are represented with different levels of indentation is major stumbling block was wondering if there were any tools available that would allow me to write code using braces or some other code block delimiter and then convert that format into properly indented representation that the python interpreter could use
|
there is solution to your problem that is distributed with python itself pindent py it is located in the tools scripts directory in windows install my path to it is python tools scripts it looks like you would have grab it from svn python org if you are running on linux or osx it adds comments when blocks are closed or can properly indent code if comments are put in here is an example of the code outputted by pindent with the command pindent myfile py def foobar if elif if end if else print oops end if end def foobar where the original myfile py was def foobar if elif if else print oops you can also use pindent py to insert the correct indentation based on comments read the header of pindent py for details this should allow you to code in python without worrying about indentation would be interested to learn what solution you end up using if you require any further assistance please comment on this post and will try to help
|
QA
|
how to express this bash command in pure python have this line in useful bash script that have not managed to translate into python where is user input number of days worth of files to archive find podcasts current mindepth mtime exec mv podcasts old am familiar with the os name and getpass getuser for the most general cross platform elements also have this function to generate list of the full names of all the files in the equivalent of podcasts current def allfiles filepath depth flist fpath os walk filepath fpath item for item in fpath while depth len fpath for item in fpath depth flist append fpath depth os sep item depth return flist first off there must be better way to do that any suggestion welcome either way for example allfiles users me music itunes itunes music podcasts gives the relevant list on windows presumably should be able to go over this list and call os stat list member st mtime and move all the stuff older than certain number in days to the archive am little stuck on that bit of course anything with the concision of the bash command would also be illuminating
|
import os import shutil from os import path from os path import join getmtime from time import time archive bak current cur def archive old versions days for root dirs files in os walk current for name in files fullname join root name if getmtime fullname time days shutil move fullname join archive name
|
QA
|
how do uninstall python from osx leopard so that can use the macports version want to use the macports version of python instead of the one that comes with leopard
|
have both installed which python usr bin python which python opt local bin python also added the following line to my profile export path opt local bin opt local sbin path
|
QA
|
how do uninstall python from osx leopard so that can use the macports version want to use the macports version of python instead of the one that comes with leopard
|
instead of uninstalling the built in python install the macports version and then modify your path to have the macports version first for example if macports installs usr local bin python then modify your bashrc to include path usr local bin path at the end
|
QA
|
how do uninstall python from osx leopard so that can use the macports version want to use the macports version of python instead of the one that comes with leopard
|
would not uninstall it since many scripts will expect python to be in the usual places when they do not follow convention and use usr bin env python you should simply edit your profile or bash profile so the macports binaries are the first in your path your profile should have this line export path opt local bin opt local sbin path if not add it in and now your she will will search macport bin first and should find macports python before system python
|
QA
|
how do uninstall python from osx leopard so that can use the macports version want to use the macports version of python instead of the one that comes with leopard
|
do not apple ships various system utilities that rely on the system python and particularly the python framework build removing it will cause you problems instead modify your path environ variable in your bash profile to put opt local bin first
|
QA
|
delete all data for kind in google app engine would like to wipe out all data for specific kind in google app engine what is the best way to do this wrote delete script hack but since there is so much data is timeout out after few hundred records
|
the official answer from google is that you have to delete in chunks spread over multiple requests you can use ajax meta refresh or request your url from script until there are no entities left
|
QA
|
what is wrong with my snap to grid code first of all am fairly sure snapping to grid is fairly easy however have run into some odd trouble in this situation and my maths are too weak to work out specifically what is wrong here is the situation have an abstract concept of grid with steps exactly step apart the steps are working fine so ignore them for now the grid is in an abstract coordinate space and to get things to line up have got magic offset in there let us call it offset to snap to the grid have got the following code python def snaptogrid originalpos offset step index int originalpos offset step truncates the remainder away return index gap offset so pass the cursor position offset and step into that function and it returns me the nearest floored position on the grid that appears to work fine in the original scenario however when take into account the fact that the view is scrollable things get little weird scrolling is made as basic as can get it have got viewport that keeps count of the distance scrolled along the axis and just offsets everything that goes through it here is snippet of the cursor mousemotion code def mousemotion self event pixelpos event pos odepos scroll pixelpostoodepos pixelpos self tool positionchanged odepos so there is two things to look at there first the scroll module translation from pixel position to the abstract coordinate space then the tool positionchanged function which takes the abstract coordinate space value and snaps to the nearest step here is the relevant scroll code def pixelpostoodepos pixelpos offsetpixelpos pixelpos self viewportoffset return pixelstoode offsetpixelpos def pixelstoode pixels return float pixels float pixels in an ode unit and the tools update code def positionchanged self newpos self snappedpos snaptogrid originalpos offset step the last relevant chunk is when the tool goes to render itself it goes through the scroll object which transforms the tool snapped coordinate space position into an onscreen pixel position here is the code in tool def render self screen scroll render screen self image self snappedpos in scroll def render self screen image odepos pixelpos self odepostopixelpos odepos screen blit image pixelpos screen is surface from pygame for the curious def odepostopixelpos self odepos offsetpos odepos self viewportoffset return odetopixels offsetpos def odetopixels odeunits return int odeunits pixels in an ode unit whew that was long explanation hope you are still with me the problem am now getting is that when scroll up the drawn image loses alignment with the cursor it starts snapping to the step exactly step below the cursor additionally it appears to phase in and out of allignment at some scrolls it is out by and other scrolls it is spot on it is never out by more than and it is always snapping to valid grid location best guess can come up with is that somewhere am truncating some data in the wrong spot but no idea where or how it ends up with this behavior anyone familiar with coordinate spaces scrolling and snapping
|
thanks for the answer there may be typo but cannot see it unfortunately the change to snaptogrid did not make difference so do not think that is the issue it is not off by one pixel but rather it is off by step playing around with it some more have found that cannot get it to be exact at any point that the screen is scrolled up and also that it happens towards the top of the screen which suspect is ode position zero so am guessing my problem is around small or negative values
|
QA
|
how to express this bash command in pure python have this line in useful bash script that have not managed to translate into python where is user input number of days worth of files to archive find podcasts current mindepth mtime exec mv podcasts old am familiar with the os name and getpass getuser for the most general cross platform elements also have this function to generate list of the full names of all the files in the equivalent of podcasts current def allfiles filepath depth flist fpath os walk filepath fpath item for item in fpath while depth len fpath for item in fpath depth flist append fpath depth os sep item depth return flist first off there must be better way to do that any suggestion welcome either way for example allfiles users me music itunes itunes music podcasts gives the relevant list on windows presumably should be able to go over this list and call os stat list member st mtime and move all the stuff older than certain number in days to the archive am little stuck on that bit of course anything with the concision of the bash command would also be illuminating
|
import subprocess subprocess call find podcasts current mindepth mtime exec mv podcasts old she will true that is not joke this python script will do exactly what the bash one does edit dropped the backslash on the last param because it is not needed
|
QA
|
what is wrong with my snap to grid code first of all am fairly sure snapping to grid is fairly easy however have run into some odd trouble in this situation and my maths are too weak to work out specifically what is wrong here is the situation have an abstract concept of grid with steps exactly step apart the steps are working fine so ignore them for now the grid is in an abstract coordinate space and to get things to line up have got magic offset in there let us call it offset to snap to the grid have got the following code python def snaptogrid originalpos offset step index int originalpos offset step truncates the remainder away return index gap offset so pass the cursor position offset and step into that function and it returns me the nearest floored position on the grid that appears to work fine in the original scenario however when take into account the fact that the view is scrollable things get little weird scrolling is made as basic as can get it have got viewport that keeps count of the distance scrolled along the axis and just offsets everything that goes through it here is snippet of the cursor mousemotion code def mousemotion self event pixelpos event pos odepos scroll pixelpostoodepos pixelpos self tool positionchanged odepos so there is two things to look at there first the scroll module translation from pixel position to the abstract coordinate space then the tool positionchanged function which takes the abstract coordinate space value and snaps to the nearest step here is the relevant scroll code def pixelpostoodepos pixelpos offsetpixelpos pixelpos self viewportoffset return pixelstoode offsetpixelpos def pixelstoode pixels return float pixels float pixels in an ode unit and the tools update code def positionchanged self newpos self snappedpos snaptogrid originalpos offset step the last relevant chunk is when the tool goes to render itself it goes through the scroll object which transforms the tool snapped coordinate space position into an onscreen pixel position here is the code in tool def render self screen scroll render screen self image self snappedpos in scroll def render self screen image odepos pixelpos self odepostopixelpos odepos screen blit image pixelpos screen is surface from pygame for the curious def odepostopixelpos self odepos offsetpos odepos self viewportoffset return odetopixels offsetpos def odetopixels odeunits return int odeunits pixels in an ode unit whew that was long explanation hope you are still with me the problem am now getting is that when scroll up the drawn image loses alignment with the cursor it starts snapping to the step exactly step below the cursor additionally it appears to phase in and out of allignment at some scrolls it is out by and other scrolls it is spot on it is never out by more than and it is always snapping to valid grid location best guess can come up with is that somewhere am truncating some data in the wrong spot but no idea where or how it ends up with this behavior anyone familiar with coordinate spaces scrolling and snapping
|
ok am answering my own question here as alexk mentioned using int to truncate was my mistake the behaviour am after is best modeled by math floor apologies the original question does not contain enough information to really work out what the problem is did not have the extra bit of information at that point with regards to the typo note think may be using the context in confusing manner from the perspective of the positionchanged function the parameter is new position coming in from the perspective of the snaptogrid function the parameter is an original position which is being changed to snapped position the language is like that because part of it is in my event handling code and the other part is in my general services code should have changed it for the example
|
QA
|
adding code to init py am taking look at how the model system in django works and noticed something that do not understand know that you create an empty init py file to specify that the current directory is package and that you can set some variable in init py so that import works properly but django adds bunch of from import statements and defines bunch of classes in init py why does not this just make things look messy is there reason that requires this code in init py
|
all imports in init py are made available when you import the package directory that contains it example dir init py import something test py import dir can now use dir something edit forgot to mention the code in init py runs the first time you import any module from that directory so it is normally good place to put any package level initialisation code edit dgrant pointed out to possible confusion in my example in init py import something can import any module not necessary from the package for example we can replace it with import datetime then in our top level test py both of these snippets will work import dir print dir datetime datetime now and import dir some module in dir print dir datetime datetime now the bottom line is all names assigned in init py be it imported modules functions or classes are automatically available in the package namespace whenever you import the package or module in the package
|
QA
|
is it good to switch from to python currently am developing in the net environment using but want to know whether it is worth learning python am thinking of learning the django framework what is better
|
depends on what you will use it for if you are making enterprise windows forms applications do not think switching to python would be good idea also it is possible to still use python on the net clr with ironpython
|
QA
|
is it good to switch from to python currently am developing in the net environment using but want to know whether it is worth learning python am thinking of learning the django framework what is better
|
both are useful for different purposes is pretty good all rounder python dynamic nature makes it more suitable for rad experiences such as site building do not think your career will suffer if you were competant in both to get going with python consider an ide with python support such as eclipse pydev or activeide komodo found subscription to safari bookshelf online really invaluable too
|
QA
|
is it good to switch from to python currently am developing in the net environment using but want to know whether it is worth learning python am thinking of learning the django framework what is better
|
what is better is inherently subjective if you like python syntax learn it it will probably be harder to find python job and net in general seem to be more popular but this may change also think it is worth to know at least one scripting language even if your main job does not require it python is not bad candidate
|
QA
|
is it good to switch from to python currently am developing in the net environment using but want to know whether it is worth learning python am thinking of learning the django framework what is better
|
personally feel you can write good bad code in any language also firmly believe in learning new language every so often for the sake of learning itself on those grounds say if you have the time just go for it python is great language that many others are inspired from whether one framework or language is better or not depends on your definition of better do you want more work as programmer do you want to develop business apps quickly or do you want to compute matrix transformations once you have answered those questions you might find yourself taking completely different direction say if you had particular interest in the financial or scientific sector
|
QA
|
is it good to switch from to python currently am developing in the net environment using but want to know whether it is worth learning python am thinking of learning the django framework what is better
|
it cannot hurt to learn python especially considering some of the heavy weights google are really getting behind it as for the actual use it all depends on the application use the best tool for the job
|
QA
|
is it good to switch from to python currently am developing in the net environment using but want to know whether it is worth learning python am thinking of learning the django framework what is better
|
yes you should learn python but it has nothing to do with python or being better it is really about making you better programmer learning python will give you whole new perspective on programmer and how problems can be solved it is like lifting weights except you are building up the developer muscles in your mind for example if you have only ever programmed using statically typed language then it is hard to imagine any other way learning python will teach you that there is an alternative in the form of dynamic typing for summary of pythons benefits http www cmswire com cms enterprise programming language of the year is php
|
QA
|
adding code to init py am taking look at how the model system in django works and noticed something that do not understand know that you create an empty init py file to specify that the current directory is package and that you can set some variable in init py so that import works properly but django adds bunch of from import statements and defines bunch of classes in init py why does not this just make things look messy is there reason that requires this code in init py
|
it is just personal preference really and has to do with the layout of your python modules let us say you have module called erikutils there are two ways that it can be module either you have file called erikutils py on your sys path or you have directory called erikutils on your sys path with an empty init py file inside it then let us say you have bunch of modules called fileutils procutils parseutils and you want those to be sub modules under erikutils so you make some py files called fileutils py procutils py and parseutils py erikutils init py fileutils py procutils py parseutils py maybe you have few functions that just do not belong in the fileutils procutils or parseutils modules and let us say you do not feel like creating new module called miscutils and you would like to be able to call the function like so erikutils foo erikutils bar rather than doing erikutils miscutils foo erikutils miscutils bar so because the erikutils module is directory not file we have to define it is functions inside the init py file in django the best example can think of is django db models fields all the django field classes are defined in the init py file in the django db models fields directory guess they did this because they did not want to cram everything into hypothetical django db models fields py model so they split it out into few submodules related py files py for example and they stuck the made field definitions in the fields module itself hence init py
|
QA
|
is it good to switch from to python currently am developing in the net environment using but want to know whether it is worth learning python am thinking of learning the django framework what is better
|
never stop learning that said how can you compare the two how good is python support in net is there support in google app engine it really depends what your target system is therefore the more languages you have the better equipped you will be to tackle different challenges
|
QA
|
time length of an mp file what is the simplest way to determine the length in seconds of given mp file without using outside libraries python source highly appreciated
|
you can use pymad it is an external library but do not fall for the not invented here trap any particular reason you do not want any external libraries import mad mf mad madfile foo mp track length in milliseconds mf total time spotted here if you really do not want to use an external library have look here and check out how he is done it warning it is complicated
|
QA
|
time length of an mp file what is the simplest way to determine the length in seconds of given mp file without using outside libraries python source highly appreciated
|
you might count the number of frames in the file each frame has start code although cannot recollect the exact value of the start code and do not have mpeg specs laying around each frame has certain length around ms for mpeg layer ii this method works for cbr files constant bit rate how vbr files work is completely different story from the document below for layer files us this formula framelengthinbytes bitrate samplerate padding for layer ii iii files use this formula framelengthinbytes bitrate samplerate padding information about mpeg audio frame header
|
QA
|
tabs versus spaces in python programming have always used tabs for indentation when do python programming but then came across question here on so where someone pointed out that most python programmers use spaces instead of tabs to minimize editor to editor mistakes how does that make difference are there other reasons why one would use spaces instead of tabs for python or is it simply not true should switch my editor to insert spaces instead of tabs right away or keep on going like used to
|
because pep tells us to use spaces
|
QA
|
tabs versus spaces in python programming have always used tabs for indentation when do python programming but then came across question here on so where someone pointed out that most python programmers use spaces instead of tabs to minimize editor to editor mistakes how does that make difference are there other reasons why one would use spaces instead of tabs for python or is it simply not true should switch my editor to insert spaces instead of tabs right away or keep on going like used to
|
recently came across an article titled python myths about indentation which discusses this and related questions the article has good reasons for recommending the use of spaces when writing python code but there is certainly room for disagreement believe it is true that most python programmers use spaces only
|
QA
|
tabs versus spaces in python programming have always used tabs for indentation when do python programming but then came across question here on so where someone pointed out that most python programmers use spaces instead of tabs to minimize editor to editor mistakes how does that make difference are there other reasons why one would use spaces instead of tabs for python or is it simply not true should switch my editor to insert spaces instead of tabs right away or keep on going like used to
|
the most pythonic way is to use spaces per indentation level the python interpreter will however recognize spaces or tabs the only gottcha is you must never mix spaces and tabs pick one or the other that said the specification recommends spaces most developers use spaces so unless you have really good reason not to would say go with spaces
|
QA
|
time length of an mp file what is the simplest way to determine the length in seconds of given mp file without using outside libraries python source highly appreciated
|
simple parse mp binary blob to calculate something in python that sounds like pretty tall order do not know python but here is some code have refactored from another program once tried to write note it is in sorry it is what have got also as is it will only handle constant bit rate mpeg audio layer files that should cover most but cannot make any guarantee as to this working in all situations hopefully this does what you want and hopefully refactoring it into python is easier than doing it from scratch determines the duration in seconds of an mp assumes mpeg not or audio layer not or constant bit rate not variable include iostream include fstream include cstdlib using namespace std bitrates assuming mpeg audio layer const int bitrates intel processors are little endian search google or see http en wikipedia org wiki endian int reverse int int toreturn toreturn ff toreturn ff toreturn ff toreturn xff return toreturn in short data in id tags are stored as syncsafe integers this is so the tag info is not mistaken for audio data and attempted to be played for more info have fun googling it int syncsafe int int toreturn toreturn toreturn toreturn toreturn return toreturn how much room does id version tag info take up at the end of this file if any int id size ifstream infile streampos savepos infile tellg get to bytes from file end infile seekg ios end streampos length infile tellg streampos infile seekg length int size char buffer infile read buffer if buffer buffer buffer size found tag data else size nothing there infile seekg savepos return size how much room does id version tag info take up at the beginning of this file if any int id size ifstream infile streampos savepos infile tellg infile seekg ios beg char buffer infile read buffer if buffer buffer would buffer no tag data infile seekg savepos return int size infile read reinterpret cast char size sizeof size size syncsafe size infile seekg savepos size does not include the byte id header return size int main int argcount char argvalues you will have to change this ifstream infile music bush comedown mp ios binary if infile is open infile close cout error opening file endl system pause return determine beginning and end of primary frame data not id tags infile seekg ios end streampos dataend infile tellg infile seekg ios beg streampos databegin dataend id size infile databegin id size infile infile seekg databegin ios beg determine bitrate based on header for first frame of audio data int headerbytes infile read reinterpret cast char headerbytes sizeof headerbytes headerbytes reverse headerbytes int bitrate bitrates int headerbytes xf calculate duration in seconds int duration dataend databegin bitrate infile close print duration in minutes seconds cout duration duration endl system pause return
|
QA
|
find matching sequences in two binary files let me start off with bit of background this morning one of our users reported that testuff setup file has been reported as infected with virus by the ca antivirus confident that this was false positive looked on the web and found that users of another program spybot have reported the same problem now for the actual question assuming the antivirus is looking for specific binary signature in the file would like to find the matching sequences in both files and hopefully find way to tweak the setup script to prevent that sequence from appearing tried the following in python but it is been running for long time now and was wondering if there was better or faster way from difflib import sequencematcher spybot open spybotsd exe rb read testuff open testuffsetup exe rb read sequencematcher none spybot testuff print find longest match len spybot len testuff is there better library for python or for another language that can do this completely different way to tackle the problem is welcome as well
|
why do not you contact ca and ask them to tell them what they are searching for for that virus or you could copy the file and change each individual byte until the warning disappeared may take while depending on the size it is possible the virus detection may be lot more complicated than simply looking for fixed string
|
QA
|
tabs versus spaces in python programming have always used tabs for indentation when do python programming but then came across question here on so where someone pointed out that most python programmers use spaces instead of tabs to minimize editor to editor mistakes how does that make difference are there other reasons why one would use spaces instead of tabs for python or is it simply not true should switch my editor to insert spaces instead of tabs right away or keep on going like used to
|
editor to editor mistake occurs when you have mixed indentation within file this arises as follows block of code is indented with spaces and then one indentation level in it is indented with tabs now the heathen who did this mixing tabs and spaces had it so his tabs are also spaces so he sees no problems and python sees no problems now our victim comes along later and he has his tabs set to spaces now our victims thinks the code looks all whacked and fixes it by removing one level of indentation which now makes the code look like it is still levels of indentation but is really one level at this point all hell breaks loose the lesson here is that you should never ever mix tabs and spaces if you keep to this then it is easy to reindent your code into spaces or tabs regardless of which you personally use the best way to ensure you do not mix tabs and spaces is to always run python with tt which will produce an error when tabs and spaces are mixed as for tabs and spaces personally use tabs so separate indentation from appearance it is much easier to change the appearance of code when it is indented with tabs than it is with spaces know this runs contrary to what of python programmers do but that is my personal preference and it is easy in any case to convert tabbed file to spaced one the reverse is not always true since you can accidentally whack out spaces in strings etc
|
QA
|
find matching sequences in two binary files let me start off with bit of background this morning one of our users reported that testuff setup file has been reported as infected with virus by the ca antivirus confident that this was false positive looked on the web and found that users of another program spybot have reported the same problem now for the actual question assuming the antivirus is looking for specific binary signature in the file would like to find the matching sequences in both files and hopefully find way to tweak the setup script to prevent that sequence from appearing tried the following in python but it is been running for long time now and was wondering if there was better or faster way from difflib import sequencematcher spybot open spybotsd exe rb read testuff open testuffsetup exe rb read sequencematcher none spybot testuff print find longest match len spybot len testuff is there better library for python or for another language that can do this completely different way to tackle the problem is welcome as well
|
hey better not wonder about the complexity and time these kinds of algorithms need if you have interest in this here ps document linked here you can find good introduction into this thematic if good implementation for these algorithms exist can not tell maybe use google to find some or put new topic on stackoverflow regards
|
QA
|
tabs versus spaces in python programming have always used tabs for indentation when do python programming but then came across question here on so where someone pointed out that most python programmers use spaces instead of tabs to minimize editor to editor mistakes how does that make difference are there other reasons why one would use spaces instead of tabs for python or is it simply not true should switch my editor to insert spaces instead of tabs right away or keep on going like used to
|
you can mix tabs and spaces but tab is considered to be the same indentation as spaces so unless your editor is set up to consider tab to be spaces you are asking for trouble when mixing them
|
QA
|
find matching sequences in two binary files let me start off with bit of background this morning one of our users reported that testuff setup file has been reported as infected with virus by the ca antivirus confident that this was false positive looked on the web and found that users of another program spybot have reported the same problem now for the actual question assuming the antivirus is looking for specific binary signature in the file would like to find the matching sequences in both files and hopefully find way to tweak the setup script to prevent that sequence from appearing tried the following in python but it is been running for long time now and was wondering if there was better or faster way from difflib import sequencematcher spybot open spybotsd exe rb read testuff open testuffsetup exe rb read sequencematcher none spybot testuff print find longest match len spybot len testuff is there better library for python or for another language that can do this completely different way to tackle the problem is welcome as well
|
see the longest common substring problem guess difflib uses the dp solution which is certainly too slow to compare executables you can do much better with suffix trees arrays using perl tree suffix might be easiest solution apparently it gives all common substrings in specified length range lcs tree lcs lcs tree lcs min len max len lcs tree longest common substrings
|
QA
|
parse dicom files in native python what is the simplest and most pythonic way to parse dicom file native python implementation without the use of non python libraries would be much preferred dicom is the standard file format in digital medical imaging look here for more information there are some libraries that support reading subset of dicom files two or three of them even have python bindings native python parser would serve two purposes for me no need to build any external libraries learn about the dicom file format
|
wonder what the original poster tried and which methods worked and not worked for him have never worked with dicom but quick google search for dicom python gave several interesting results it seems that this project http www creatis univ lyon fr public gdcm should deliver what you want it has python bindings and pretty active mailing list
|
QA
|
find matching sequences in two binary files let me start off with bit of background this morning one of our users reported that testuff setup file has been reported as infected with virus by the ca antivirus confident that this was false positive looked on the web and found that users of another program spybot have reported the same problem now for the actual question assuming the antivirus is looking for specific binary signature in the file would like to find the matching sequences in both files and hopefully find way to tweak the setup script to prevent that sequence from appearing tried the following in python but it is been running for long time now and was wondering if there was better or faster way from difflib import sequencematcher spybot open spybotsd exe rb read testuff open testuffsetup exe rb read sequencematcher none spybot testuff print find longest match len spybot len testuff is there better library for python or for another language that can do this completely different way to tackle the problem is welcome as well
|
note that even if you did find it this way there is no guarantee that the longest match is actually the one being looked for instead you may find common initialisation code or string tables added by the same compiler for instance
|
QA
|
using kwargs with simplexmlrpcserver in python have class that wish to expose as remote service using pythons simplexmlrpcserver the server startup looks like this server simplexmlrpcserver serversettings listen ip serversettings listen port service service server register instance service server serve forever then have serviceremote class that looks like this def init self ip port self rpcclient xmlrpclib server http ip port def getattr self name forward all calls to the rpc client return getattr self rpcclient name so all calls on the serviceremote object will be forwarded to xmlrpclib server which then forwards it to the remote server the problem is method in the service that takes named varargs usedb def select self db fields kwargs pass the usedb decorator wraps the function creating the db before the call and opening it then closing it after the call is done before returning the result when call this method get the error call got an unexpected keyword argument name so is it possible to call methods taking variable named arguments remotely or will have to create an override for each method variation need thanks for the responses changed my code around bit so the question is no longer an issue however now know this for future reference if indeed do need to implement positional arguments and support remote invocation think combination of thomas and praptaks approaches would be good turning kwargs into positional args on the client through xmlrpclient and having wrapper on methods serverside to unpack positional arguments
|
as far as know the underlying protocol does not support named varargs or any named args for that matter the workaround for this is to create wrapper that will take the kwargs and pass it as an ordinary dictionary to the method you want to call something like this server side def select wrapper self db fields kwargs accepts an ordinary dict which can pass through xmlrpc return select self db fields kwargs on the client side def select self db fields kwargs you can call it with keyword arguments and they will be packed into dict return self rpcclient select wrapper self db fields kwargs disclaimer the code shows the general idea you can do it bit cleaner for example writing decorator to do that
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.