Can't uninstall wxPython
I have two versions of wxPython installed on my Mac (OS X Tiger). One is version 2.6.1.0 and the other is version 2.6.0.0. I want to keep the newer version, but I can't seem to uninstall either one using the uninstall_wxPython.py script. When I run that script, I get this error message: $ sudo: uninstall_wxPython.py: command not found Is there any way I could delete one, or both, of these installations manually? For some reason, whenever I try to run a wxPython script, it uses the older version of wxPython and it doesn't always run correctly. Thanks in advance. Justin -- http://mail.python.org/mailman/listinfo/python-list
missing cephes module
When I used py2exe to create executable file, "cephes" module missing error occurred. I have installed python 2.3 and scientific and numeric python. Can anybody suggest me how to resolve the problem? Justin__Do You Yahoo!?Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -- http://mail.python.org/mailman/listinfo/python-list
missing cephes module
Hi All: When I used py2exe to create executable file, "cephes" module missing error occurred. I have installed python 2.3 and scientific and numeric python. Can anybody suggest me how to resolve the problem? Justin Yahoo! Mail Mobile Take Yahoo! Mail with you! Check email on your mobile phone.-- http://mail.python.org/mailman/listinfo/python-list
Re: Asychronous execution *with* return codes?
If you're on a POSIX system, you could use the usual fork/exec/wait: import os for lstArgs in pileOflstArgs: pid = os.fork() if not pid: os.execv( app, lstArgs ) for i in range(len(pileOflstArgs)): pid, status = os.wait() Of couse, os.wait() will block until a child exits. Look at the docs for the status code it returns, though, as it's not just the return value of the process. On Oct 5, 7:43 am, "utabintarbo" <[EMAIL PROTECTED]> wrote: > MonkeeSage wrote: > > utabintarbo wrote: > > > pid = subprocess.Popen([app] + lstArgs).pid > > > Check out the poll() method and the returncode attribute: > >http://docs.python.org/lib/node533.htmlThanks for the reply. > > If I understand your meaning, I should do something like this (given I > wish to run an app against several arguments [my use case]): > > for lstArgs in pileOflstArgs: > uniqueProcessID = subprocess.Popen([app] + lstArgs) > pid = uniqueProcessID.pid > retcode = uniqueProcessID.poll() > # increment uniqueProcessID > > > If so, how do I handle the poll() on long-running processes? Run a > bunch and then start a check loop? Am I asking too many questions? -- http://mail.python.org/mailman/listinfo/python-list
How can I catch segmentation fault in python?
Hi all, I am calling a program written in C inside Python using ctypes, and it seems that sometimes the program in C crashes while it's being used in Python. Even under the circumstances, I want to get the Python program going by handling the segmentation fault. I've already searched the Internet, but couldn't get the right answer to catch them. Could any of you please let me know how to deal with this and catch the segmentation fault in Python? Thanks, Justin. -- http://mail.python.org/mailman/listinfo/python-list
Re: How can I catch segmentation fault in python?
On Nov 17, 1:06 am, John Nagle wrote: > On 11/16/2010 10:15 PM, swapnil wrote: > > > > > > > On Nov 17, 10:26 am, justin wrote: > >> Hi all, > > >> I am calling a program written in C inside Python using ctypes, > >> and it seems that sometimes the program in C crashes while it's being > >> used in Python. > >> Even under the circumstances, I want to get the Python program going > >> by handling the segmentation fault. > > >> I've already searched the Internet, but couldn't get the right answer > >> to catch them. > >> Could any of you please let me know how to deal with this and catch > >> the segmentation fault in Python? > > >> Thanks, > >> Justin. > > > Segmentation fault isn't exactly an exception that you can catch. It > > usually means something has gone horribly wrong, like dereferencing > > invalid pointer, trying to access memory out of process's range. Since > > if you run out of memory Python simply raises MemoryError exception, > > which you can catch. So that is not the case for segmentation fault. > > Either fix the program so it doesn't crash,or run the offending > module and the C code in a subprocess. > > John Nagle Thanks guys for this fast replies, Turns out that it is a fact that segmentation fault is not what I can deal with in programming level. But the problem is that the code is not mine, and it takes over a day for me to get the point where the segmentation fault occurred. Plus, it seems that the point is not deterministic Still, I think I should at least try to figure out exactly at which point the segmentation fault occurs, and think where to go from there according to your kind advice. Again many thanks, Justin. -- http://mail.python.org/mailman/listinfo/python-list
Re: How can I catch segmentation fault in python?
Just checked what is valgrind, sounds promising. Let me try that. Thanks a lot, Justin. On Nov 17, 9:47 am, Wolfgang Rohdewald wrote: > On Mittwoch 17 November 2010, Wolfgang Rohdewald wrote: > > > On Mittwoch 17 November 2010, justin wrote: > > > But the problem is that the code is not mine, and it takes > > > over a day for me to get the point where the segmentation > > > fault occurred. Plus, it seems that the point is not > > > deterministic > > > > Still, I think I should at least try to figure out exactly > > > at which point the segmentation fault occurs, and think > > > where to go from there according to your kind advice. > > > try valgrind > > hit the send button too fast... > > even if the segmentation fault only happens after a long time > valgrind might find problems much sooner, and fixing them > might remove the segmentation fault. > > -- > Wolfgang -- http://mail.python.org/mailman/listinfo/python-list
How to populate all possible hierarchical clusterings from a set of elements?
The title sounds too complex, but my question is actually simple. Suppose I have [1,2,3,4,5], then there are many ways of making clustering. Among them, I want to pair up terminals until there is only one left at the end. For example, 1,2),3),4),5), (1,(2,(3,(4,5, or (((1,2),(3,4)), 5) would be legitimate ones. How do you think can I, using the modules of Python such as itertools as much as possible, make all possible such clusterings? Thanks in advance, Justin. -- http://mail.python.org/mailman/listinfo/python-list
list 'results' from maps.google then crawl
list 'results' from maps.google then crawl through the (engine of some sort) space to the 'results' website and look at it html to find the contact -- http://mail.python.org/mailman/listinfo/python-list
Flowcharting in Python?
Hi guys, Does anyone know of any code or projects around that are written in Python or can be used by Python to write a flowcharting application? I haven't been able to find any, but the closest thing I have come across is FlowchartPython which allows you to code in Python from flowcharts, which isn't what I want; something more like Microsoft Visio. I'm beginning to think I'll have to create something from scratch. Thanks. :) -- http://mail.python.org/mailman/listinfo/python-list
numpy is not installed with Python2.
My university has a cluster computer, on which I want to run my python program that uses numpy. I am installing my Python2.7 locally separated from the main system, and trying to install numpy, attach it with Python2.7. I used many different versions of numpys to make it happen, but I got stuck with the same following error on every trial, "[...@login1 numpy]$ python2.7 setup.py install Running from numpy source directory.Traceback (most recent call last): File "setup.py", line 210, in setup_package() File "setup.py", line 187, in setup_package from numpy.distutils.core import setup File "/users/hp6/DOWN/numpy/numpy/distutils/core.py", line 25, in from numpy.distutils.command import config, config_compiler, \ File "/users/hp6/DOWN/numpy/numpy/distutils/command/build_ext.py", line 9, in from distutils.command.build_ext import build_ext as old_build_ext File "/users/hp6/apps/python27/lib/python2.7/distutils/command/ build_ext.py", line 13, in from site import USER_BASE, USER_SITE ImportError: cannot import name USER_BASE" It seems the error is related to the inability of Python2.7 to process "from site import USER_BASE, USER_SITE", since the machine I succeeded to install numpy with Python2.7 doesn't prompt an error from this command, whereas this machine in which I failed to do so cannot handle this. My question is: How can I make Python2.7 to process this, since the manual says this package is the one that's automatically turned on in startup. Thanks, Justin. -- http://mail.python.org/mailman/listinfo/python-list
Re: numpy is not installed with Python2.
On Aug 27, 12:10 pm, Robert Kern wrote: > On 8/27/10 11:40 AM, justin wrote: > > > > > > > My university has a cluster computer, on which I want to run my python > > program that uses numpy. > > I am installing my Python2.7 locally separated from the main system, > > and trying to install numpy, attach it with Python2.7. > > I used many different versions of numpys to make it happen, but I got > > stuck with the same following error on every trial, > > > "[...@login1 numpy]$ python2.7 setup.py install > > Running from numpy source directory.Traceback (most recent call last): > > File "setup.py", line 210, in > > setup_package() > > File "setup.py", line 187, in setup_package > > from numpy.distutils.core import setup > > File "/users/hp6/DOWN/numpy/numpy/distutils/core.py", line 25, in > > > > from numpy.distutils.command import config, config_compiler, \ > > File "/users/hp6/DOWN/numpy/numpy/distutils/command/build_ext.py", > > line 9, in > > from distutils.command.build_ext import build_ext as old_build_ext > > File "/users/hp6/apps/python27/lib/python2.7/distutils/command/ > > build_ext.py", line 13, in > > from site import USER_BASE, USER_SITE > > ImportError: cannot import name USER_BASE" > > > It seems the error is related to the inability of Python2.7 to process > > "from site import USER_BASE, USER_SITE", > > since the machine I succeeded to install numpy with Python2.7 doesn't > > prompt an error from this command, > > whereas this machine in which I failed to do so cannot handle this. > > Your Python installation appears to be broken. Find the site.py module that > you > are actually importing. I.e. from the numpy source directory: > > $ python2.7 -c "import site; print site.__file__" > > This will tell you the site.pyc file that actually gets imported. Find the > associated site.py file (it should be in the same directory) and check to see > if > it has USER_BASE defined. The filename should be > > /users/hp6/apps/python27/lib/python2.7/site.pyc > > If it isn't, that may be the source of your problem. > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > that is made terrible by our own mad attempt to interpret it as though it > had > an underlying truth." > -- Umberto Eco Dear Kern, Thanks a lot. Your quick and detailed comment saves me a lot of time and effort now. It seems the file path links are out of order as you diagnosed. Like you said, there is a site.py on /users/hp6/apps/python27/lib/ python2.7/. But when I typed in "$ python2.7 -c "import site; print site.__file__", it refers to another place: "/opt/apps/gurobi/3.0.0/linux64/lib/python2.5/site.pyc", and it doesn't have USER_BASE! So I changed the value of PYTHONPATH accordingly. Thanks again, Justin. -- http://mail.python.org/mailman/listinfo/python-list
AMQP listening and user-facing daemon
Hi all, What is the best approach to writing a concurrent daemon that can execute callbacks for different types of events (AMQP messages, parsed output of a subprocess, HTTP requests)? I am considering [twisted][1], the built-in [threading][2] module, and [greenlet][3]. I must admit that I am very unfamiliar with concurrent programming and Python programming in general (formerly a data analysis driven procedural programmer). Any resources on threaded/concurrent programming (specifically daemons...not just multi-threading a single task) would be much appreciated. Thank you. Details: 1) Listens into AMQP messaging queues and executes callbacks when messages arrive. Example: Immediately after startup, the daemon continuously listens to the [Openstack Notifications messaging queue][4]. When a virtual machine is launched, a notification is generated by Openstack with the hostname, IP address, etc. The daemon should read this message and write some info to a log (or POST the info to a server, or notify the user...something simple). 2) Parse the output of a subprocess and execute callbacks based on the output. Example: Every 30 seconds, a system command "[qstat][5]" is run to query a job resource manager (e.g. TORQUE). Similar callbacks to 1). 3) Receive requests from a user and process them. I think this will be via WSGI HTTP. Example: User submits an XML template with virtual machine templates. The daemon does some simple XML parsing and writes a job script for the job resource manager. The job is submitted to the resource manager and the daemon continually checks for the status of the job with "qstat" and for messages from AMQP. It should return "live" feedback to the user and write to a log. [1]: https://twistedmatrix.com/trac/wiki/Documentation [2]: http://docs.python.org/2/library/threading.html [3]: http://greenlet.readthedocs.org/en/latest/ [4]: https://wiki.openstack.org/wiki/NotificationEventExamples#Immediate_Notifications: [5]: http://www.clusterresources.com/torquedocs21/commands/qstat.shtml Justin ChiuTRIUMF -- http://mail.python.org/mailman/listinfo/python-list
AMQP listening and user-facing daemon
Hi all, What is the best approach to writing a concurrent daemon that can execute callbacks for different types of events (AMQP messages, parsed output of a subprocess, HTTP requests)? I am considering [twisted][1], the built-in [threading][2] module, and [greenlet][3]. I must admit that I am very unfamiliar with concurrent programming and Python programming in general (formerly a data analysis driven procedural programmer). Any resources on threaded/concurrent programming (specifically daemons...not just multi-threading a single task) would be much appreciated. Thank you. Details: 1) Listens into AMQP messaging queues and executes callbacks when messages arrive. Example: Immediately after startup, the daemon continuously listens to the [Openstack Notifications messaging queue][4]. When a virtual machine is launched, a notification is generated by Openstack with the hostname, IP address, etc. The daemon should read this message and write some info to a log (or POST the info to a server, or notify the user...something simple). 2) Parse the output of a subprocess and execute callbacks based on the output. Example: Every 30 seconds, a system command "[qstat][5]" is run to query a job resource manager (e.g. TORQUE). Similar callbacks to 1). 3) Receive requests from a user and process them. I think this will be via WSGI HTTP. Example: User submits an XML template with virtual machine templates. The daemon does some simple XML parsing and writes a job script for the job resource manager. The job is submitted to the resource manager and the daemon continually checks for the status of the job with "qstat" and for messages from AMQP. It should return "live" feedback to the user and write to a log. [1]: https://twistedmatrix.com/trac/wiki/Documentation [2]: http://docs.python.org/2/library/threading.html [3]: http://greenlet.readthedocs.org/en/latest/ [4]: https://wiki.openstack.org/wiki/NotificationEventExamples#Immediate_Notifications: [5]: http://www.clusterresources.com/torquedocs21/commands/qstat.shtml Justin ChiuTRIUMF -- http://mail.python.org/mailman/listinfo/python-list
Re: [newbie] problem with data (different behaviour between batch and interactive use)
When you are reading it in measurement is a string. The indicies of the string are going to be returned in your print statements. Similar to having done this in the interpreter: In [17]: measurement = '+3.874693E01,+9.999889E03,+9.91E+37,+1.876595E+04,+3.994000E+04' In [18]: measurement[1] Out[18]: '3' In [19]: measurement[0] Out[19]: '+' You need to split up your string and convert to floats. measurement = map(float, serkeith.readline().replace('\x11','').replace('\x13','').replace('\x0d','\n').split(',')) Something like that should work... to test in interpreter do the following : measurement = map(float, '+3.874693E01,+9.999889E03,+9.91E+37,+1.876595E+04,+3.994000E+04'.split(',')) In [24]: measurement[0] Out[24]: 38.74693 -- http://mail.python.org/mailman/listinfo/python-list
Re: retry many times decorator
On Friday, June 29, 2012 4:53:43 AM UTC-4, andrea crotti wrote: > On the other hand now that I think again even supposing there is a > permanent error like MySql completely down, retrying continuosly > won't do any harm anyway because the machine will not be able to do > anything else anyway, when someone will fix MySql it would > restart again without human intervention. > > So I think I could even just let it retry and use maybe a SMTPHanlder > for the logging errors, to make the notification of problems very > quick.. Rather then write a decorator, sounds like you should write your own class or method connecting to the database that has the ability to retry. Are you finding you are decorating only db calls or are you decorating all sorts of stuff? -- http://mail.python.org/mailman/listinfo/python-list
Re: from calendar import* doesn't import everything
see http://docs.python.org/tutorial/modules.html#importing-from-a-package http://stackoverflow.com/questions/2187583/whats-the-python-all-module-level-variable-for I know the 1st link is for importing from a package but the same applies for modules -- http://mail.python.org/mailman/listinfo/python-list
send function keys to a legacy DOS program
Greetings, We have an old barcode program (MSDOS and source code unavailable.) I've figured out how to populate the fields (by hacking into one of the program's resource files.) However, we still need to hit the following function keys in sequence. F5, F2, F7 Is there a way to pipe said keys into the program? I know it's not really a python problem but I got nowhere else to go. I've tried other barcode solutions but none give the same output. -- http://mail.python.org/mailman/listinfo/python-list
Re: send function keys to a legacy DOS program
On Mar 20, 7:30 am, Alexander Gattin wrote: > On Sun, Mar 20, 2011 at 12:52:28AM +0200, > > You need to place 2 bytes into the circular buffer > to simulate key press. Lower byte is ASCII code, > higher byte is scan code (they are the same for > functional keys, whe using default keycode set#1): > > F5: 0x3F 0x3F > F2: 0x3C 0x3C > F7: 0x41 0x41 > > -- > With best regards, > xrgtn looks promising. will give this a try. thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: send function keys to a legacy DOS program
On Tue, Mar 29, 2011 at 9:59 PM, Alexander Gattin wrote: > I'm not sure regarding the ASCII part. I think it > might need to be set to 0x00 for all functional > keys instead of 0x3F/0x3C/0x41, but probably no > application actually cares. > > Another thing is that you may need to send key > release after key press in order for the > application to trigger the F5/F2/F7 event. I'm not > sure what the scan codes for F5/F2/F7 releases > are, but think that they may be: > > F5: 0xBF > F2: 0xBC > F7: 0xC1 > > -- > With best regards, > xrgtn > appreciate all the help. unfortunately, my hard drive crashed and badly. thus was unable to investigate this further. as I was running out of time, we're now going for a reimplementation of the legacy barcode program. was fortunate to find an implementation that gives the same output (we're testing thoroughly and we may have found a winner) oh btw, it was a seagate 250GB drive for my dell laptop may need to pay somebody to try to recover my personal files. all work files are in version control so they're ok -- http://mail.python.org/mailman/listinfo/python-list
Re: The Incredible Growth of Python (stackoverflow.blog)
On Tue, Sep 12, 2017 at 11:44 PM, Paul Rubin wrote: > Chris Angelico writes: > > Why? Unless they're going to be maintaining a Py2 codebase, why should > > they learn the older version with less features? > > Are there actually Py3 codebases? I guess there must be, even though > I've never seen one. Every Python codebase of any size that I know of > is Py2. So yes, of course they're working on a Py2 codebase. That's > the only kind there is, as far as I know. > -- > https://mail.python.org/mailman/listinfo/python-list > This is Zed Shaw levels of willful ignorance here. The codebase I work on at my job is entirely Python 3. I'm sure the same is true for anyone building a new piece of software with Python since at least 2015. Not everyone gets paid to maintain legacy software in "enterprise" corporations. Some of us are contractors or work for startups. -- https://mail.python.org/mailman/listinfo/python-list
Re: Even Older Man Yells At Whippersnappers
On Tue, Sep 19, 2017 at 8:00 AM, Stefan Ram wrote: > D'Arcy Cain writes: > >of course, I use calculators and computers but I still understand the > >theory behind what I am doing. > > I started out programming in BASIC. Today, I use Python, > the BASIC of the 21st century. Python has no GOTO, but when > it is executed, its for loop eventually is implemented using > a GOTO-like jump instruction. Thanks to my learning of BASIC, > /I/ can have this insight. Younger people, who never learned > GOTO, may still be able to use Python, but they will not > understand what is going on behind the curtains. Therefore, for > a profound understanding of Python, everyone should learn BASIC > first, just like I did! > > ;-) > > > > -- > https://mail.python.org/mailman/listinfo/python-list > As a young person (read: late 20s), the one thing I've learned is that if a language has a `GOTO` instruction, it's probably a bad idea to use said instruction. I'm sure there's exceptions to this rule, but I'm lucky enough to have better solutions for calling the same procedure multiple times, i.e. functions. I always wonder what my "old man yells at cloud" moment will be once I get older. -- https://mail.python.org/mailman/listinfo/python-list
Re: Even Older Man Yells At Whippersnappers
On Tue, Sep 19, 2017 at 8:59 AM, Grant Edwards wrote: > On 2017-09-19, Rhodri James wrote: > > On 19/09/17 16:00, Stefan Ram wrote: > >> D'Arcy Cain writes: > >>> of course, I use calculators and computers but I still understand the > >>> theory behind what I am doing. > >> > >>I started out programming in BASIC. Today, I use Python, > >>the BASIC of the 21st century. Python has no GOTO, but when > >>it is executed, its for loop eventually is implemented using > >>a GOTO-like jump instruction. Thanks to my learning of BASIC, > >>/I/ can have this insight. Younger people, who never learned > >>GOTO, may still be able to use Python, but they will not > >>understand what is going on behind the curtains. Therefore, for > >>a profound understanding of Python, everyone should learn BASIC > >>first, just like I did! > > > > Tsk. You should have learned (a fake simplified) assembler first, then > > you'd have an appreciation of what your processor actually did. > > > >:-) > > Tsk, Tsk. Before learning assembly, you should design an instruction > set and implement it in hardare. Or at least run in in a VHDL > simulator. [Actually, back in my undergrad days we used AHPL and > implemented something like a simplified PDP-11 ISA.] > > Alternatively, you should design an instruction set and implement it > using microcode and AM2900 bit-slice processors. > > -- > Grant Edwards grant.b.edwardsYow! Could I have a drug > at overdose? > gmail.com > > -- > https://mail.python.org/mailman/listinfo/python-list > Even Assembly is easy nowadays: https://fresh.flatassembler.net/index.cgi?page=content/1_screenshots.txt -- https://mail.python.org/mailman/listinfo/python-list
Re: Old Man Yells At Cloud
On Tue, Sep 19, 2017 at 9:17 AM, Grant Edwards wrote: > On 2017-09-19, Jan Erik =?utf-8?q?Mostr=C3=B6m?= > wrote: > > > And I'm amazed how often I see people trying to calculate > > > > change = sum handed over - cost > > > > and then trying to figure out what bills/coins should be returned > > instead of doing the simple thing of just adding to the cost. > > When I was a kid, making change like that was something we were all > taught in school. I have a feeling that's been dropped from most > curricula. > > -- > Grant Edwards grant.b.edwardsYow! MMM-MM!! So THIS > is > at BIO-NEBULATION! > gmail.com > > -- > https://mail.python.org/mailman/listinfo/python-list > Not sure about the most recent decade, but back when I was in elementary school(1995-2001-ish), we definitely still learned math through how to make change. -- https://mail.python.org/mailman/listinfo/python-list
Re: Even Older Man Yells At Whippersnappers
On Tue, Sep 19, 2017 at 9:12 AM, Rhodri James wrote: > On 19/09/17 16:59, Grant Edwards wrote: > >> On 2017-09-19, Rhodri James wrote: >> >>> On 19/09/17 16:00, Stefan Ram wrote: >>> D'Arcy Cain writes: > of course, I use calculators and computers but I still understand the > theory behind what I am doing. > I started out programming in BASIC. Today, I use Python, the BASIC of the 21st century. Python has no GOTO, but when it is executed, its for loop eventually is implemented using a GOTO-like jump instruction. Thanks to my learning of BASIC, /I/ can have this insight. Younger people, who never learned GOTO, may still be able to use Python, but they will not understand what is going on behind the curtains. Therefore, for a profound understanding of Python, everyone should learn BASIC first, just like I did! >>> >>> Tsk. You should have learned (a fake simplified) assembler first, then >>> you'd have an appreciation of what your processor actually did. >>> >>> :-) >>> >> >> Tsk, Tsk. Before learning assembly, you should design an instruction >> set and implement it in hardare. Or at least run in in a VHDL >> simulator. [Actually, back in my undergrad days we used AHPL and >> implemented something like a simplified PDP-11 ISA.] >> > > > Eh, my school never 'ad an electronics class, nor a computer neither. Made > programming a bit tricky; we 'ad to write programs on a form and send 'em > off to next county. None of this new-fangled VHDL neither, we 'ad to do > our simulations with paper and pencil. > > > (All true, as it happens. My school acquired a computer (just the one: a > NorthStar Horizon) in my O-Level year, but before that we really did have > to send programs off to Worcester where someone would laboriously type them > in for you. A week later you got a print out of the results and a roll of > paper tape with your program on it.) > > > -- > Rhodri James *-* Kynesim Ltd > -- > https://mail.python.org/mailman/listinfo/python-list > What happened if there was a bug? Did you have to re-send it? -- https://mail.python.org/mailman/listinfo/python-list
Re: Old Man Yells At Cloud
On Tue, Sep 19, 2017 at 9:26 AM, Larry Martell wrote: > On Tue, Sep 19, 2017 at 10:30 AM, D'Arcy Cain > wrote: > > On 09/19/2017 06:46 AM, Larry Martell wrote: > >> > >> True story - the other day I was in a store and my total was $10.12. I > > > > > > One time I was at a cash with three or four items which were taxable. The > > cashier rung each one up and hit the total button. She turned to me and > > said something like "$23.42 please." She was surprised to see that I was > > already standing there with $23.42 in my hand. "How did you do that" she > > asked. She must have thought it was a magic trick. > > I was just in a clothing store this weekend and there was a rack of > clothes that was 50%. The sales clerk said everything on that rack was > an additional 25% off, so it's 75% off the original price. I asked is > it 75% off the original price or 25% off the 50% of the price. Said > it's the same thing. I said no it's not. She insisted it was. I said > no, let's take a simple example. If it was $100 and it was 75% off it > would be $25. But if it's 50% off and then 25% off that it will be > $37.50. She looked totally dumbfounded. > -- > https://mail.python.org/mailman/listinfo/python-list > That just seems like a simple logical failure. I'm amazed every day by how many people find that type of thinking difficult. -- https://mail.python.org/mailman/listinfo/python-list
Re: Even Older Man Yells At Whippersnappers
On Wed, Sep 20, 2017 at 7:29 AM, Larry Martell wrote: > On Wed, Sep 20, 2017 at 5:09 AM, Gregory Ewing > wrote: > > > > Never mind that fake assembly rubbish, learn a real assembly > > language! And hand-assemble it and toggle it into the front > > panel switches like I did! > > 1979, I was working at Bausch and Lomb in Rochester NY. We had a 16 > bit Data General Nova 'Minicomputer'. It had 4 registers, called > accumulators. It had 16 front panel toggle switches, one for each bit, > one that said 'deposit', and one that said run. It had a dial with > stops for AC0, AC1, AC2, AC3 (for the 4 accumulators), PC (program > counter), address and contents. > > When you powered up the machine it did not boot. You had to hand enter > a short bootstrap program in binary. Do to this you had to turn the > dial to address, key in a 16 bit address, click deposit, turn the dial > to contents, key in a 16 bit line of assembly code, click deposit, and > repeat this for each line of code (there were like 5 or 6). Then key > in the address of where you wanted to run from turn the dial to PC, > deposit, and click run. Any mistake and it would not boot. Often took > 3 or 4 tries. > > After a few weeks of this I was sick of it. I had the boot code burned > into an EEPROM (which I had to send out to be programmed). Then I > build a very small wire wrapped board with the EEPROM and an > oscillator and few TTL chips. I tapped into the 5V power on the CPU > board and used the leading edge of that to trigger a one shot which > 'woke up' my circuit, and caused it to clock out the code from the > EEPROM and load it to the appropriate place, set the program counter > and start the program. I drilled holes in the CPU board and mounted > this with little plastic standoffs. > > I did this all on my own, coming in on the weekends, without company > approval, and when it was working I showed my boss. He was blown away > and he was sure we could patent this and sell it. He had me formalize > the design, write it up, have an actual PCB made, go to the company > lawyers, the whole 9 yards. Then Data General announced the new > version of the Nova with auto boot. > -- > https://mail.python.org/mailman/listinfo/python-list > That's crazy! The oldest computer I ever owned was a 1984 Tandy 1000. I actually still miss that thing. It had an option where you could change the 8-bit music that played on startup. Luckily for me, it took 5.25" floppys. -- https://mail.python.org/mailman/listinfo/python-list
Re: Beginners and experts (Batchelder blog post)
On Fri, Sep 29, 2017 at 2:57 AM, Leam Hall wrote: > On 09/27/2017 10:33 PM, Stefan Ram wrote: > >Some areas of knowledge follow, a programmer should not be >>ignorant in all of them: >> > > --- > > Stefan, this is list AWESOME! > > I have started mapping skills I have to the list and ways to build skills > I don't have. Last night I started working on a project that has been on my > mind for over a year; taking a CSV list of game characters and putting them > into a MongoDB datastore. Now I need to figure out how to build an > interface for CRUD operations using Python, pymongo, and maybe Tk. > > I appreciate the structure your list provides. Thank you! > > Leam > > -- > https://mail.python.org/mailman/listinfo/python-list > Python web backends just happen to be my specialty. I do mostly Django, but it doesn't mesh well with MongoDB. Well, it does if you still use an RDBMS forsome things. I can recommend the following: - Flask: http://flask.pocoo.org/ Small and light But not tiny. Not really fast, not really slow. Not a ton of batteries included. Tons of third-party extensions. - ApiStar: https://github.com/encode/apistar New kid on the block. Specializes in APIS. No template integrations. Best for serving JSON through a RESTful interface. Fairly quick, but not blazing fast. Has the upside that any web API can be exposed as a CLI API. Not a ton of third party extensions available. Would be a good choice if you don't want to build a desktop application instead of a web application as it will help design the API that something like Tkinter will sit on top of. - Sanic: https://github.com/channelcat/sanic Another new kid. Python 3.5+ only. Uses the new async capabilities quite heavilly. Based on falcon. Blazing fast. No batteries included. Small number of fairly high quality third-party extensions. - Django: https://www.djangoproject.com/ The old workhorse. Mature and proven. Best choice for reliability. Not fast, not slow. Huge collection of third party extensions ranging in quality. Though, it is pretty heavilly integrated with it's relational Db backends. If you decide on this, you would need to use postgres/sqlite/mysql to store all of Django's built in model classes(tables). I got through writing all of the above without realizing that you meant you wanted to build a desktop application and not a web application. Though, I think the advice is still helpful. -- https://mail.python.org/mailman/listinfo/python-list
Re: Beginners and experts (Batchelder blog post)
On Fri, Sep 29, 2017 at 12:14 PM, Bill wrote: > > I'll write for the possible benefit of any beginners who may be reading. > I guess by definition, if one still has a "bug" it's because one doesn't > quite understand what the code is doing. And I would say you should lose > your license if you "fix something", and don't understand why it works > (within reason of course--some mystery's of library functions should > probably remain so forever). So ADT (Any Damn Thing--I just made that up > that acronym) you can do to understand your code better is fair game! : ) > In fact, in my experience, the sooner you start getting a little bit > angry, the sooner you'll get to the heart of matter. Usually, what looks > like a long route, isn't, in the end. Don't be afraid to write *really > descriptive* output statements, and do so even though you "don't need to". > Besides for making you more productive, it will help soothe you : ) > Beginners almost never need to... I think that getting out of the > beginner phase requires developing a certain amount of humility. Just wait > 5 or 10 years, any look back, and see if what I've written isn't more true > than false. > > The only part I am unsure of is whether you are supposed to get a little > big angry or not (YMMV). I find 2 cups of coffee about right. That is, 2 > before and 2 after lunch. Of course, that does not include "meetings". > -- > https://mail.python.org/mailman/listinfo/python-list > Reminds me of a bug I had to chase down recently. I've been working on the front-end of this web application for a while. It's an SPA built with Vuejs. The bug arose in the login workflow. Basically, it went like this: client loads login screen -> user enters credentials into form and submits -> client sends credentials to server -> server verifies credentials -> server sends back auth token -> client receives auth token and stores it -> client redirects user to home screen -> home screen makes get request for some data Now, this worked perfectly fine everywhere except for Safari 9.1 on OSX. A user could login just fine on Safari 9.1, but after that, no requests would complete. Safari's dev tools were no help because they were not showing any errors or any failed requests. I checked the server logs and found that no requests were even sent. It took me 2 days to figure out this bug. I tracked it down to the function that injected the authorization header into all requests if the user was logged in. Based on troubleshooting, I knew it couldn't be anything else. That said, I was still confused because this worked on literally every other browser(even IE 9). After searching for people with similar problems and coming up with nothing I got to thinking about the asynchronous nature of JS. So, out of sheer frustration I moved the line of code that stored the auth token from one function to another, booted up my testing environment, and it worked. So, the bug was basically because Safari was waiting for a specific function call to complete before it committed the token to local storage even though the line of code that did so was within said function. So, two days worth of work to move a single line of code from one function to another. You can only imagine the tirade of curse words directed at apple during the above calamity. Had I simply written a console log for every function down the chain, I may have been able to find the cause of the bug more quickly. -- https://mail.python.org/mailman/listinfo/python-list
Re: choice of web-framework
On Sun, Oct 22, 2017 at 3:24 AM, Patrick Vrijlandt wrote: > Hello list, > > I would like your recommendation on the choice of a web framework. > > The project is completely new, there are no histories to take into account > (current solutions are paper-based). The website involves questionnaires > that will be developed, filled out and stored. Users are not programmers or > developers. They should be authenticated. Version control is required. > Internationalization is not an issue. I expect that the project will add > additional requirements and complexity later on that I can not foresee yet. > I'm targeting a single deployment (maybe a second on a development > machine). I usually work on Windows, but Linux can be considered. > > I'm not afraid to learn a (=one) new framework (that would actually be > fun) but trying out a lot of them is not feasible. My current goal is a > demonstration version of the project as a proof of concept. I may want to > hand it over to a commercial solution at that stage. > > I'm an experienced python programmer but not an experienced web developer. > A few years ago I read some books about Zope and Plone, but never did > serious development with those. I currently maintain an intranet site in > MoinMoin. I assume Zope could still be a potential choice, but it may have > lost the vibrancy of a few years ago. Also, I would not know which version > to choose (Zope 4, BlueBream, or something like Grok). The problem seems > too complicated for micro frameworks like bottle of Flask. Django could be > the next alternative. > > Finally, for a new project, I would not like to be confined to Python 2.7. > > What are your ideas? > > Thanks in advance, > > -- > Patrick > -- > https://mail.python.org/mailman/listinfo/python-list > I think your best choice here would be Django. I've been doing web development with Python for about 5 years now and I have only found thing that Django can't handle: replacing the authentication framework's dependence on SQL. i.e., if you wanted to use a noSQL db like MongoDb for your user model, it's not really possible without a ton of work. Other than that though, Django can pretty much do everything. Since you need to get this prototype done quickly, I think Django is your absolute best choice. The projects motto is "The web framework for perfectionists with deadlines." You get a ton of stuff out of the box: - User authentication - Sessions - Admin interface - Fantastic ORM - Templating (like jinbja2 but with some Django flair) - The best documentation I have ever seen - A huge ecosystem of third party libraries and plugins - A strong and heavilly opinionated MVC architecture - One of ths strongest and best suppported OSS projects in existence - Built in and versioned schema migrations The reasons I would not reccomend Flask/Bottle for your project specifically: - Flask is better for more "customized" solutions or simpler projects - Flask is a great framework, but offers very little out of the box as far as modern web application features - It takes longer to get rolling with Flask(a lot more initial configuration) - When using Flask, many devs end up building their own version of Django anyways - Flask's tutorial is a lot less in-depth than Django's - Although learning Flask in its entirety is much simpler than learning Django in its entirety, it takes more time to get up and running with Flask in my experience. Web2py/zope/other small and old frameworks: - I would stay away from these unless you have a lot of experience with them. - These projects do not have a modern ecosystem of libraries and may not have full Python3 support - You will find less community memebers that are able to help you as there are less people using these frameworks Hug/Sanic/Falcon/ApiStar: - These are designed around the idea of REST apis - They offer less than Flask does out of the box(except for building REST apis) - They are fairly new and have not had the time to build up a supportive ecosystem yet - They rely on new language features like async - Their docs are not up to par with more mature projects Pyramid: Though I haven't ever worked with Pyramid, I have met several people who are very happy with it. I also met with one of the project's core contributors and he spoke about how the architecture is "plugin based". There is the the core library and all of the other layers of the application such as the data layer or authentication, for example, are officially supported plugins. Might be worth looking into. -- https://mail.python.org/mailman/listinfo/python-list
Re: choice of web-framework
On Tue, Oct 24, 2017 at 4:14 AM, Chris Angelico wrote: > > (There are other ORMs than SQLAlchemy, of course; I can't recall the > exact syntax for Django's off the top of my head, but it's going to be > broadly similar to this.) > > ChrisA > -- > https://mail.python.org/mailman/listinfo/python-list > I can help with that: ## Defining a model: class Thing(models.Model): """ This is the "schema" for the `thing` table. The pk field is created automatically and is called `id` by default. This table with have four columns: `id`, `foo`, `baz`, and `score`. """ foo = models.Charfield( max_length=140, blank=False ) baz = models.CharField( max_length=140, blank=True ) score = models.IntegerField() ## Create an object: new_thing = Thing.objects.create(foo="bar", baz="foo") ## Get a list of objects: Thing.objects.all() ## Filter a list of objects: Thing.objects.filter(foo="bar") ## Modify an object: thing = Thing.objects.get(id=1) thing.foo = "baz" thing.save() ## Perform an aggregation: data = Thing.objects.aggregate(avg=Avg("score")) print(data) >>> {"avg": 50} ## Django basic view(called controllers in other frameworks normally) and template: def person_list(request): """ Get a collection of `User` objects from the database. """ people = User.objects.filter(is_active=True).order_by("date_joined") return render( request, "person/list.html", context={"people": people} ) Then, in `templates/person/list.html`: {% extends 'base.html' %} {% block content %} {% for person in people %} {{person.first_name}} {{person.last_name}} {% endfor %} {% endblock %} Alternatives to Django's ORM and SQLAlchemy include but are not limited to: - Peewee: https://github.com/coleifer/peewee - PonyORM: https://ponyorm.com/ -- https://mail.python.org/mailman/listinfo/python-list
Re: Need some help with Python Job Board
On Sat, Nov 11, 2017 at 3:27 PM, Skip Montanaro wrote: > The Python Job Board could use a little help in a couple areas. One, we can > always use help reviewing and approving (or rejecting) submissions. The > backlog keeps growing, and the existing volunteers who help can't always > keep up. (This is a good problem to have, reflecting on Python's broad > popularity in many application domains.) > > Two, and perhaps more important, the submission form really needs to > support WYSIWYG editing. Apparently, most posters are unable to handle > markup-based systems, probably just pasting content from Word documents. > Making this change would streamline the review process, as formatting > problems are currently the biggest impediment to successful submissions. > There is an open ticket to add this feature: > > https://github.com/python/pythondotorg/issues/655 > > If you can help with either task, please drop a note to j...@python.org. > > Thanks, > > Skip > -- > https://mail.python.org/mailman/listinfo/python-list > I might be able to help implement a wysiwyg editor. The only issue I can think of at the moment would be finding a way to determine if the template should render wysiswyg content or Markdown content. I'll need to look over the repo a bit more closely first. -- https://mail.python.org/mailman/listinfo/python-list
Re: [Jobs] Need some help with Python Job Board
On Mon, Nov 13, 2017 at 1:16 AM, M.-A. Lemburg wrote: > Hi Justin, > > the default markup is currently set to restructuredtext: > > https://github.com/python/pythondotorg/blob/master/jobs/models.py > > but this can be changed to any of these supported ones: > > https://github.com/jamesturk/django-markupfield > > as long as we make sure that all existing records continue > to be set to ReST (to not mess up the formatting). > > Since I had a look at WYSIWYG editors, some new ones may have > surfaced. > > The templates are defined here: > > https://github.com/python/pythondotorg/tree/master/templates/jobs > > and the main project page has instructions on how to get > a local copy of the website working: > > https://pythondotorg.readthedocs.io/ > > Thanks, > -- > Marc-Andre Lemburg > Python Software Foundation > http://www.python.org/psf/ > http://www.malemburg.com/ > _ > > Jobs mailing list > > j...@python.org > > https://mail.python.org/mailman/listinfo/jobs > > > > Thank you Marc. I'll take a look over this stuff and hopefully I can squeeze in some time this week to work on it. -- https://mail.python.org/mailman/listinfo/python-list
Re: Linear Time Tree Traversal Generator
On Tue, Sep 20, 2016 at 9:46 AM, ROGER GRAYDON CHRISTMAN wrote: > I am trying to find a better (i.e. more efficient) way to implement a > generator > that traverses a tree. > > The current model of the code (which is also used by a textbook I am > teaching > from does this) > >def __iter__(node): > for x in iter(node._left): > yield x > yield node._value > for x in iter(node._right) > yield x > > This is nice, simple, and straightforward, but has an O(n log n) running > time, > since > values from the leaves of the tree have to be yielded multiple times to > the top > of the tree. > Are the left and right attributes collections of more nodes or are they simply references to the node's position in the tree? >From the code provided it seems like the former is true and a node's left attribute is a reference to another node? I don't know how flexible you are with the structure of your tree, but you could try taking the modified pre-order tree traversal approach. This article explains it in the context of a database, but the idea is the same: https://www.sitepoint.com/hierarchical-data-database-2/ Each node would then have a parent attribute as well as left and right attributes. The parent would be a reference to a parent node, and the left and right would be integers that position the element in the tree. The upside to this is that traversal and lookup is much faster since you do not need to have an iterator nested in an iterator. This is because the top level node will always have the lowest integer as it's left attribute and the highest integer as it's right attribute. That means that you can instead have a single iterator that iterates through a range of integers to yield the node with the specified left and right values. The downside is that inserting a new node can take a long time because, depending on the insertion point, the left and right values for each node in the tree may have to be recalculated. Now, I may have completely missed the mark here. I am completely self taught and have only been programming for about 3 years. I hope that you gleaned some value from my response either way. -- https://mail.python.org/mailman/listinfo/python-list
Re: New to python
On Mon, Oct 17, 2016 at 12:51 PM, Bill Cunningham wrote: > I just installed python I might start with 3. But there is version 2 out > too. So far I can '3+4' and get the answer. Nice. I typed the linux man > page > and got a little info. So to learn this language is there an online > tutorial? I am interested in the scripting too. > I highly recommend http://www.composingprograms.com/ if you are new to programming in general. It teaches basic concepts using Python 3 in the style of S.I.C.P. -- https://mail.python.org/mailman/listinfo/python-list
Re: Obtain javascript result
On Fri, Oct 21, 2016 at 8:07 AM, wrote: > Yes, > > the page is http://www.betexplorer.com/next/soccer/ > and You have to open any match You want. > > This pop-up new windows with match detail and odds > (if present). > > I try to extract home team, away team, results, and > bet365's bookmaker odds. > > I can't continue in my fun analyses because the odds > are returned through that javascript code and > I don't know how manage it in python > to take that results. > The data is being obtained through an ajax call: jQuery.ajax({ url: '/gres/ajax-matchdetails.php', type: 'GET', cache: false, dataType: 'json', success: function(data) { if (data.user_logged) { user.logged = true; user.oddsformat = data.oddsformat; } bookmaker_urls = data.bookmaker_urls; ajax_to_call--; if (ajax_to_call == 0) { matchdetails_finish(); $('#odds-all-loader').remove(); $('#odds-all').show(); } } }); jQuery.ajax({ url: '/gres/ajax-matchodds.php', type: 'GET', data: 't=d&e=' + eventid + '&b=' + bettype, success: function(data) { $('#odds-all').html(data); ajax_to_call--; if (ajax_to_call == 0) { matchdetails_finish(); $('#odds-all-loader').remove(); $('#odds-all').show(); } } You can see this by opening up your developer tools (chrome or Firefox) and navigating to the debugger/scripts tab where you will find the "matchdetails_init" function. However, I tried fetching the "ajax-matchdetails.php" endpoint via httpie, and I received a 404 page. Investigating the request via the developer console led to some strange results as well. There was a small piece of json data returned containing the keys "user_logged" and "bookmaker_urls". There was no data about the match at all. There are several other ajax calls in the script, so you may want to check those out. However, it seems like the match data itself is actually populated with data server-side via a PHP script. You should be able to get the link for a match, point beautiful soup at it, parse it, and get the data. -- https://mail.python.org/mailman/listinfo/python-list
New REST API Library for Django
Hi everyone! I am working on a new REST API library for Django. You can see it on: Github: https://github.com/FFX01/django-restup PyPI: https://pypi.python.org/pypi?name=django-restup&version=0.1.1&:action=display I know there is already a couple great packages out there for REST API development with Django. However, I found them to be difficult to use for very granular data manipulation and permissions for my most recent project. So, I set out to make that a bit easier for myself. I am not using this package in production anywhere as I just released this pre-alpha today for people to mess around with if they want. I just want to see what you all think. I could use any criticism, feedback, and ideas you may have for me. If you want to contribute, that would be even better! This is my first time putting something out on PyPI. It's also my first "serious" open source project. Let me know what you would like to see from a REST API library and I can add it to the schedule. Thank you, - Justin -- https://mail.python.org/mailman/listinfo/python-list
Re: advanced SimpleHTTPServer?
On Wed, Nov 2, 2016 at 11:40 AM, Chris Warrick wrote: > The other frameworks are simple to set up, too. I’ve personally had > Unicode issues with Bottle, and it doesn’t even do sessions. Unlike > Flask, or of course Django. > > Because, as the old saying goes, any sufficiently complicated Bottle > or Flask app contains an ad hoc, informally-specified, bug-ridden, > slow implementation of half of Django. > > (In the form of various plugins to do databases, accounts, admin panels > etc.) > I've found this to be the case whenever I see a Flask or Bottle project that does anything more than expose a data API. I think Flask is great for building small applications or microservices. Any more and you are essentially hacking together a bunch of packages that may or may not have been designed to work together. I find that Django can suit almost any use case perfectly well. You can use whatever part of the framework you want and toss out/replace any part you don't want. Plus, built in sessions and authentication are fantastic time savers. -- https://mail.python.org/mailman/listinfo/python-list
Re: advanced SimpleHTTPServer?
On Wed, Nov 2, 2016 at 12:52 PM, Eric S. Johansson wrote: > So this brings me back to my question. What is missing in > SimpleHTTPServer to keep it from being secure enough? > There's no way to vet requests. You can't stop a request from accessing anything in the directory that SimpleHTTPServer is running in. I'm sure an enterprising individual could also probably access the shell session SimpleHTTPServer is running in as well. I haven't looked into the internals very much, but it is possible an attacker could use eval() to run a Python script sent in a request body. Not sure about that last one. I'll have to try it myself and report back. -- https://mail.python.org/mailman/listinfo/python-list
Re: need some kind of "coherence index" for a group of strings
On Thu, Nov 3, 2016 at 9:18 AM, Fillmore wrote: > > Hi there, apologies for the generic question. Here is my problem let's say > that I have a list of lists of strings. > > list1:#strings are sort of similar to one another > > my_nice_string_blabla > my_nice_string_blqbli > my_nice_string_bl0bla > my_nice_string_aru > > > list2:#strings are mostly different from one another > > my_nice_string_blabla > some_other_string > yet_another_unrelated string > wow_totally_different_from_others_too > > > I would like an algorithm that can look at the strings and determine that > strings in list1 are sort of similar to one another, while the strings in > list2 are all different. > Ideally, it would be nice to have some kind of 'coherence index' that I > can exploit to separate lists given a certain threshold. > > I was about to concoct something using levensthein distance, but then I > figured that it would be expensive to compute and I may be reinventing the > wheel. > > Thanks in advance to python masters that may have suggestions... > > > > -- > https://mail.python.org/mailman/listinfo/python-list > When you say similar, do you mean similar in the amount of duplicate words/letters? Or were you more interested in similar sentence structure? -- https://mail.python.org/mailman/listinfo/python-list
Re: advanced SimpleHTTPServer?
On Thu, Nov 3, 2016 at 10:27 PM, Rustom Mody wrote: > On Thursday, November 3, 2016 at 1:23:05 AM UTC+5:30, Eric S. Johansson > wrote: > > On 11/2/2016 2:40 PM, Chris Warrick wrote: > > > Because, as the old saying goes, any sufficiently complicated Bottle > > > or Flask app contains an ad hoc, informally-specified, bug-ridden, > > > slow implementation of half of Django. (In the form of various plugins > > > to do databases, accounts, admin panels etc.) > > > > That's not a special attribute of bottle, flask or Django. Ad hoc, > > informally specified, bug ridden slow implementations abound. We focus > > too much on scaling up and not enough on scaling down. We (designers) > > also have not properly addressed configuration complexity issues. > > This scaling up vs down idea is an important one. > Related to Buchberger’s blackbox whitebox principle > > > > > If I'm going do something once, if it cost me more than a couple of > > hours to figure it out, it's too expensive in general but definitely if > > I forget what I learned. That's why bottle/flask systems meet and need. > > They're not too expensive to forget what you learned. > > > > Django makes the cost of forgetting extremely expensive. I think of > > using Django as career rather than a toolbox. > > Thats snide... and probably accurate ;-) > Among my more unpleasant programming experiences was Ruby-on-Rails > And my impression is that Ruby is fine; Rails not > Django I dont know and my impression is its a shade better than Rails > > It would be nice to discover the bottle inside the flask inside django > > Put differently: > Frameworks are full-featured and horrible to use > APIs are elegant but ultimately underpowered > DSLs (eg requests) are in intermediate sweetspot; we need more DSL-families > -- > https://mail.python.org/mailman/listinfo/python-list > I work with Django every day. Knowing Django is like knowing another ecosystem. It's totally worth learning though. The speed of development is absolutely unbeatable. I can build a fully featured and good-looking blog in about 10 minutes. It's nuts. The best part about it though, is that it's really just simple Python under the hood for the most part. You can override or modify any part of it to make it work in exactly the way you want it to. I'm a huge Django fanboy, so excuse the gushing. The docs are also some of the most comprehensive I've ever seen. -- https://mail.python.org/mailman/listinfo/python-list
Re: key and ..
On Thu, Nov 17, 2016 at 7:05 PM, Val Krem via Python-list < python-list@python.org> wrote: > > > Hi all, > Sorry for asking such a basic question butI am trying to merge two > files(file1 and file2) and do some stuff. Merge the two files by the first > column(key). Here is the description of files and what I would like to do. > > > file1 > > key c1 c2 > 1 759 939 > 2 345 154571 > 3 251 350711 > 4 3749 22159 > 5 676 76953 > 6 46756 > > > file2 > key p1p2 > 1 759939 > 2 345 154571 > 3 251 350711 > 4 3915 23254 > 5 7676 77953 > 7 256 4562 > > create file3 > a) merge the two files by (key) that exit in file1 and file2 > b) create two variables dcp1 = c1- p1 and dcp2= c2-p2 > c) sort file3 by dcp2(descending) and output > > create file4:- which exist in file1 but not in file2 > create file5:- that exist in file2 but not in file1; > > > Desired output files > > file3 > key c1c2 p1 p2 dcp1 dcp2 > 4 3749 22159 3915 23254 -166 -1095 > 5676 76953 7676 77953 -7000 -1000 > 1759939 759939 0 0 > 2345 154571 345 154571 0 0 > 3251 350711 251 350711 0 0 > > file4 > key c1 p1 > 6 46 756 > > file5 > key p1 p2 > 7 256 4562 > > > > Thank you in advance > -- > https://mail.python.org/mailman/listinfo/python-list > 1. Take each file and read it using file.open() declaring a variable to store the string. 2. Use list.split('\n') to split the file into an array of lines. 3. Build a list of dictionaries by splitting each line at whitespace and calling int() on the values of each column for each file. 4. Do what you have to do math wise between each dict storing the values in a new dict. You can write this out directly to the file or append it to a new list. 5. Use file.open() to write the resulting lines to a new file. 6. transform one of the lists into a set and use set.difference() or set.intersection() to create a new list. This list will be unordered by default, so you may want to run it through sorted(set, key=lambda row: row['key']). 7. repeat step 5 above to write out to file 4 and 5. no need to transform the list into a set again. Just find the difference/interference again. This isn't the fastest or most efficient way of doing it, but it is probably the most straight forward. If these files are quite large you may want to take a different approach in the interest of performance and memory. If you don't want to use dicts, you should have no problem substituting tuples or nested lists. The whole thing could be made into a generator as well. Basically, there are a lot of ways to approach this. Hope that helped at least a little bit. -- https://mail.python.org/mailman/listinfo/python-list
Re: Quick help for a python newby, please
On Wed, Nov 23, 2016 at 7:13 AM, Dayton Jones wrote: > ah...yes, but then how could I strip the rest (h:m:s) from it? > > Enter the numerical month you were born: 3 > Enter the numerical day of the month you were born: 30 > Enter the year you were born: 1989 > 10100 days, 0:00:00 > -- > https://mail.python.org/mailman/listinfo/python-list > You'll probably want to use `timedelta`: https://docs.python.org/3.4/library/datetime.html#timedelta-objects -- https://mail.python.org/mailman/listinfo/python-list
Re: When will they fix Python _dbm?
On Mon, Dec 5, 2016 at 6:45 AM, clvanwall wrote: > I have been a Perl programmer for 15+ years and decided to give Python a > try. My platform is windows and I installed the latest 3.5.2. Next I > decided to convert a perl program that uses a ndbm database since according > to the doc on python, it should be able to work with it. Needless to say, > I get: dbm.error: db type is dbm.ndbm, but the module is not available > Searching on Python Bug Tracker shows _dbm missing back in 03-03-2012! > That's a long time for a bug to be left open. > John Van Walleghen > > > Sent from my Galaxy Tab® A > -- > https://mail.python.org/mailman/listinfo/python-list > Hi there, Could you please post code that is giving you an error? -- https://mail.python.org/mailman/listinfo/python-list
Re: When will they fix Python _dbm?
On Mon, Dec 5, 2016 at 5:06 PM, clvanwall wrote: > will thid do? John > Looks like you need to use dbm.ndbm.open() instead of just dbm.open(). See the docs here for more info: https://docs.python.org/3/library/dbm.html#module-dbm.ndbm -- https://mail.python.org/mailman/listinfo/python-list
Re: Django broken pipe error
On Tue, Dec 6, 2016 at 6:21 AM, wrote: > Hi, > > I'm facing strange Django broken pipe error (Python 2.7 on Ubuntu) that > apparently is a not fixed Django bug. Does anybody now how to fix it? I've > been searching a lot and didn't find any solution. > > This error happens very irregularly by Post request in Django. Sometimes > it works sometimes not: > > [06/Dec/2016 13:33:57] "POST /export_report/ HTTP/1.1" 500 59 > Traceback (most recent call last): > File "/usr/lib/python2.7/SocketServer.py", line 593, in > process_request_thread > self.finish_request(request, client_address) > File "/usr/lib/python2.7/SocketServer.py", line 334, in finish_request > self.RequestHandlerClass(request, client_address, self) > File "/home/ait/.virtualenvs/env1/local/lib/python2.7/site- > packages/django/core/servers/basehttp.py", line 129, in __init__ > super(WSGIRequestHandler, self).__init__(*args, **kwargs) > File "/usr/lib/python2.7/SocketServer.py", line 651, in __init__ > self.finish() > File "/usr/lib/python2.7/SocketServer.py", line 710, in finish > self.wfile.close() > File "/usr/lib/python2.7/socket.py", line 279, in close > self.flush() > File "/usr/lib/python2.7/socket.py", line 303, in flush > self._sock.sendall(view[write_offset:write_offset+buffer_size]) > error: [Errno 32] Broken pipe > > Exception happened during processing of request from ('127.0.0.1', 38224) > > It is also described in: https://www.reddit.com/r/ > joinmarket/comments/4atqrm/is_this_exception_normal_exception_happened/ > > On https://bugs.python.org/issue14574 is stated that this error should > already be fixed but apparently not. > > Best regards, > > Roman Hi Roman, Is this happening on the dev server or a production server? Did you use the command ./manage.py runserver to start the server? Can you please provide the code for the view class/function that is throwing the error? I believe that this issue may be caused by a call to the database not being structured correctly. -- https://mail.python.org/mailman/listinfo/python-list
Re: Django broken pipe error
On Wed, Dec 7, 2016 at 1:08 AM, wrote: > Thank you Justin, > > I'm on the dev server and should present results in this way. > > Yes, I use manage.py runserver --insecure to start the server (from > PyCharm). > > My views.py call: > > @detail_route(methods=['post'], permission_classes=[permissions.AllowAny]) > def export_report(request): > body_unicode = request.body.decode('utf-8') > body_str = body_unicode.encode('ascii','ignore') > attr_list = body_str.split('&') > attr_dict = {} > if (len(attr_list) > 0): > for attr in attr_list: >... >key = key_value_pair[0] >attr_dict[key] = key_value_pair[1] > trend = trends.calculate_trend( > attr_dict['search_phrase'] > , attr_dict['time_from'] > , attr_dict['time_to'] > , attr_dict['time_scale'] > ) > attr_dict['trend'] = trend > res = str(json.dumps(attr_dict)) > return HttpResponse(res, content_type="text/plain; charset=utf-8") > > and trend calculation in trends.py with database calls: > > def calculate_trend(query_phrase, time_from, time_to, time_scale): > # check in database if trend already exists > try: > db_trend = Trend.objects.get(pk=query_phrase) > if db_trend.from_time.strftime("%Y-%m-%d") == time_from \ > and db_trend.to_time.strftime("%Y-%m-%d") == time_to \ > and db_trend.granularity == time_scale: > logger.info("trend already exists.") > existing_trend_dict = ast.literal_eval(db_trend.content) > return existing_trend_dict > except Trend.DoesNotExist: > logger.info("It is a new trend search.") > trend_dict = {} > start_time = pd.Timestamp(value[0]) > end_time = pd.Timestamp(value[-1]) > freq = ... get frequency using pandas lib > trend_dict[key] = freq > json_trend_content = trend_dict_to_sorted_json_str(trend_dict) > trend = Trend( > phrase=query_phrase, > content=json_trend_content, > from_time=time_from, > to_time=time_to, > granularity=time_scale, > ) > if trend is not None: > try: > db_trend = Trend.objects.get(pk=query_phrase) > db_trend.delete() > logger.info("delete old trend: %s. " % trend) > except Trend.DoesNotExist: > logger.info("create trend: %s. " % trend) > trend.save() > return trend_dict > > Thank you in advance! > > Roman > -- > https://mail.python.org/mailman/listinfo/python-list > It looks like you can probably get rid of the try/except block at the end of the calculate_trend method as any existing Trend object will have already been caught in the first try/except block. >From what I'm reading here: http://stackoverflow.com/questions/11866792/how-to-prevent-errno-32-broken-pipe , this issue can be caused by the client closing the connection before sendall() finishes writing. Can you estimate how long it takes for a request to this endpoint takes to resolve? If it's a long time(maybe due to the pandas call?), your browser/client may be timing out. It could be because it takes a while for the Db to find an existing Trend object as well. I can't give you any advice on how to fix it exactly, but I can tell you what the problem is: The client is closing the connection before socket.sendall() has finished writing to the socket. My guess is that the calculate_trend() method takes a long time to complete and the client is timing out. -- https://mail.python.org/mailman/listinfo/python-list
Re: "Best" websocket implementation for Python 2.x?
On Wed, Dec 7, 2016 at 8:50 AM, Skip Montanaro wrote: > PyPI came back. A bit more sleuthing suggests that the > websocket-client package on PyPI is Ohtani's package, and is more > up-to-date than the copyright notices would suggest. The package was > updated a few days ago on GitHub. > > Taking the path of least resistance (no changes necessary to the > code), I suspect I will just stick with that unless there are > overriding inputs from the community suggesting something else is way > better... > > S > -- > https://mail.python.org/mailman/listinfo/python-list > I can't vouch for it being better, but if you're using asgi, you may want to take a look at Daphne: https://github.com/django/daphne. I believe it uses autobahn to power the websocket side of things. Daphne was developed for the django-channels project. I have used channels before and I can say that it works pretty well. -- https://mail.python.org/mailman/listinfo/python-list
Re: Django broken pipe error
On Mon, Dec 12, 2016 at 7:27 AM, roma wrote: > Thanks Justin, > > I believe, the whole database story has no influence on the broken pipe > error. I've commented out the whole block and leave only return line: > return HttpResponse(res, content_type="text/plain; charset=utf-8") > The error is still present. And I have no influence on that. > > I call python from js client: > > var newTrendReport = new App.TrendReport(); > newTrendReport.set('search_phrase', search_phrase); > newTrendReport.set('time_from', time_from); > newTrendReport.set('time_to', time_to); > newTrendReport.set('time_scale', time_scale); > newTrendReport.set('category', category); > newTrendReport.startExport( > > function(response){ > console.log("Successfully calculated trend report."); > App.trendPage = new App.TrendPageView(); > App.trendPage.render(response); > }, > ); > > go throw: > > App.TrendReport = Backbone.Model.extend({ > urlRoot: "/api/trend_reports/", > defaults: { > search_phrase: "", > time_from: "", > time_to: "", > time_scale: "", > category: "" > }, > > startExportSuffix: "/export_report/", > > startExport: function( successCallback, errorCallback ) { > console.log("start trend calculation"); > var that = this; > var ajaxUrl = this.startExportSuffix; > var options = { > method: "POST", > data: this.attributes, > contentType: "application/json;charset=UTF-8", > dataType: "json", > > error: errorCallback, > success: successCallback > }; > console.log("start trend export sync"); > App.ajax(ajaxUrl, options); > } > > }); > > and come in export_report method. > > My urls.py: > > url(r'^export_report', ensure_csrf_cookie(views.export_report), > name="export_report"), > -- > https://mail.python.org/mailman/listinfo/python-list > I'm not super familiar with the way backbone does http requests, but something seems off about the startExport function. It seems to me that you are sending a post request to "/export_report/" which is an endpoint that I'm guessing is nested in an include from "/api/trend_reports/". However, it looks like the error you're getting above says you aren't sending the request to "https://root.com/api/trend_reports/export_report/";. Instead, you are sending the request to "https://root.com/export_report/"; . Though, I'm also not sure that's the case because that would normally throw a 404. I also noticed that you set content type to 'application/json' in your js, but the view function returns a 'text/plain' content type. Is There a reason for this? The data key in your js http function is set to the attributes variable which, as far as I can tell, does not exist. There's a lot going on here, but I think you can probably narrow it down to something in your backbone code or the way backbone handles http requests as the error you are getting is caused by the client prematurely closing the socket. It's possible backbone will stop reading the response since it isn't the same content-type as the request. -- https://mail.python.org/mailman/listinfo/python-list
Re: Django broken pipe error
On Mon, Jan 2, 2017 at 6:14 AM, wrote: > > Thanks a lot Justin, > > The problem was solved when I employed standard Framework methods for > creation of new database object: > > in JS: > var trendModel = new App.TrendModel(); > trendModel.set("phrase", search_phrase); > trendModel.set("from_time", time_from); > trendModel.set(... > trendModel.save(... > > in PY: > def create(self, request): > ... > > I've also created extra template and additional View. PageView for some > unclear reason didn't support creation of new object - this event just > disappeared. > > Regards, > > Roman > -- > https://mail.python.org/mailman/listinfo/python-list > Glad to hear that you solved the problem! -- https://mail.python.org/mailman/listinfo/python-list
Re: Choosing a Python IDE. what is your Pythonish recommendation? I do not know what to choose.
On Mon, Jan 2, 2017 at 3:38 AM, Antonio Caminero Garcia < tonycam...@gmail.com> wrote: > Hello, I am having a hard time deciding what IDE or IDE-like code editor > should I use. This can be overwhelming. > > So far, I have used Vim, Sublime, Atom, Eclipse with PyDev, Pycharm, > IntelliJ with Python plugin. > > The thing with the from-the-scratch full featured IDEs (Eclipse, IntelliJ, > Pycharm) is that they look like a space craft dashboard and that > unwarranted resources consumption and the unnecessary icons. I want my IDE > to be minimalistic but powerful. My screen should be mostly “made of code” > as usually happens in Vim, Sublime or Atom. However, Pycharm is really cool > and python oriented. > > The problem with Vim is the learning curve, so I know the very basic > stuff, but obviously not enough for coding and I do not have time to learn > it, it is a pity because there are awesome plugins that turns Vim into a > lightweight powerful IDE-like. So now it is not an option but I will > reconsider it in the future, learning little by little. Also, I am not very > fan GUI guy if the task can be accomplished through the terminal. However, > I don’t understand why people underrate GUIs, that said I normally use > shortcuts for the most frequent tasks and when I have to do something that > is not that frequent then I do it with the mouse, for the latter case in > vim you would need to look for that specific command every time. > > Sublime is my current and preferred code editor. I installed Anaconda, Git > integration and a couple of additional plugins that make sublime very > powerful. Also, what I like about sublime compared to the full featured > IDEs, besides the minimalism, is how you can perform code navigation back > and forth so fast, I mean this is something that you can also do with the > others but for some subjective reason I specifically love how sublime does > it. The code completion in sublime I do not find it very intelligence, the > SublimeCodeIntel is better than the one that Anaconda uses but the > completions are not as verbose as in the IDEs. > > Now, I am thinking about giving a try to Visual Studio Code Edition (take > a look, it sounds good https://marketplace.visualstudio.com/items? > itemName=donjayamanne.python). I need an editor for professional software > development. What would you recommend to me? > -- > https://mail.python.org/mailman/listinfo/python-list > Have yo tried emacs? It's similar to Vim in that it relies very heavily on keyboard shortcuts and such. However, you may like the shortcuts a bit more or find them easier to learn. I side with Marc Brooks in that I believe you should definitely be willing to put in the time to learn an editor of your choice. Becoming an expert at using an editor will make you a lot more productive. Personally, I use Pycharm for most of my projects as I deal with large amounts of different files that can be thousands of lines long. All of the code completion and structure indexing really helps when you need to remember the structure of large applications. Pycharm's debugger integration is also totally awesome. I usually use the debugger to run my tests to get more informative tracebacks or to add breakpoints to failing tests. The git integration is very useful as well because I personally hate Git's CLI. For some small projects I'll use Atom as it gives me a sublime-esque interface without forcing me to use proprietary software. Otherwise I'll use nano for small, single file projects. Have you looked into ipython notebook? It's not exactly an IDE, but it does have built in code completion and makes' it really simple to document your code. -- https://mail.python.org/mailman/listinfo/python-list
Re: The perils of multiple Pythons
On Mon, Apr 30, 2018 at 10:32 AM, Chris Angelico wrote: > On Tue, May 1, 2018 at 3:30 AM, Ned Batchelder > wrote: > > On 4/30/18 1:15 PM, Chris Angelico wrote: > >> > >> https://xkcd.com/1987/ > >> > >> So take-away is: On a Mac, just use Homebrew. > >> > >> (Cue the angry hordes telling me how wrong I am.) > >> > > > > My take-away (though not really, since I held this view before this > > morning): pick a way and stick to it. > > Well, yes. Until that way stops working, in which case you have to try > another way. And that's when the problems start... > > ChrisA > -- > https://mail.python.org/mailman/listinfo/python-list > I feel like this problem is pretty handily solved by virtual environments. Also, if a single project requires all of this, perhaps Python isn't the best choice for the project. -- https://mail.python.org/mailman/listinfo/python-list
Re: The perils of multiple Pythons
On Mon, Apr 30, 2018 at 1:40 PM, Chris Angelico wrote: > On Tue, May 1, 2018 at 6:22 AM, justin walters > wrote: > > On Mon, Apr 30, 2018 at 10:32 AM, Chris Angelico > wrote: > > > >> On Tue, May 1, 2018 at 3:30 AM, Ned Batchelder > >> wrote: > >> > On 4/30/18 1:15 PM, Chris Angelico wrote: > >> >> > >> >> https://xkcd.com/1987/ > >> >> > >> >> So take-away is: On a Mac, just use Homebrew. > >> >> > >> >> (Cue the angry hordes telling me how wrong I am.) > >> >> > >> > > >> > My take-away (though not really, since I held this view before this > >> > morning): pick a way and stick to it. > >> > >> Well, yes. Until that way stops working, in which case you have to try > >> another way. And that's when the problems start... > >> > >> ChrisA > >> -- > >> https://mail.python.org/mailman/listinfo/python-list > >> > > > > I feel like this problem is pretty handily solved by virtual > environments. > > Also, if a single project requires all of this, > > perhaps Python isn't the best choice for the project. > > Some of it is definitely solved by venvs. But which Python binary do > you use? And is venv installed? Do you need to install virtualenv > first? How do you... etc, etc, etc, etc, etc. Endless fun! > > ChrisA > -- > https://mail.python.org/mailman/listinfo/python-list > With Python 3.5+, venv is a built in module. If using a venv, default to using the binary in the venv. That's what I do anyways. -- https://mail.python.org/mailman/listinfo/python-list
Re: The perils of multiple Pythons
On Mon, Apr 30, 2018 at 3:24 PM, Rich Shepard wrote: > On Mon, 30 Apr 2018, justin walters wrote: > > With Python 3.5+, venv is a built in module. If using a venv, default to >> using the binary in the venv. That's what I do anyways. >> > > I'm running Python3-3.6.5 and have a developing application in > ~/development/project/. Can I run 'python3 -m venv ~/development/project/' > to install it in a directory with existing modules? > > Rich > -- > https://mail.python.org/mailman/listinfo/python-list > Yes, you can create a virtual env with all of the global packages. Though, you would probably want to run: `python3 -m venv ~/development/project/venv` to put the virtualenv files in their own directory. Then you just need to activate it with: `source venv/bin/activate`. As long as the virtualenv is activated, you can interact with it in the same way you would with the system/global environment. i.e. running the interpreter will use the binary from the virtualenv, pip install will install in the virtualenv only, etc. -- https://mail.python.org/mailman/listinfo/python-list
Re: Introducing Coconut
On Sun, Jun 24, 2018 at 5:51 AM, Steven D'Aprano < steve+comp.lang.pyt...@pearwood.info> wrote: > Coconut, the functional programming language which compiles to Python: > > http://coconut.readthedocs.io/en/master/FAQ.html > > http://coconut-lang.org/ > > (Its not my language. I just think its cool.) > > > -- > Steven D'Aprano > "Ever since I learned about confirmation bias, I've been seeing > it everywhere." -- Jon Ronson > > -- > https://mail.python.org/mailman/listinfo/python-list > As someone who has been studying Elixir and Phoenix lately, This is pretty neat. There have definitely been some pieces of my Python projects that could have benefited from a Functional structure. I don't think writing an entire project in Cocounut would be worth while. At that point, why not use an actual FP language? However, I do think it sounds useful for when certain parts of a project could be cleaned up or optimized with functional code. Almost like a better `functools`. All that said though, I am interested to see performance metrics for the transpiled python. -- https://mail.python.org/mailman/listinfo/python-list
Re: Introducing Coconut
From: justin walters On Sun, Jun 24, 2018 at 5:51 AM, Steven D'Aprano < steve+comp.lang.pyt...@pearwood.info> wrote: > Coconut, the functional programming language which compiles to Python: > > http://coconut.readthedocs.io/en/master/FAQ.html > > http://coconut-lang.org/ > > (Its not my language. I just think its cool.) > > > -- > Steven D'Aprano > "Ever since I learned about confirmation bias, I've been seeing > it everywhere." -- Jon Ronson > > -- > https://mail.python.org/mailman/listinfo/python-list > As someone who has been studying Elixir and Phoenix lately, This is pretty neat. There have definitely been some pieces of my Python projects that could have benefited from a Functional structure. I don't think writing an entire project in Cocounut would be worth while. At that point, why not use an actual FP language? However, I do think it sounds useful for when certain parts of a project could be cleaned up or optimized with functional code. Almost like a better `functools`. All that said though, I am interested to see performance metrics for the transpiled python. --- BBBS/Li6 v4.10 Toy-3 * Origin: Prism bbs (1:261/38) -- https://mail.python.org/mailman/listinfo/python-list
Re: Which are best, well-tested ways to create REST services, with Json, in Python?
On Mon, Mar 28, 2016 at 2:06 PM, David Shi via Python-list < python-list@python.org> wrote: > Has anyone done a recent reviews of creating REST services, in Python? > Regards. > David > -- > https://mail.python.org/mailman/listinfo/python-list > There are a ton of different ways to do this. Can you provide some details about the application? -- https://mail.python.org/mailman/listinfo/python-list
Re: Which are best, well-tested ways to create REST services, with Json, in Python?
On Mon, Mar 28, 2016 at 5:17 PM, David Shi wrote: > Hello, Justin, > > I am thinking of a fast, responsive, secure way of doing this. Python at > server-side. It provides REST services. Data exchange with the > web--page. Formatted XML or Json. > > Ideally, it uses the least code. > > Any excellent literature describes this? I like articles which give > insight into the nitty-gritty. > > Looking forward to hearing from you. > > Regards. > > Shao > > > > David, Please reply all on this list. My preferred method is to use Django with Django Rest Framework. Django is a very mature and robust framework with a ton of features. I use it in production for several projects and have very few issues. It includes middleware authentication and security features as well. You can find the Django documentation here: https://docs.djangoproject.com/en/1.9/. If you've never used Django before, I recommend going through the official tutorial. It is also advised to use Python 3.4+. Django rest framework is probably one of the best documented packages out there. You can find it's documentation here: http://www.django-rest-framework.org/. The official tutorial is very in-depth. I would recommend working through it as well. DRF includes a lot of functionality and multiple authentication and serialization methods. There are other options as well depending on the scale of your project you may choose to use something like flask: http://flask.pocoo.org/ with flask-restful and sqlalchemy. Like I said my personal recommendation is Django and DRF as it is easy to set up, there isn't much overhead, and it scales very well. Does that answer your question, or were you looking for more information? -- https://mail.python.org/mailman/listinfo/python-list
Re: Which are best, well-tested ways to create REST services, with Json, in Python?
Hi David, once again, please reply all on this list. I sent you a couple of step by step guides. Pleas look at the links that I sent. On Mon, Mar 28, 2016 at 9:12 PM, David Shi wrote: > Hello, Justin, > > Is there any official step by step guide. > > Send me the download link and link to Official tutorial. > > Regards. > > David > > > On Tuesday, 29 March 2016, 2:35, justin walters < > walters.justi...@gmail.com> wrote: > > > > > On Mon, Mar 28, 2016 at 5:17 PM, David Shi wrote: > > Hello, Justin, > > I am thinking of a fast, responsive, secure way of doing this. Python at > server-side. It provides REST services. Data exchange with the > web--page. Formatted XML or Json. > > Ideally, it uses the least code. > > Any excellent literature describes this? I like articles which give > insight into the nitty-gritty. > > Looking forward to hearing from you. > > Regards. > > Shao > > > > > > David, > > Please reply all on this list. > > My preferred method is to use Django with Django Rest Framework. Django is > a very mature and robust framework with a ton of features. I use it in > production for several projects and have very few issues. It includes > middleware authentication and security features as well. You can find the > Django documentation here: https://docs.djangoproject.com/en/1.9/. If > you've never used Django before, I recommend going through the official > tutorial. It is also advised to use Python 3.4+. > > Django rest framework is probably one of the best documented packages out > there. You can find it's documentation here: > http://www.django-rest-framework.org/. The official tutorial is very > in-depth. I would recommend working through it as well. DRF includes a lot > of functionality and multiple authentication and serialization methods. > > > There are other options as well depending on the scale of your project you > may choose to use something like flask: http://flask.pocoo.org/ with > flask-restful and sqlalchemy. > > Like I said my personal recommendation is Django and DRF as it is easy to > set up, there isn't much overhead, and it scales very well. > > Does that answer your question, or were you looking for more information? > > > > -- https://mail.python.org/mailman/listinfo/python-list
Re: ANN: Python 201 - Intermediate Python book
On Mar 30, 2016 8:41 AM, "Mike Driscoll" wrote: > > Hi, > > I just wanted to let you know that I am hard at work on my second book, which is entitled Python 201 which will come out this Fall 2016. I currently have a Kickstarter going where you can pre-order the book: https://www.kickstarter.com/projects/34257246/python-201-intermediate-python > > I actually posted to this list last year about what you would consider to be intermediate topics in Python. From that discussion and from some ideas I had already been working, this book was born. The book is aimed for people who already know the basics of Python but would like to learn more. It is also written with Python 3 in mind. > > Let me know if you have any questions. > > Thanks, > Mike Driscoll > > -- > https://mail.python.org/mailman/listinfo/python-list Can you go over a couple of the topics you are going to cover? Are you going to cover any of the most popular packages such as Django and scrapy? -- https://mail.python.org/mailman/listinfo/python-list
Re: ANN: Python 201 - Intermediate Python book
On Mar 30, 2016 11:21 AM, "Mike Driscoll" wrote: > > Hi Justin, > > > > https://mail.python.org/mailman/listinfo/python-list > > > > Can you go over a couple of the topics you are going to cover? > > > > Are you going to cover any of the most popular packages such as Django and > > scrapy? > > Sure! I'm planning on covering several of the more popular intermediate-level modules from Python's standard library, such as collections, contextlib, functools and itertools. > > I am also going to be covering benchmarking, encryption, connecting to databases, etc. > > There is a section on Web-related chapters. While I don't plan to cover a web framework, I am going to cover other items related to working with the internet using Python. I do plan to talk about creating a web crawler / scraper, but I hadn't decided if I was going to use scrapy for that or not. I also plan to write about working with web APIs, such as Amazon's or Google's APIs. There will probably be some kind of chapter about Selenium / Web Driver too. I have some other ideas too. > > I hope that answered your question. > > Mike > -- > https://mail.python.org/mailman/listinfo/python-list That absolutely answers my questions. I'll keep an eye out for your book when it is realeased. It seems like it will cover some topics that could be useful in continuing my learning. I am especially interested in encryption as that is something I have yet to dive into. -- https://mail.python.org/mailman/listinfo/python-list
Django Channels examples
To all of my Web developer bros and broettes, You all should check out this github repo: https://github.com/andrewgodwin/channels-examples This is not my repo or my work. Channels is a package for Django that allows Django to work more easily with websockets through an asgi interface. The Django devs intend to add Channels into the core packages with the next major release. The linked repo contains 2 examples. One is a live blogging application, and one is a live chat application. I just typed out all of the code to build the chat application myself and it works well. It was a fun exercise. If you are interested in websocket applications with Python, I highly recommend checking it out. Let me know if this kind of thing does not belong on this list. I'm just really excited about this. -- https://mail.python.org/mailman/listinfo/python-list
Re: mod_wsgi not compatible with Wamp 2.4 and python 3.4.3
On Apr 5, 2016 12:51 PM, "asimkon ." wrote: > > I am using Apache to develop Python Web applications via Django. As i am > new to python web development, i am having problem to find the right > version for mod_wsgi.so (compiled version for Apache 2.4.4 - WampServer 2.4 > - and python 3.4.3 latest version from ActivePython on Windows x86) and i > get a 500 internal server error "The server encountered an internal error > or misconfiguration and was unable to complete your request". > > when i try to run the following script: > > def application(environment, start_response): > status = '200 OK' > response_headers = [('Content-type', 'text/html')] > start_response(status, response_headers) > page = """ > > > Hello world! > This is being served using mod_wsgi > > > """ > return page > > I just found the following link > http://grapevine.dyndns-ip.com/download/folder.asp?eid=33&folder=%2Fdownload%2Fapache%2Fmod_wsgi-windows-4.4.6%2Fmod_wsgi-windows-4.4.6%2Fapache24-win32-vc10%2Fmodules%2F > but unfortunately i have got incompatibility problems with the compiled > files mentioned. Any kind of help would be convenient to me. > > I am looking for the compiled (.so file) version, as it will save me from a > lot of trouble. > > Regards > Kostas Asimakopoulos > -- > https://mail.python.org/mailman/listinfo/python-list Have you tried using apache as a proxy server to forward requests to a dedicated wsgi server such as gunicorn instead of using mod_wsgi? I find it's a lot easier to set up. -- https://mail.python.org/mailman/listinfo/python-list
Re: mod_wsgi not compatible with Wamp 2.4 and python 3.4.3
On Wed, Apr 6, 2016 at 3:57 AM, asimkon . wrote: > I managed to connect Apache 2.2 with django framework successfully using > Python 2.7 and mod_wsgi.so (Apache module) thanks to the instructions from > https://pusonchen.wordpress.com/2013/06/03/build-django-website-with-apache-mod_wsgi-on-windows/. > The problem is that i see the Django project Web page using localhost or > 127.0.0.1 in my browser. > I want to change it to localhost/mysite as i have built other projects in > php with Apache (WampServer) using Cakephp and other php scripts. Is there > any way or i will have to sacrifice my entire Apache Web server for just > only Django project? > Afterwards i just download > https://dev.mysql.com/downloads/connector/python/ (MySQL driver) install > it and play with syncdb to create tables in my MySQL database. I create the > db using phpmyadmin and import the info in my settings.py django project > folder. > > Regards > Kostas Asimakopoulos > So, you are running this on your local machine then? I did some quick googling for you because I wasn't sure if Apache could run mod_php and mod_wsgi together. Apparently it can. See this google search: https://www.google.com/search?client=ubuntu&channel=fs&q=can+apache+run+mod_php+and+mod_wsgi+at+the+same+time%3F&ie=utf-8&oe=utf-8 The basic premise is that you set one port to your php application, and another port to your Python application. So, if you visit, say 127.0.0.1:80, you will arrive at your php application. If you instead visit 127.0.0.1:8000, you will arrive at your Python application. Unfortunately, I do not believe there is any way to have both applications listen on the same port. You could, however, create an alias so that when you visit 'htttp://localhost/mysite' it actually points to 127.0.0.1:8000 which is the port for your Python application. >Afterwards i just download https://dev.mysql.com/downloads/connector/python/ (MySQL driver) install it and play with syncdb to create tables in my MySQL database. I create the db using phpmyadmin and import the info in my settings.py django project folder. Can you explain this further? Are you not using the Django ORM? -- https://mail.python.org/mailman/listinfo/python-list
Looking for feedback on weighted voting algorithm
Hi all, I'm looking for feedback on the below vote weighting algorithm which includes sample input. This is written in Python3. def weight(votes): """ Takes a list of tuples in the form of '(vote %, weight)' where vote % is the rating that a user gave and weight is the number of votes it counts as. Returns the average score based on votes and vote weight. """ sum_of_votes = 0 num_of_votes = 0 for vote, weight in votes: sum_of_votes += vote * weight num_of_votes += weight score = sum_of_votes/num_of_votes return score if __name__ == '__main__': votes = [(72, 4), (96, 3), (48, 2), (53, 1), (26, 4), (31, 3), (68, 2), (91, 1)] print(weight(votes)) Specifically, I'm wondering if this is a good algorithm for weighted voting. Essentially a vote is weighted by the number of votes it counts as. I realize that this is an extremely simple algorithm, but I was wondering if anyone had suggestions on how to improve it. Thank you for your time. -- https://mail.python.org/mailman/listinfo/python-list
Re: Looking for feedback on weighted voting algorithm
On Apr 14, 2016 9:41 AM, "Martin A. Brown" wrote: > > > Greetings Justin, > > >score = sum_of_votes/num_of_votes > > >votes = [(72, 4), (96, 3), (48, 2), (53, 1), (26, 4), (31, 3), (68, 2), (91, 1)] > > >Specifically, I'm wondering if this is a good algorithm for > >weighted voting. Essentially a vote is weighted by the number of > >votes it counts as. I realize that this is an extremely simple > >algorithm, but I was wondering if anyone had suggestions on how to > >improve it. > > I snipped most of your code. I don't see anything wrong with your > overall approach. I will make one suggestion: watch out for > DivisionByZero. > > try: > score = sum_of_votes / num_of_votes > except ZeroDivisionError: > score = float('nan') > > In your example data, all of the weights were integers, which means > that a simple mean function would work, as well, if you expanded the > votes to an alternate representation: > > votes = [72, 72, 72, 72, 96, 96, 96, 48, 48, 53, 26, 26, 26, 26, >31, 31, 31, 68, 68, 91] > > But, don't bother! > > Your function can handle votes that have a float weight: > > >>> weight([(4, 1.3), (1, 1),]) > 2.695652173913044 > > Have fun! > > -Martin > > -- > Martin A. Brown > http://linux-ip.net/ Thanks Martin! I'll add the check for division by zero. Didn't think about that. I think I'm going to sanitize input anyways, but always better to be safe than sorry. -- https://mail.python.org/mailman/listinfo/python-list
Re: I have been dealing with Python for a few weeks...
On Thu, Apr 14, 2016 at 1:50 PM, Fillmore wrote: > > ...and I'm loving it. > > Sooo much more elegant than Perl...and so much less going back to the > manual to lookup the syntax of simple data structures and operations... > > REPL is so useful > > and you guys rock too > > cheers > -- > https://mail.python.org/mailman/listinfo/python-list > Good to hear you're enjoying it. Out of curiosity, what were you using Perl for? -- https://mail.python.org/mailman/listinfo/python-list
Re: Looking for feedback on weighted voting algorithm
Thanks for the advice and the code Michael. That's definitely a clever way to do it. The algorithm is going to be used for a web application, so the inputs should be sanitized for security reasons. It will be trivial to make sure the inputs are integers and are in the correct range. I will raise a DivisionByZero error for clarity. I plan to have the result stored in the cache and then transferred to the db after every new vote, so this algorithm could see some heavy use for short periods of time. Therefore, performance is important for me. I believe the algorithm that I provided is O(n) or O(n+1), but I never really studied Compsci, so I'm not sure. Either way, I think it should perform well enough. On Thu, Apr 14, 2016 at 1:48 PM, Michael Selik wrote: > > > On Thu, Apr 14, 2016, 7:37 PM justin walters > wrote: > >> On Apr 14, 2016 9:41 AM, "Martin A. Brown" wrote: >> > >> > >> > Greetings Justin, >> > >> > >score = sum_of_votes/num_of_votes >> > >> > >votes = [(72, 4), (96, 3), (48, 2), (53, 1), (26, 4), (31, 3), (68, 2), >> (91, 1)] >> > >> > >Specifically, I'm wondering if this is a good algorithm for >> > >weighted voting. Essentially a vote is weighted by the number of >> > >votes it counts as. I realize that this is an extremely simple >> > >algorithm, but I was wondering if anyone had suggestions on how to >> > >improve it. >> > >> > I snipped most of your code. I don't see anything wrong with your >> > overall approach. I will make one suggestion: watch out for >> > DivisionByZero. >> > >> > try: >> > score = sum_of_votes / num_of_votes >> > except ZeroDivisionError: >> > score = float('nan') >> > >> > In your example data, all of the weights were integers, which means >> > that a simple mean function would work, as well, if you expanded the >> > votes to an alternate representation: >> > >> > votes = [72, 72, 72, 72, 96, 96, 96, 48, 48, 53, 26, 26, 26, 26, >> >31, 31, 31, 68, 68, 91] >> > >> > But, don't bother! >> > >> > Your function can handle votes that have a float weight: >> > >> > >>> weight([(4, 1.3), (1, 1),]) >> > 2.695652173913044 >> > >> > Have fun! >> > >> > -Martin >> > >> > -- >> > Martin A. Brown >> > http://linux-ip.net/ >> >> Thanks Martin! >> >> I'll add the check for division by zero. Didn't think about that. I think >> I'm going to sanitize input anyways, but always better to be safe than >> sorry. >> > > I suggest not worrying about sanitizing inputs. If someone provides bad > data, Python will do the right thing: stop the program and print an > explanation of what went wrong, often a more helpful message than one you'd > write. Use error handling mostly for when you want to do something *other* > than stop the program. > > I'm not sure I'd use NaN instead of raise division by zero error. NaNs can > be troublesome for downstream code that might not notice until it gets > confusing. A div-by-zero error is clear and easier to track down because of > the traceback. > > What do you think of using list comprehensions? > > weighted_sum = sum(rating * weight for rating, weight in votes) > total_weights = sum(weight for rating, weight in votes) > score = weighted_sum / total_weights > > It's two loops as I wrote it, which is instinctively slower, but it might > actually execute faster because of the built-in sum vs a regular for loop. > Not sure. > >> -- https://mail.python.org/mailman/listinfo/python-list
Re: Static files load problem Django 1.9
On Fri, Apr 15, 2016 at 5:13 AM, asimkon . wrote: > I have got a problem with static files regarding Django 1.9. These files > are (js,css) in the standard folder static, inside project folder > directory. I got an error Http 404 that can not be loaded. > > Project folder / static / css / several files *.css > /static / js / several files *.js > several_apps > > i have executed the python manage.py collectstatic > > settings.py > > STATIC_URL = '/static/' > > STATIC_ROOT = os.path.join(BASE_DIR, "static") > > STATICFILES_DIRS = ( > > os.path.join(BASE_DIR, 'static'), > ) > > and of course as INSTALLED_APPS > > 'django.contrib.staticfiles', > > Sorry for my template (at the beginning of my work): > > {% load staticfiles %} > > > > > > type="text/javascript"> > type="text/javascript"> > type="text/javascript"> > > > > > > > > > > > > but i am afraid the problem lies in urls.py (i do not know what to do) > > http://127.0.0.1:8000/static/css/file_name (in the firebug network) but > i > can not open it directly via server. > > urls.py > > urlpatterns = [ > url(r'^admin/', admin.site.urls), > url(r'^hello/','category.views.hello'), > ] > > > Any kind of help would be convenient to me? > > Kind Regards > Kostas Asimakopoulos > -- > https://mail.python.org/mailman/listinfo/python-list > You shouldn't need a special pattern in your urls for static files. I think your issue lies with your STATIC_ROOT setting. It is the same as your STATICFILES_DIRS setting. Try changing the STATIC_ROOT setting to: STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static') This will put the static root outside of your project folder. This may solve your problem, and will make it easier to host static files somewhere else on your server or in a CDN if need be. -- https://mail.python.org/mailman/listinfo/python-list
Re: PEP proposal: sequence expansion support for yield statement: yield *
I agree with the others that the new syntax is not needed. I would also like to point out that I believe any new added syntax or functionality should avoid the use of '*' and '**' as both of these characters are already used for many things such as optional arguments and mathematical operators. Adding more uses for said characters only decreases the readability of the code. -- https://mail.python.org/mailman/listinfo/python-list
Re: Error 0*80070570
On Thu, Apr 21, 2016 at 2:06 AM, Allan Leo wrote: > When running the setup for your 3.5.1(32-bit version), the setup > experiences error 0*80070570 and tells me to check the log file. What could > be the problem and whats the solution. > On Apr 21, 2016 7:05 AM, "Allan Leo" wrote: > > > When running the setup for your 3.5.1(32-bit version) the setup > > experiences error 0*80070570 and tells me to checkout the log file. What > > could be the problem and whats the resolution. > > > -- > https://mail.python.org/mailman/listinfo/python-list > Have you tried checking the log file or googling the error code? -- https://mail.python.org/mailman/listinfo/python-list
Re: Writing different sections into a file
On Mon, Apr 25, 2016 at 3:04 AM, Karim wrote: > > > On 25/04/2016 09:30, Palpandi wrote: > >> Hi, >> >> I need to write different sections into a file. >> At any point of time, content can be added to any section. >> >> I don't want keep each section into a temporary file. >> What is the better way to store the contents of each section and write >> them into a file at the end? >> What is the better datatype to achieve this? >> >> >> Thanks and Regards, >> Palpandi >> > > Use Stringio: > - > > from cStringIO import StringIO > > content = StringIO() > > # Header > content.write('; Header\n') > content.write('; Body'\n) > content.write('; Footer\n') > > open('my_file', 'wb').write(content.getvalue()) > > - > Karim > > > -- > https://mail.python.org/mailman/listinfo/python-list > All of the other answers are great too. I was thinking that you could format the text file to have dividers for each section. For instance it may look something like this: Header Lorem ipsum <---> Body Lorem ipsum... <---> Footer Lorem ipsum.. Then, you could create a list of sections like so: file = open('file.txt', 'r').read() section_list = file.split('<--->') print(section_list[0]) >>> Header Lorem ipsum... Say you wanted to get really fancy, you could even format the file to have named sections like so: Lorem ipsum... Lorem ipsum... Lorem ipsum... Then you can use the xmlparser library to parse the file into an xml object. Alternatively, you could also use JSON formatting: { sections: { header: { title: "header", content: "Lorem ipsum..." }, body: { title: "Body", content: "Lorem ipsum..." }, footer: { title: "Footer", content: "Lorem ipsum..." } } } I hope this helps. -- https://mail.python.org/mailman/listinfo/python-list
Re: how to create a dictionary from csv file?
On Tue, Apr 26, 2016 at 7:18 AM, +dime+ wrote: > I am learning python. > > if I have a csv file, like this > banana,4.0 > apple,3.5 > orange,3.0 > > Can anyone show me how to read the csv file line by line and then create a > dictionary to contain these keys and values? > > > Regards, > +dime+ > -- > https://mail.python.org/mailman/listinfo/python-list > It's best if you look up how to do this in the docs yourself. An even better way would be to think about the steps necessary to do this and then writing them down in pseudo-code. After that you can look up the functions/tools that will help you accomplish this task. One of the most important skills a programmer can have is called 'algorithmic thinking'. That is, essentially, the ability to break a problem down into smaller pieces in order to eventually solve it. So, think about this: What steps do you need to take to turn this csv file into a Python dictionary object? Imagine that you were going to do this by hand. How would you do it? -- https://mail.python.org/mailman/listinfo/python-list
Re: online python courses
On Thu, Apr 28, 2016 at 7:57 AM, Joel Goldstick wrote: > On Thu, Apr 28, 2016 at 10:15 AM, wrote: > > I am follows on this moment two online pythoncourses from > code.tutsplus.com > > But I am interested in following more online pythoncourses. > > Maby someone have some links to websites for me what handles python > online courses. > > > > thanks > > -- > > https://mail.python.org/mailman/listinfo/python-list > > Try here: > > http://lmgtfy.com/?q=python+online+courses#seen > > > -- > Joel Goldstick > http://joelgoldstick.com/blog > http://cc-baseballstats.info/stats/birthdays > -- > https://mail.python.org/mailman/listinfo/python-list > SICP in Python: http://composingprograms.com/ -- https://mail.python.org/mailman/listinfo/python-list
Re: Best way to clean up list items?
On May 2, 2016 10:03 AM, "Jussi Piitulainen" wrote: > > DFS writes: > > > Have: list1 = ['\r\n Item 1 ',' Item 2 ','\r\n '] > > Want: list1 = ['Item 1','Item 2'] > > > > > > I wrote this, which works fine, but maybe it can be tidier? > > > > 1. list2 = [t.replace("\r\n", "") for t in list1] #remove \r\n > > 2. list3 = [t.strip(' ') for t in list2]#trim whitespace > > 3. list1 = filter(None, list3) #remove empty items > > > > After each step: > > > > 1. list2 = [' Item 1 ',' Item 2 ',' '] #remove \r\n > > 2. list3 = ['Item 1','Item 2',''] #trim whitespace > > 3. list1 = ['Item 1','Item 2'] #remove empty items You could also try compiled regex to remove unwanted characters. Then loop through the list and do a replace for each item. -- https://mail.python.org/mailman/listinfo/python-list
Re: python - handling HTTP requests asynchronously
On Thu, May 5, 2016 at 11:56 PM, wrote: > Hi everyone, > I need to generate a PDF report for each entry of a django queryset. > There'll be between between 30k and 40k entries. > > The PDF is generated through an external API. Since currently is generated > on demand, this is handled synchronously via an HTTP request/response. That > will be different for this task, since I think I'll use a django management > command to loop through the queryset and perform the PDF generation. > > Which approach should I follow for this task? I thought about 3 possibile > solutions, although are technologies that I never used: > > 1) Celery: assign a task (http request with a different payload) to a > worker, then retrieve it once it's done. > > 2) request-futures: using requests in a non-blocking way. > > 3) multiprocessing module, with e.g. 10 as workers limit. > > > the goal is to use the API concurrently (e.g. send 10 or 100 http requests > simultaneously, depending on how many concurrent requests the API can > handle). > > Anybody here that handled a similar task and can give advices on how to > proceed on this? > -- > https://mail.python.org/mailman/listinfo/python-list > Have you tried channels: https://github.com/andrewgodwin/channels ? If it's an asyncronous request/response cycle you're looking for, it should work well. Essentially, you have worker processes that receive a message over a websocket connection and then send the new message back to the "group". I would recommend using the redis in memory transaction layer if you go this route as it is the fastest and most efficient. The best part about channels is that you can still run a normal django app alongside it. You can have only one app use websockets while the rest use standard http.. -- https://mail.python.org/mailman/listinfo/python-list
Re: html & python connection problem with hyperlinks
On Wed, May 25, 2016 at 3:24 AM, wrote: > Why not created the field title, that located on the template > BusinessList.html as a link to go to Business_Detail.html..? please check > > Code: > > models. py: > > from django.db import models > > > REGIONS = ( > ('ΘΕΣ', 'ΘΕΣΣΑΛΟΝΙΚΗ'), > ('ΣΕΡ', 'ΣΕΡΡΕΣ'), > ( 'ΑΘΗ', 'ΑΘΗΝΑ'), > > > > TYPEOFBUSINESS = ( > ('ΕΣΤ', 'ΕΣΤΙΑΤΟΡΙΑ'), > ('ΦΑΡ', 'ΦΑΡΜΑΚΕΙΑ'), > ('ΒΙΒ', 'ΒΙΒΛΙΟΠΩΛΕΙΑ'), > ( 'ΚΟΜ', 'ΚΟΜΜΩΤΗΡΙΑ'), > ('ΣΙΝ', 'ΣΙΝΕΜΑ') > > ) > > class Business(models.Model): > created_Date = models.DateTimeField(auto_now_add=True) > owner = models.ForeignKey('auth.User', related_name='snippets', null=True) > title = models.CharField(max_length=100, blank=True, default='') > Type_of_Business = models.CharField(max_length=3, choices=TYPEOFBUSINESS) > region = models.CharField(max_length=3, choices=REGIONS) > address = models.CharField(max_length=100, blank=True, default='') > phone = models.CharField(max_length=15, blank=True, default='') > image = models.ImageField(null=True) > > > def __str__(self): > return str(self.title) > > views.py > > from django.contrib.auth.models import User > from django.http import HttpResponse > from django.shortcuts import render, get_object_or_404 > from rest_framework import filters > from rest_framework import generics > from rest_framework import permissions > from snippets.permissions import IsOwnerOrReadOnly > from snippets.serializers import SnippetSerializer > from snippets.serializers import UserSerializer > from .models import Business > > > > class UserList(generics.ListAPIView): > queryset = User.objects.all() > serializer_class = UserSerializer > > > class UserDetail(generics.RetrieveAPIView): > queryset = User.objects.all() > serializer_class = UserSerializer > > class BusinessList(generics.ListCreateAPIView): > > permission_classes = (permissions.IsAuthenticatedOrReadOnly,) > queryset = Business.objects.all() > serializer_class = SnippetSerializer > filter_backends = (filters.DjangoFilterBackend,filters.SearchFilter, > filters.OrderingFilter,) > filter_fields = ('Type_of_Business', 'region') > search_fields = ('Type_of_Business', 'region') > ordering_fields = ('Type_of_Business','title', 'region') > > > def BusinessList(request): > business = Business.objects.all(); > return render(request, 'snippets/BusinessList.html' {'business':business}) > > def perform_create(self, serializer): > serializer.save(owner=self.request.user) > > > > class Business_Detail(generics.RetrieveUpdateDestroyAPIView): > permission_classes = (permissions.IsAuthenticatedOrReadOnly, > IsOwnerOrReadOnly,) > queryset = Business.objects.all() > serializer_class = SnippetSerializer > > > def Business_Detail(request, pk): > business = get_object_or_404(Business, pk=pk) > return render(request, 'snippets/Business_Detail.html', {'business': > business}) > > serializers.py > > from rest_framework import serializers > from snippets.models import Business > from django.contrib.auth.models import User > > > class SnippetSerializer(serializers.HyperlinkedModelSerializer): > owner = serializers.ReadOnlyField(source='owner.username') > > class Meta: > model = Business > fields = ('created_Date', 'owner', 'title','Type_of_Business', 'region', > 'address', 'phone', 'image') > > > class UserSerializer(serializers.ModelSerializer): > snippets = serializers.PrimaryKeyRelatedField(many=True, > queryset=Business.objects.all()) > > class Meta: > model = User > fields = ('id', 'username', 'snippets') > > BusinessList.html > > {% extends 'snippets/base.html' %} > > {% block content %} > {% for business in business%} > > > {{ business.created_Date }} #τυπωσε ημερ.δημιουργιας του Business > > {{ > business.title }} > {{business.Type_of_Business }} > {{ business.region }} > {{ business.address }} > {{ business.phone }} > {% if business.image %} > > {% endif %} > > {% endfor %} > {% endblock %} > > Business_Detail.html > > {% extends 'snippets/base.html' %}' %} > > {% block content %} > > {% if business.created_Date %} # αν υπαρχει ημερομηνια δημιουργίας > > {{ business.created_Date }} > > {% endif %} > {{ business.title }} > {{ business.region }} > {{ business.Type_of_Business}} > {{ business.phone }} > > {% if business.image %} # αν υπαρχει εικονα > # παρε εικονα απο το αντιστοιχο url > {% endif %} > > > {% endblock %} > > tutorial/snippets/urls.py > > from django.conf.urls import url, include > from django.contrib import admin > from rest_framework.urlpatterns import format_suffix_patterns > from django.contrib.staticfiles.urls import staticfiles_urlpatterns > from django.conf.urls import include > > from . import views > > urlpatterns = [ > url(r'^admin/', include(admin.site.urls)), > url(r'^$', views.BusinessList.as_view()), > url(r'^business/(?P[0-9]+)/$', views.Business_Detail.as_view()), > url(r'^users/$', views.UserList.as_view()), > url(r'^users/(?P[0-9]+)/$', views.UserDetail.as_view()), > url(r'^api-auth/', include('rest_framework.urls', > namespace=
Re: Tie dictionary to database table?
It looks like you might be looking for an ORM. Have you checked out sqlalchemy? -- https://mail.python.org/mailman/listinfo/python-list
Django Tastypie Vs. Djaogn Rest Framework
Hi guys and gals. I've been building a new web application with my business partner. We're using Django and postreSQL. We needed a restful API as we wanted the back end to be completely decoupled from the front end. We ended up going with Tastypie over DRF due to the former being seemingly less complex and easier to get rolling. I've used DRF in the past and found it to have somewhat of a steeper learning curve compared to Tastypie. The way tastypie has you define resources seems a lot more intuitive to me than the way DRF does so. Despite my experience, it seems like DRF is by far the more popular choice for new applications. I was wondering if anyone could offer some insights into why this is the case. Does DRF offer more highly optimized queries? -- https://mail.python.org/mailman/listinfo/python-list
Re: Just starting to learn Python, and encounter a problem
: On Jul 22, 2016 7:46 AM, "Gordon Levi" wrote: > > Zagyen Leo wrote: > > >yeah, it may be quite simple to you experts, but hard to me. > > > >In one of exercises from the Tutorial it said: "Write a program that asks the user their name, if they enter your name say "That is a nice name", if they enter "John Cleese" or "Michael Palin", tell them how you feel about them ;), otherwise tell them "You have a nice name." > > > >And i write so: > > > >name = input("Enter your name here: ") > >if name == "John Cleese" or "Michael Palin": > >print("Sounds like a gentleman.") > >else: > >print("You have a nice name.") > > > >But strangely whatever I type in (e.g. Santa Claus), it always say "Sounds like a gentleman.", not the result I want. > > The second line should be > if name == "John Cleese" or name == "Michael Palin": > > As discussed in recent lengthy thread in this group the following > line, and hence your statement, is always true - > > If "Michael Palin": > -- > https://mail.python.org/mailman/listinfo/python-list The easiest way to right this would be to use a tuple like so: if name in ('John Cleese', 'Michael Palin'): print ('They sound like a gentleman') -- https://mail.python.org/mailman/listinfo/python-list
Re: learning python. learning defining functions . need help
On Fri, Jul 22, 2016 at 6:24 AM, Chris Angelico wrote: > On Fri, Jul 22, 2016 at 11:13 PM, Dennis Lee Bieber > wrote: > > Now... Going much beyond the assignment (if you were having > trouble > > with the assignment, this will seem like magic) [Python 2.7]: > > I'm not sure, but I think your code would become Py3 compatible if you > just change your prints. Which I'd recommend - it's not difficult to > just always print a single string, and most example code is ASCII-only > and has no difficulty with the bytes/unicode distinction. But, point > of curiosity... > > > class Refrigerator(object): > > def __init__(self, stock=None): > > if stock is None or type(stock) != type(dict()): > > self._stock = dict() > > else: > > self._stock = stock > > ... why do you call up "type(dict())"? Why not either just "dict" or > "type({})"? > > ChrisA > -- > https://mail.python.org/mailman/listinfo/python-list > Hi Chris, Try opening the interactive terminal on your command line and type the following: type({}) == dict() That should illustrate why. This is because simply typing '{}' could be interpreted as either a dict or a set. My interpreter defaults 'type({})' to 'dict', but it's best to not take the risk. You could also replace that line with: if stock is None or type(stock) != dict: -- https://mail.python.org/mailman/listinfo/python-list
Re: Final statement from Steering Council on politically-charged commit messages
I for one don't want to see politics involved in PL development. However, inclusivity isn't a political issue, it's a human rights issue. Do I agree with the PR, not exactly. However, I do think we as a community should be accommodating to people Whose use of the English language differs from the standard as long as the meaning is clear. This thread reads like a bunch of old fuddy duddies complaining about immigrants not speaking perfect English at a fast food restaurant. Feel free to ban me from the list if this doesn't meet your standards. On Mon, Aug 17, 2020, 9:03 PM wrote: > On Monday, August 17, 2020 at 1:26:33 PM UTC-5, Chris Angelico wrote: > > For context, see this commit: > > > > > https://github.com/python/peps/commit/0c6427dcec1e98ca0bd46a876a7219ee4a9347f4 > > > > The commit message is highly politically charged and is now a > > permanent part of the Python commit history. The Python Steering > > Council has this to say: > > > > > https://github.com/python/steering-council/issues/34#issuecomment-675028005 > > > > "The SC discussed this and ... we do not deplore the message." > > > > So now we know: go ahead and put all the political messages you like > > into the commit messages, just don't put anything inappropriate into > > the content. White supremacy has been mentioned; who wants to pick the > > next hot topic? > > > > ChrisA > > It should be noted that these Darlings Of Conspicuous Caring are still > using that - gasp! - horrid "master' branch. The very idea ... > -- > https://mail.python.org/mailman/listinfo/python-list > -- https://mail.python.org/mailman/listinfo/python-list
Re: Final statement from Steering Council on politically-charged commit messages
I believe the commit message was written in bad faith. It reeks of virtue signaling. Commit messages should remain purely technical in nature. However, I do think the change itself is valid. I don't care about the style of comments as long as they are clear and communicate their message well. How is that determined? During the PR review process. If you are performing a review and a comment is so poorly written that you can't figure out what it means, request improvements. Non technical discussion should be left out of commit messages and issues. Instead, that sort of discussion should take place on mailing lists, forums, and in person. As a community, we need to be more open to discussing these sort of topics without resorting to condescending remarks. I apologize for being ageist earlier as well. That was out of line. On Tue, Aug 18, 2020, 9:36 AM Tim Daneliuk wrote: > On 8/17/20 1:26 PM, Chris Angelico wrote: > > For context, see this commit: > > > > > https://github.com/python/peps/commit/0c6427dcec1e98ca0bd46a876a7219ee4a9347f4 > > > > The commit message is highly politically charged and is now a > > permanent part of the Python commit history. The Python Steering > > Council has this to say: > > > > > https://github.com/python/steering-council/issues/34#issuecomment-675028005 > > > > "The SC discussed this and ... we do not deplore the message." > > > > So now we know: go ahead and put all the political messages you like > > into the commit messages, just don't put anything inappropriate into > > the content. White supremacy has been mentioned; who wants to pick the > > next hot topic? > > > > ChrisA > > > Just a few thoughts here ... > > - While languages evolve over time, _in any given moment_ there are better > and worse ways to express ideas in a given language. "The Elements Of > Style" > remains relevant today because it provides guidance on improving > written clarity. It is not some blind defence of the > perfect English. > > - Precision of language and precision of thought go hand in hand. Much > of the grousing about languages standards (in this case, hiding in > drag as social consciousness) is little more than intellectual laziness. > In actual fact, our discipline has burned a lot of intellectual > fuel in trying to find ways to be _more precise_ for things like > specifications, formal semantics, and the like. > > - It is my consistent experience when working with non-native English > speakers, that they wish to _improve_ their use and precision of the > language, not simplify it. > > - Why is English the only target of these social pieties? You never > hear these demands to relax these linguistic standards for, say, French, > German, or Spanish. Similarly, where is the outcry to make > Mandarin, Bantu, Swahili, or Arabic more approachable for > Westerners? > > Methinks there is an ideological skunk in the parlor ... > > > -- > https://mail.python.org/mailman/listinfo/python-list > -- https://mail.python.org/mailman/listinfo/python-list
Wits end with Python and cron
I’ve researched this problem for the last few days. Say I have the following script that I execute from cron on linux. Yes, the following runs quite fine from the command line: #! /bin/sh # /u01/app/oracle/product/10.1.0/Db_1/lib source /home/oracle/.bashrc PYTHONPATH=/usr/lib/python2.3:/usr/lib/python2.3/site-packages:/u01/app/oracle/product/10.1.0/Db_1/lib LD_LIBRARY_PATH=/u01/app/oracle/product/10.1.0/Db_1/lib PATH=${PATH}:${LD_LIBRARY_PATH}:${PYTHONPATH} echo "Load library is" echo ${LD_LIBRARY_PATH} echo "The python path is" echo ${PYTHONPATH} echo "The path itself is" echo ${PATH} rm /home/oracle/.error-log touch /home/oracle/.error-log echo "Starting python map script" cd /home/oracle/rods_dbf_file/ echo "changing directory" /usr/bin/python /home/oracle/rods_dbf_file/map_unix.py echo "python script run" And the error I continually get is: Traceback (most recent call last): File "/home/oracle/rods_dbf_file/map_unix.py", line 29, in ? import cx_Oracle ImportError: libclntsh.so.10.1: cannot open shared object file: No such file or directory What is going on? I’ve googled this thing to death and it seems like I’ve got two different solutions, PYTHONPATH and LD_LIBRARY_PATH, that should satisfy this. /u01/app/oracle/product/10.1.0/Db_1/lib is where the lib resides. Justin Del Vecchio Computer Engineer -- http://mail.python.org/mailman/listinfo/python-list
parsing a tuple in embedded python
I am returning a tuple from my python method and am stuck trying to figure out how to read it into a C array using PyArg_Parse. My C Code: int array[3]; PyArg_Parse(return, "(iii)", &array); My Python Code: mytuple = (1,2,3) return mytuple That gives me a segmentation fault. What am I doing wrong? -- http://mail.python.org/mailman/listinfo/python-list
Re: parsing a tuple in embedded python
Thanks Fredrik. Yes, I see now how the function works. I'm new to Python and the book I'm studying out of wasn't too explicit in how to handle arrays. I've changed the code to what you suggested, but strangely enough nothing got read into my array. If I return a single integer from my Python method, I get the expected return using: PyArg_Parse(return, "i", &integer); But, PyArg_Parse(return, "(iii)", array, array+1, array+2) and PyArg_Parse(return, "(iii)", &array[0], &array[1], &array[2]) does not alter "array" at all. Any ideas? Thanks Fredrik Lundh wrote: > [EMAIL PROTECTED] wrote: > > > I am returning a tuple from my python method and am stuck trying to > > figure out how to read it into a C array using PyArg_Parse. > > My C Code: > > int array[3]; > > PyArg_Parse(return, "(iii)", &array); > > > > My Python Code: > > mytuple = (1,2,3) > > return mytuple > > > > That gives me a segmentation fault. What am I doing wrong? > > you're not providing enough arguments; "iii" means three pointers, not > one. try: > > PyArg_Parse(return, "(iii)", array, array+1, array+2) > > instead. or, if you prefer maximum clarity: > > PyArg_Parse(return, "(iii)", &array[0], &array[1], &array[2]) > > (I assume you left out the error handling code; ignoring the return value > from PyArg_Parse is not a good idea) > > -- http://mail.python.org/mailman/listinfo/python-list
get current function name
See module inspect -- http://mail.python.org/mailman/listinfo/python-list
Re: what's wrong with "lambda x : print x/60,x%60"
Try lambda_hrs = lambda x: (x/60,x%60) -- http://mail.python.org/mailman/listinfo/python-list
pyparsing and LaTeX?
> Anyone parsing simple LaTeX constructs with pyparsing? Greetings Tim, Have always wanted a way to parse LaTeX myself. Unfortunately, I have been moved to a different project. However, I am still very much interested. Did you ever get a reply? -- http://mail.python.org/mailman/listinfo/python-list
MMTK Install Problem
Hello All, I am hoping that someone out there will be able to help me. During the "build" phase of MMTK installation, I receive the following series of errors: $ python setup.py build running build running build_py running build_ext building 'lapack_mmtk' extension gcc -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused-madd -fno-common -dynamic -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -DLIBM_HAS_ERFC -DEXTENDED_TYPES -IInclude -I/System/Library/Frameworks/Python.framework/Versions/ 2.3/include/python2.3 -c Src/lapack_mmtk.c -o build/temp.darwin-7.7.0-Power_Macintosh -2.3/Src/lapack_mmtk.o Src/lapack_mmtk.c:2:33: Numeric/arrayobject.h: No such file or directory Src/lapack_mmtk.c:6: warning: function declaration isn't a prototype Src/lapack_mmtk.c:11: warning: function declaration isn't a prototype Src/lapack_mmtk.c: In function `lapack_mmtk_CheckObject': Src/lapack_mmtk.c:29: warning: implicit declaration of function `PyArray_Check' Src/lapack_mmtk.c:34: error: `PyArrayObject' undeclared (first use in this function) Src/lapack_mmtk.c:34: error: (Each undeclared identifier is reported only once Src/lapack_mmtk.c:34: error: for each function it appears in.) Src/lapack_mmtk.c:34: error: parse error before ')' token Src/lapack_mmtk.c:34: error: `CONTIGUOUS' undeclared (first use in this function) Src/lapack_mmtk.c:39: error: parse error before ')' token Src/lapack_mmtk.c: In function `lapack_mmtk_dsyev': Src/lapack_mmtk.c:72: error: `PyArray_DOUBLE' undeclared (first use in this function) Src/lapack_mmtk.c:81: warning: implicit declaration of function `dsyev_' Src/lapack_mmtk.c:81: error: `PyArrayObject' undeclared (first use in this function) Src/lapack_mmtk.c:81: error: parse error before ')' token Src/lapack_mmtk.c:81: error: parse error before ')' token Src/lapack_mmtk.c:81: error: parse error before ')' token Src/lapack_mmtk.c: In function `lapack_mmtk_dgesvd': Src/lapack_mmtk.c:107: error: `PyArray_DOUBLE' undeclared (first use in this function) Src/lapack_mmtk.c:118: warning: implicit declaration of function `dgesvd_' Src/lapack_mmtk.c:118: error: `PyArrayObject' undeclared (first use in this function) Src/lapack_mmtk.c:118: error: parse error before ')' token Src/lapack_mmtk.c:118: error: parse error before ')' token Src/lapack_mmtk.c:118: error: parse error before ')' token Src/lapack_mmtk.c:118: error: parse error before ')' token Src/lapack_mmtk.c:118: error: parse error before ')' token Src/lapack_mmtk.c: At top level: Src/lapack_mmtk.c:134: warning: function declaration isn't a prototype Src/lapack_mmtk.c:132: warning: `lapack_mmtkError' defined but not used error: command 'gcc' failed with exit status 1 I am attempting the install on a Mac OS X v10.3 with Python v2.3, NumPy v23.1, and SciPy v2.4.3 Thanks in advance for any help you can give me. -Justin Lemkul -- http://mail.python.org/mailman/listinfo/python-list
tkSnack pitch() for frequency estimation
I am using the tkSnack library to estimate the frequency from a sound file. The pitch seems to drop down an octave at 400 Hertz. For example A~440 Hertz comes out at 220 Hertz. When I use the maxpitch and minpitch options to limit the response to say 380 - 460 the result is all zeros. Any ideas on how I can estimate the pitch of a sound up to 880 Hertz (with tkSnack or not)? Thanks Justin Shaw -- http://mail.python.org/mailman/listinfo/python-list
Atlas and NumPy Problems
Hello all, I am hoping someone out there will be able to help me. I am trying to install a program that utilizes NumPy. In installing NumPy, I realized that I was lacking Atlas. I ran into the following problems installing Atlas and NumPy, as I realized that NumPy could be installed using the Mac OSX veclib already built in. If anyone has any ideas on how to fix either of these, I would be most grateful. I am fairly new to Python (I've been learning it myself), so I apologize if these questions are a bit foolish. I've been fighting these problems for days, and I'm out of ideas. I am running OS X v10.3, gcc v3.3, Python v2.3, ScientificPython v2.4.3, and am attempting to install NumPy 23.7 Thank you! -Justin ATLAS install problem: n file included from /Users/jalemkul/Desktop/ATLAS/include/ atlas_prefetch.h:8, from ../ATL_col2blk.c:33:/Users/jalemkul/Desktop/ATLAS/ include/atlas_altivec.h:6:27: altivec.h: No such file or directory../ATL_col2blk.c: In function `ATL_dcol2blk_aX':../ATL_col2blk.c:79: error: `vector' undeclared (first use in this function)../ATL_col2blk.c:79: error: (Each undeclared identifier is reported only once../ ATL_col2blk.c:79: error: for each function it appears in.)../ATL_col2blk.c:79: error: parse error before "float"../ATL_col2blk.c:80: error: parse error before "float"make[7]: *** [ATL_dcol2blk_aX.o] Error 1make[7]: *** Waiting for unfinished jobsmake[6]: *** [dlib] Error 2make[5]: *** [dmmlib] Error 2make[4]: *** [res/atlas_cacheedge.h] Error2make[3]: *** [dinstall] Error 2make[2]: *** [MMinstall] Error 2 STAGE2-1-2: CacheEdge DETECTIONmake -f Makefile INSTALL_LOG/atlas_cacheedge.h pre=d 2>&1 | ./xatlas_tee INSTALL_LOG/dMMCACHEEDGE.LOGcd /Users/jalemkul/Desktop/ATLAS/tune/blas/gemm/ OSX_UNKNOWNAltiVec_2 ; make res/atlas_cacheedge.h pre=dmake dRunFindCEcd /Users/ jalemkul/Desktop/ATLAS/src/blas/gemm/OSX_UNKNOWNAltiVec_2 ; make dlibmake auxillib dcleanuplib dusergemmcd /Users/jalemkul/Desktop/ATLAS/src/auxil/ OSX_UNKNOWNAltiVec_2 ; make libmake[7]: Nothing to be done for `lib'.cd KERNEL ; make -f dMakefile dlibmake[7]: Nothing to be done for `dlib'.cd /Users/jalemkul/Desktop/ATLAS/ src/blas/gemm/OSX_UNKNOWNAltiVec_2 ; make dusermmmake[7]: `dusermm' is up to date.make -j 2 dlib.grd/usr/bin//gcc -o ATL_dcol2blk_aX.o -c -DL2SIZE=4194304 -I/Users/ jalemkul/Desktop/ATLAS/include -I/Users/jalemkul/Desktop/ATLAS/include/ OSX_UNKNOWNAltiVec_2 -I/Users/jalemkul/Desktop/ATLAS/include/contrib -DATL_OS_OSX -DATL_AltiVec -DATL_AVgcc -DATL_AS_OSX_PPC -DATL_NCPU=2 -O -maltivec -mabi=altivec -DDREAL -DALPHAX ../ATL_col2blk.c /usr/bin//gcc -o ATL_drow2blkT_aX.o -c -DL2SIZE=4194304 -I/Users/jalemkul/Desktop/ ATLAS/include -I/Users/jalemkul/Desktop/ATLAS/include/OSX_UNKNOWNAltiVec_2 -I/Users/ jalemkul/Desktop/ATLAS/include/contrib -DATL_OS_OSX -DATL_AltiVec -DATL_AVgcc -DATL_AS_OSX_PPC -DATL_NCPU=2 -O -maltivec -mabi=altivec -DDREAL -DALPHAX ../ ATL_row2blkT.c In file included from /Users/jalemkul/Desktop/ATLAS/include/atlas_prefetch.h:8, from ../ATL_row2blkT.c:32: /Users/jalemkul/Desktop/ATLAS/include/atlas_altivec.h:6:27: altivec.h: No such file or directory ../ATL_row2blkT.c: In function `ATL_drow2blkT_NB_aX': ../ATL_row2blkT.c:64: error: `vector' undeclared (first use in this function) ../ATL_row2blkT.c:64: error: (Each undeclared identifier is reported only once ../ATL_row2blkT.c:64: error: for each function it appears in.) ../ATL_row2blkT.c:64: error: parse error before "float" ../ATL_row2blkT.c:65: error: parse error before "float" ../ATL_row2blkT.c:74: error: parse error before "float" ../ATL_row2blkT.c:75: error: parse error before "float" In file included from /Users/jalemkul/Desktop/ATLAS/include/atlas_prefetch.h:8, from ../ATL_col2blk.c:33: /Users/jalemkul/Desktop/ATLAS/include/atlas_altivec.h:6:27: altivec.h: No such file or directory ../ATL_col2blk.c: In function `ATL_dcol2blk_aX': ../ATL_col2blk.c:79: error: `vector' undeclared (first use in this function) make[6]: *** [ATL_drow2blkT_aX.o] Error 1 make[6]: *** Waiting for unfinished jobs ../ATL_col2blk.c:79: error: (Each undeclared identifier is reported only once ../ATL_col2blk.c:79: error: for each function it appears in.) ../ATL_col2blk.c:79: error: parse error before "float" ../ATL_col2blk.c:80: error: parse error before "float" make[6]: *** [ATL_dcol2blk_aX.o] Error 1 make[5]: *** [dlib] Error 2 make[4]: *** [dmmlib] Error 2 make[3]: *** [res/atlas_cacheedge.h] Error 2 make[2]: *** [/Users/jalemkul/Desktop/ATLAS/tune/blas/gemm/OSX_UNKNOWNAltiVec_2/ res/atlas_cachedge.h] Error 2 ERROR 572 DURING CACHE EDGE DETECTION!!. cd ../.. ; make error_report arch=OSX_UNKNOWNAltiVec_2 make -f Make.top error_report arch=OSX_UNKNOWNAltiVec_2 uname -a 2>&1 >> bin/OSX_UNKNOWNAltiVec_2/INSTALL_LOG/ERR
Re: An absolute Newbie question
wpog wrote: > I have a question about using "IDLE", and that is whenever I start write my > own program in the "Python Shell" it will automatically execute whatever > command I have written, for example: >>> print 'Hello World" > > So, how to I get it to not execute, so that I can write a program that has > ordinary executable functions, and stuff like that? Also if you open IDLE and in the menu bar go to Options >> Configure IDLE, select the 'General' tab and you can specify if you want the interactive prompt or an Edit Window to open at startup. Then hitting F5 will execute the written code, and you can also go to Run >> Python Shell and open an interactive prompt window. Justin -- http://mail.python.org/mailman/listinfo/python-list
tkFileDialog.askopenfilename filetypes problem
Hopefully someone can catch what im missing here. Ive googled this and I think Ive got the filetypes arg written properly, but I get a traceback when calling this function. Heres the code followed by its traceback. def do_ask_fn_1(): z = askopenfilename(title=TITLE, initialdir=Dst_Dir, filetypes=(('AIFF Files','*.aiff'), ("AU Files", "*.au"), ("RAW Files", "*.raw"), ("SD Files", "*.sd"), ("SND Files", "*.snd"), ("WAV files", "*.wav") ) ) print z Exception in Tkinter callback Traceback (most recent call last): File "E:\PYTHON~1\lib\lib-tk\Tkinter.py", line 1345, in __call__ return self.func(*args) File "P:\work\Python\PYZoid\PYZoid.pyw", line 213, in do_ask_fn_1 filetypes=[('AIFF Files','*.aiff'), TypeError: askopenfilename() takes exactly 0 non-keyword arguments (1 given) Can anyone point to what Ive done wrong? Thanks for any input. Justin -- http://mail.python.org/mailman/listinfo/python-list
Re: Some simple performace tests (long)
How much ram does your machine have? the main point is "except when a very large range is used on a memory-starved machine" run x = range(10 ** 6) and look at the memory usage of python.. what happens when you run this program: import time def t(func, num): s = time.time() for x in func(num): pass return time.time() - s def run(func, num): times = [] for x in range(5): times.append(t(func,num)) return min(times), max(times), sum(times)/5 def main(): x = 10 ** 6 while 1: print "trying", x for s, f in ('xr', xrange), (' r', range): print s + " %.3f %.3f %.3f" % run(f, x) x *= 1.5 x = int(x) if __name__ == "__main__": main() I get (columns are mix/max/average): trying 100 xr 0.110 0.115 0.111 r 0.101 0.186 0.119 trying 150 xr 0.082 0.087 0.083 r 0.152 0.158 0.154 trying 225 xr 0.124 0.138 0.128 r 0.228 0.235 0.230 trying 3375000 xr 0.184 0.189 0.186 r 0.344 0.352 0.346 trying 5062500 xr 0.276 0.284 0.279 r 0.515 0.528 0.519 trying 7593750 xr 0.415 0.421 0.416 r 0.774 0.795 0.779 trying 11390625 xr 0.623 0.634 0.626 r 1.163 1.246 1.180 trying 17085937 xr 0.934 0.941 0.937 Killed The "Killed" is from the linux OOM killing the python process.. notice that the xrange for that number worked fine. -- http://mail.python.org/mailman/listinfo/python-list
Filetypes in email attachments.
Hello everyone, I'm writing a simple spam filter as a project, partly to learn python. I want to filter by filetype, however, the mime content type I get using .get_content_type gives limited and possibly bogus information, especially when trying to detect viruses or spam. I would like to use the magic file to detect the filetype, if this is possible. I have the attachement stored and (generally) decoded in a variable. Justin -- http://mail.python.org/mailman/listinfo/python-list
problems with tarfile.open and tar.bz2
Hello everyone, I need some tar functionality for my program. Currently the following code properly displays tar archives, and tar.gz archives. However, it chokes on tar.bz2 archives with the following error: File "mail_filter.py", line 262, in extract_archive tar_archive = tarfile.open('', 'r', fileobj) File "/usr/lib/python2.3/tarfile.py", line 900, in open return func(name, "r", fileobj) File "/usr/lib/python2.3/tarfile.py", line 980, in bz2open raise ValueError, "no support for external file objects" ValueError: no support for external file objects The code snippet is: fileobj = StringIO(attach) if attach_type == 'application/x-tgz' or attach_type == 'application/x-tbz' or attach_type == 'application/x-tar': print '%s file detected, attempting to decompress' % (attach_type) tar_archive = tarfile.open('', 'r', fileobj) print tar_archive.getnames() for archive_file in tar_archive.getmembers(): print archive_file print tar_archive.extractfile(archive_file).read() #except: #print 'Error while extracting %s.' % (attach_type) #return '' I'm at my wits end with this error, it doesn't make any sense that it would treat bzip2'd tar archives very differently than gz'd tar archives. Justin -- http://mail.python.org/mailman/listinfo/python-list
Re: problems with tarfile.open and tar.bz2
r is supposed to autodetect the archive type. However, even changing it to 'r:bz2' produces an identical error. -- http://mail.python.org/mailman/listinfo/python-list
how to do this?
Greetings Pythonistas. Im looking for a way to write this but not sure where or how to begin. As the user enters or removes characters into/from sEnt I would like for set_info() to set infVar with the correct value. The same as how IDLE shows the line and column in the lower right corner. Code Example from time import localtime from Tkinter import * def set_info(): x = len(strVar.get()) infVar.set('Length: %i' % (x)) ROOT = Tk() strVar = StringVar() infVar = StringVar() sLab = Label(ROOT, text='String') sLab.grid(row=0, column=0) sEnt = Entry(ROOT, textvariable=strVar, width=15) sEnt.grid(row=0, column=1, columnspan=2) qBut = Button(ROOT, text='Quit', command=ROOT.quit) qBut.grid(row=1, column=2, pady=2, padx=2, sticky=E) iLab = Label(ROOT, textvariable=infVar, width=21, relief=SUNKEN, anchor=W) iLab.grid(row=2, column=0, columnspan=3) set_info() # example to show what will be displayed. ROOT.mainloop() End Example Can anyone point me in the right direction for how to do this? Regards, Justin -- http://mail.python.org/mailman/listinfo/python-list
Re: how to do this?
Thanks Steve and Peter, these two methods are a lot of help. Ill have to play with each in my actual app to find which works best. I found more info on trace_variable() at http://effbot.org/tkinterbook/variable.htm and also some more info on events and bindings at http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm Justin -- http://mail.python.org/mailman/listinfo/python-list