MRG.COM
comp.lang.python -- http://mail.python.org/mailman/listinfo/python-list
Re: Question on for loop
On Thu, 03 Jan 2013 12:04:03 -0800, subhabangalore wrote: > Dear Group, > If I take a list like the following: > > fruits = ['banana', 'apple', 'mango'] > for fruit in fruits: >print 'Current fruit :', fruit > > Now, > if I want variables like var1,var2,var3 be assigned to them, we may > take, var1=banana, > var2=apple, > var3=mango > > but can we do something to assign the variables dynamically I was > thinking of var_series=['var1','var2','var3'] > for var in var_series: > for fruit in fruits: >print var,fruits > > If any one can kindly suggest. > > Regards, > Subhabrata > > NB: Apology for some alignment mistakes,etc. if you really want to do this (& I agree with the other replies that this is unlikely to be a good idea) then you could simply unpack the list var1,var2,var3=fruits of course if your list is of unknown length then this again becomes impractical. for most programming requirements there is a simple solution, if you find your approach is not easily implemented it is probably a good time to re- asses your approach, more of the than not you have been given a bum steer and are heading down the wrong road. See http://thedailywtf.com for an almost limitless supply of examples of programmers continuing down the wrong road ;-) -- There's nothing worse for your business than extra Santa Clauses smoking in the men's room. -- W. Bossert -- http://mail.python.org/mailman/listinfo/python-list
Re: Yet another attempt at a safe eval() call
On 1/3/2013 6:25 PM, Grant Edwards wrote: I've written a small assembler in Python 2.[67], and it needs to evaluate integer-valued arithmetic expressions in the context of a symbol table that defines integer values for a set of names. The "right" thing is probably an expression parser/evaluator using ast, but it looked like that would take more code that the rest of the assembler combined, and I've got other higher-priority tasks to get back to. Will ast.literal_eval do what you want? -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Yet another attempt at a safe eval() call
On Fri, 04 Jan 2013 07:24:04 -0500, Terry Reedy wrote: > On 1/3/2013 6:25 PM, Grant Edwards wrote: >> >> I've written a small assembler in Python 2.[67], and it needs to >> evaluate integer-valued arithmetic expressions in the context of a >> symbol table that defines integer values for a set of names. The >> "right" thing is probably an expression parser/evaluator using ast, but >> it looked like that would take more code that the rest of the assembler >> combined, and I've got other higher-priority tasks to get back to. > > Will ast.literal_eval do what you want? No. Grant needs to support variables, not just literal constants, hence the symbol table. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Bias correction using histogram matching
I am trying to do the histogram matching of the simulated data to the observed
data. The aim is to correct the bias in the simulated data by CDF matching
CDFobs(y) = CDFsim(x). I could only reach to the stage of generating the CDFs.
I got stuck in finding the transfer function.
The image shows the CDF's and the the Transfer function in
plot(c)http://s8.postimage.org/4txybzz8l/test.jpg. I am trying to replicate
the same. Please help me in achieving the plot.
Thanks in advance
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
import scipy.stats as st
sim = st.gamma(1,loc=0,scale=0.8) # Simulated
obs = st.gamma(2,loc=0,scale=0.7) # Observed
x = np.linspace(0,4,1000)
simpdf = sim.pdf(x)
obspdf = obs.pdf(x)
plt.plot(x,simpdf,label='Simulated')
plt.plot(x,obspdf,'r--',label='Observed')
plt.title('PDF of Observed and Simulated Precipitation')
plt.legend(loc='best')
plt.show()
plt.figure(1)
simcdf = sim.cdf(x)
obscdf = obs.cdf(x)
plt.plot(x,simcdf,label='Simulated')
plt.plot(x,obscdf,'r--',label='Observed')
plt.title('CDF of Observed and Simulated Precipitation')
plt.legend(loc='best')
plt.show()
--
http://mail.python.org/mailman/listinfo/python-list
Re: New to python, do I need an IDE or is vim still good enough?
Ben Finney writes: > Hans Mulder writes: > >> Don't bother: Python comes with a free IDE named IDLE. > > And any decent Unix-alike (most OSen apart from Windows) comes with its > own IDE: the shell, a good text editor (Vim or Emacs being the primary > candidates), and a terminal multiplexor (such as ‘tmux’ or GNU Screen). Just curious since I read the same thing in a programming book recently (21st century C). So what's the greatness that terminal multiplexors offer over tabbed terminals? Especially for software development? For sure I use screen at the remote end of ssh connections where I don't want the application like irssi to die if the connection goes down but other than that? -- http://mail.python.org/mailman/listinfo/python-list
Re: Missing something obvious with python-requests
On 4/01/13 03:56:47, Chris Angelico wrote:
> On Fri, Jan 4, 2013 at 5:53 AM, Ray Cote
> wrote:
>> proxies = {
>> 'https': '192.168.24.25:8443',
>> 'http': '192.168.24.25:8443', }
>>
>> a = requests.get('http://google.com/', proxies=proxies)
>>
>>
>> When I look at the proxy log, I see a GET being performed -- when it should
>> be a CONNECT.
>> Does not matter if I try to get http or https google.com.
> Not sure if it's related to your problem or not, but my understanding
> of a non-SSL request through a proxy is that it'll be a GET request
> (eg "GET http://google.com/ HTTP/1.0"). So the problem is only that
> it's still doing GET requests when it's an https query (which is where
> CONNECT is needed).
It all depends on the proxy URL.
It the proxy URL is http://192.168.24.25/, then the client should send
GET requests to the proxy in both cases, and the proxy should send GET
or CONNECT to the origin server, depending on whether origin URL uses
SSL.
If the proxy URL is https://192.168.24.25/, then the client should send
CONNECT requests to the proxy, and the proxy should send GET or CONNECT
as appropriate.
Python-requests appears to implement only the first case.
Hope this helps,
-- HansM
--
http://mail.python.org/mailman/listinfo/python-list
Re: Missing something obvious with python-requests
On Sat, Jan 5, 2013 at 2:00 AM, Hans Mulder wrote: > It the proxy URL is http://192.168.24.25/, then the client should send > GET requests to the proxy in both cases, and the proxy should send GET > or CONNECT to the origin server, depending on whether origin URL uses > SSL. > > If the proxy URL is https://192.168.24.25/, then the client should send > CONNECT requests to the proxy, and the proxy should send GET or CONNECT > as appropriate. Are you sure? This seems backward. As I understand it, a GET request to a proxy triggers a GET request to the origin server, and a CONNECT request to a proxy triggers a TCP socket connection to the origin host (which may not even be an HTTP/HTTPS server). This has nothing to do with the protocol used between the client and the proxy. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: New to python, do I need an IDE or is vim still good enough?
On Fri, Jan 4, 2013 at 6:34 PM, Anssi Saari wrote: > Ben Finney writes: > >> And any decent Unix-alike (most OSen apart from Windows) comes with its >> own IDE: the shell, a good text editor (Vim or Emacs being the primary >> candidates), and a terminal multiplexor (such as ‘tmux’ or GNU Screen). > > Just curious since I read the same thing in a programming book recently > (21st century C). So what's the greatness that terminal multiplexors > offer over tabbed terminals? Especially for software development? The main thing is that you'll need a _lot_ of terminals. On my Debian and Ubuntu GNOME-based systems, I tend to assign one desktop to each of several "modes", usually with my (tabbed) editor and browser on the first desktop. At the moment, desktop #3 (hit Ctrl-Alt-RightArrow twice) is for building Pike, running Gypsum, and git-managing Gypsum; desktop #2 is for my poltergeist controllers (MIDI to my keyboard), with a few different windows depending on what I'm doing; and desktop #1 is... everything else. SciTE, Google Chrome, a couple of Nautilus windows, and roughly twenty terminals doing various things like Command & Conquer Renegade, iptables management, SSH sessions to two other servers, the Yosemite project... wow, what a lot of random junk I have running on Sikorsky at the moment. It seems I currently have 25 instances of bash running, in addition to the non-bash windows. Tabbed terminals probably would work fine, but I've personally just never gotten accustomed to any. You will want some kind of system that lets you group related shell sessions together (eg one for 'make', one for running the app, and one for git, all relating to one project), and add more terminals to a group as required. The most important editing key is command recall (up arrow or similar), and keeping three or four different command histories per project is hugely advantageous. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
'subprocess.check_output' extra new line?
Hi
I wonder if the additional new line charachter at the end of the standard
output capture is on purpose with 'subprocess.check_output'?
>>> subprocess.check_output([ 'cygpath', 'C:\\' ])
'/cygdrive/c\n'
If I do the same from the shell there is no extra new line (which is correct I
believe):
$ x=$(cygpath C:\\); echo "_${x}_"
_/cygdrive/c_
Surely I have a workaround. I was more interested whether it was a design flaw.
Cheers
B.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Yet another attempt at a safe eval() call
On 2013-01-04, Steven D'Aprano wrote:
> On Thu, 03 Jan 2013 23:25:51 +, Grant Edwards wrote:
>
>> I've written a small assembler in Python 2.[67], and it needs to
>> evaluate integer-valued arithmetic expressions in the context of a
>> symbol table that defines integer values for a set of names. The
>> "right" thing is probably an expression parser/evaluator using ast, but
>> it looked like that would take more code that the rest of the assembler
>> combined, and I've got other higher-priority tasks to get back to.
>>
>> How badly am I deluding myself with the code below?
>
> Pretty badly, sorry.
I suspected that was the case.
> See trivial *cough* exploit below.
>
>
>> def lessDangerousEval(expr):
>> global symbolTable
>> if 'import' in expr:
>> raise ParseError("operand expressions are not allowed to contain
>> the string 'import'")
>> globals = {'__builtins__': None}
>> locals = symbolTable
>> return eval(expr, globals, locals)
>>
>> I can guarantee that symbolTable is a dict that maps a set of string
>> symbol names to integer values.
>
>
> Here's one exploit. I make no promises that it is the simplest such one.
>
> # get access to __import__
> s = ("[x for x in (1).__class__.__base__.__subclasses__() "
> "if x.__name__ == 'catch_warnings'][0]()._module"
> ".__builtins__['__imp' + 'ort__']")
> # use it to get access to any module we like
> t = s + "('os')"
> # and then do bad things
> urscrewed = t + ".system('echo u r pwned!')"
>
> lessDangerousEval(urscrewed)
>
>
> At a minimum, I would recommend:
>
> * Do not allow any underscores in the expression being evaluated.
> Unless you absolutely need to support them for names, they can only
> lead to trouble.
I can disallow underscores in names.
> [...]
> * Since you're evaluating mathematical expressions, there's probably
> no need to allow quotation marks either. They too can only lead to
> trouble.
>
> * Likewise for dots, since this is *integer* maths.
OK, quotes and dots are out as well.
> * Set as short as possible limit on the length of the string as you
> can bare; the shorter the limit, the shorter any exploit must be,
> and it is harder to write a short exploit than a long exploit.
>
> * But frankly, you should avoid eval, and write your own mini-integer
> arithmetic evaluator which avoids even the most remote possibility
> of exploit.
That's obviously the "right" thing to do. I suppose I should figure
out how to use the ast module.
> So, here's my probably-not-safe-either "safe eval":
>
>
> def probably_not_safe_eval(expr):
> if 'import' in expr.lower():
> raise ParseError("'import' prohibited")
> for c in '_"\'.':
> if c in expr:
> raise ParseError('prohibited char %r' % c)
> if len(expr) > 120:
> raise ParseError('expression too long')
> globals = {'__builtins__': None}
> locals = symbolTable
> return eval(expr, globals, locals) # fingers crossed!
>
> I can't think of any way to break out of these restrictions, but that may
> just mean I'm not smart enough.
Thanks! It's definitely an improvement.
--
Grant Edwards grant.b.edwardsYow! -- I have seen the
at FUN --
gmail.com
--
http://mail.python.org/mailman/listinfo/python-list
Re: Yet another attempt at a safe eval() call
On 2013-01-04, Steven D'Aprano wrote: > On Fri, 04 Jan 2013 07:24:04 -0500, Terry Reedy wrote: > >> On 1/3/2013 6:25 PM, Grant Edwards wrote: >>> >>> I've written a small assembler in Python 2.[67], and it needs to >>> evaluate integer-valued arithmetic expressions in the context of a >>> symbol table that defines integer values for a set of names. The >>> "right" thing is probably an expression parser/evaluator using ast, but >>> it looked like that would take more code that the rest of the assembler >>> combined, and I've got other higher-priority tasks to get back to. >> >> Will ast.literal_eval do what you want? > > No. Grant needs to support variables, not just literal constants, hence > the symbol table. Right. ast.literal_eval() doesn't even support arithmetic expressions involving only literal constats such as "3+1" (that's the bare minimum requirement). It would also be very highly desirable to allow expressions involving symblic constants such as "PC+1". Google has found me exapmles of ast-based code that does pretty much what I want, but I haven't tried it yet because of that solution's size and complexity. -- Grant Edwards grant.b.edwardsYow! I brought my BOWLING at BALL -- and some DRUGS!! gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Yet another attempt at a safe eval() call
On 01/04/2013 08:53 AM, Grant Edwards wrote: > That's obviously the "right" thing to do. I suppose I should figure > out how to use the ast module. Or PyParsing. As for your program being "secure" I don't see that there's much to exploit. You're not running as a service, and you're not running your assembler as root, called from a normal user. The user has your code and can "exploit" it anytime he wants. -- http://mail.python.org/mailman/listinfo/python-list
Re: 'subprocess.check_output' extra new line?
On Sat, Jan 5, 2013 at 2:50 AM, wrote:
>
> Hi
>
> I wonder if the additional new line charachter at the end of the standard
> output capture is on purpose with 'subprocess.check_output'?
>
subprocess.check_output([ 'cygpath', 'C:\\' ])
> '/cygdrive/c\n'
>
> If I do the same from the shell there is no extra new line (which is correct
> I believe):
>
> $ x=$(cygpath C:\\); echo "_${x}_"
> _/cygdrive/c_
>
> Surely I have a workaround. I was more interested whether it was a design
> flaw.
What you may have there is the shell $( ) handling changing the
program's output. Try piping the command into 'hd' or similar to see
what it actually produces; it's entirely possible the \n is there, and
the shell is stripping it.
In any case, you can easily trim whitespace from inside Python. That
would be your workaround, I think.
ChrisA
--
http://mail.python.org/mailman/listinfo/python-list
Re: Yet another attempt at a safe eval() call
On 2013-01-04, Michael Torrie wrote: > On 01/04/2013 08:53 AM, Grant Edwards wrote: >> That's obviously the "right" thing to do. I suppose I should figure >> out how to use the ast module. > > Or PyParsing. > > As for your program being "secure" I don't see that there's much to > exploit. There isn't. > You're not running as a service, and you're not running your > assembler as root, called from a normal user. The user has your code > and can "exploit" it anytime he wants. I'm just trying to prevent surprises for people who are running the assembler. We have to assume that they trust the assembler code to not cause damage intentionally. But, one would not expect them to have to worry that assembly language input fed to the assembler code might cause some sort of collateral damage. Sure, I can change the source code for gcc so that it wreaks havok when I invoke it. But, using the stock gcc compiler there shouldn't be any source file I can feed it that will cause it to mail my bank account info to somebody in Eastern Europe, install a keylogger, and then remove all my files. -- Grant Edwards grant.b.edwardsYow! I have a TINY BOWL in at my HEAD gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: New to python, do I need an IDE or is vim still good enough?
If you are going to review an IDE, or multiple, I would recommend Komodo and Komodo Edit. On Thursday, December 27, 2012 2:01:16 PM UTC-6, mogul wrote: > 'Aloha! > > > > I'm new to python, got 10-20 years perl and C experience, all gained on unix > alike machines hacking happily in vi, and later on in vim. > > > > Now it's python, and currently mainly on my kubuntu desktop. > > > > Do I really need a real IDE, as the windows guys around me say I do, or will > vim, git, make and other standalone tools make it the next 20 years too for > me? > > > > Oh, by the way, after 7 days I'm completely in love with this python thing. I > should have made the switch much earlier! > > > > /mogul %-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Yet another attempt at a safe eval() call
On 2013-01-04, Steven D'Aprano wrote:
> On Thu, 03 Jan 2013 23:25:51 +, Grant Edwards wrote:
>
>> I've written a small assembler in Python 2.[67], and it needs to
>> evaluate integer-valued arithmetic expressions in the context of a
>> symbol table that defines integer values for a set of names.
[...]
[ my attaempt at a safer eval() ]
> So, here's my probably-not-safe-either "safe eval":
>
>
> def probably_not_safe_eval(expr):
> if 'import' in expr.lower():
> raise ParseError("'import' prohibited")
> for c in '_"\'.':
> if c in expr:
> raise ParseError('prohibited char %r' % c)
> if len(expr) > 120:
> raise ParseError('expression too long')
> globals = {'__builtins__': None}
> locals = symbolTable
> return eval(expr, globals, locals) # fingers crossed!
>
> I can't think of any way to break out of these restrictions, but that may
> just mean I'm not smart enough.
I've added equals, backslash, commas, square/curly brackets, colons and
semicolons to the
prohibited character list. I also reduced the maximum length to 60
characters. It's unfortunate that parentheses are overloaded for both
expression grouping and for function calling...
def lessDangerousEval(expr):
if 'import' in expr.lower():
raise ParseError("'import' prohibited in expression")
for c in '_"\'.;:[]{}=\\':
if c in expr:
raise ParseError("prohibited char '%r' in expression" % c)
if len(expr) > 60:
raise ParseError('expression too long')
globals = {'__builtins__': None}
locals = symbolTable
return eval(expr, globals, locals) # fingers crossed!
Exploits anyone?
--
Grant Edwards grant.b.edwardsYow! I'm ZIPPY the PINHEAD
at and I'm totally committed
gmail.comto the festive mode.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Yet another attempt at a safe eval() call
On Sat, Jan 5, 2013 at 3:38 AM, Grant Edwards wrote: > I've added equals, backslash, commas, square/curly brackets, colons and > semicolons to the > prohibited character list. I also reduced the maximum length to 60 > characters. It's unfortunate that parentheses are overloaded for both > expression grouping and for function calling... I have to say that an expression evaluator that can't handle parens for grouping is badly flawed. Can you demand that open parenthesis be preceded by an operator (or beginning of line)? For instance: (1+2)*3+4 # Valid 1+2*(3+4) # Valid 1+2(3+4) # Invalid, this will attempt to call 2 You could explain it as a protection against mistaken use of algebraic notation (in which the last two expressions have the same meaning and evaluate to 15). Or, alternatively, you could simply insert the asterisk yourself, though that could potentially be VERY confusing. Without parentheses, your users will be forced to store intermediate results in variables, which gets tiresome fast. discriminant = b*b-4*a*c denominator = 2*a # Okay, this expression demands a square rooting, but let's pretend that's done. sol1 = -b+discriminant sol2 = -b-discrminant sol1 = sol1/denominator sol2 /= denominator # if they know about augmented assignment You can probably recognize the formula I'm working with there, but it's far less obvious and involves six separate statements rather than two. And this is a fairly simple formula. It'll get a lot worse in production. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: New to python, do I need an IDE or is vim still good enough?
On 01/04/13 01:34, Anssi Saari wrote:
Ben Finney writes:
And any decent Unix-alike (most OSen apart from Windows) comes with its
own IDE: the shell, a good text editor (Vim or Emacs being the primary
candidates), and a terminal multiplexor (such as ‘tmux’ or GNU Screen).
Just curious since I read the same thing in a programming book recently
(21st century C). So what's the greatness that terminal multiplexors
offer over tabbed terminals? Especially for software development?
For sure I use screen at the remote end of ssh connections where I don't
want the application like irssi to die if the connection goes down but
other than that?
The reattaching is a nice feature--especially since you can start
some work in one location, then SSH into the box remotely and
reattach, resuming where you left off. Other nice things include
- if it's a remote machine, only connecting once. This is more a
factor if you need to enter a password, rather than using
passwordless public/private key auth. But even with passwordless
key-pairs, you still have to type "ssh user@host" rather than
"{prefix key}c" to create a new connection on the same machine.
- the ability to monitor windows for activity/silence (at least GNU
Screen offered this; I haven't dug for it yet in tmux which I'm
learning). This is nice for backgrounding a compile and being
notified when it goes silent (usually means it's done) or watching a
long-running quiet process to get notification when it finally has
some output. I used this feature a LOT back when I did C/C++ work.
- both offer the ability to do screen-sharing with other parties, as
well as granting them various permissions (user X can watch but not
interact with the session, while user Y can issue commands to the
terminal as well) which is nice for remotely pair programming, or
teaching somebody the ropes or troubleshooting.
- depending on your tabbed terminal windows, terminal multiplexors
usually offer some split-screen abilities (last I checked, GNU
Screen only offered horizontal splits; tmux had both vertical &
horizontal splits). As a Vim user (which doesn't have a way to
include a terminal window inside Vim unless you rebuild it with
unofficial patches), this allows me to have an editor in one
{screen|tmux} window and a shell in the other and be able to see
them together. I don't use it much, but it's nice to have when I do
need it.
- tmux offers the ability to transmit keyboard input to all
linked/synchronized windows, so you can connect to multiple servers
and then issue the same commands and they get run across all of
them. I believe Screen offers a similar ability to broadcast
keystrokes to all windows, but with a clunkier interface. Sort of a
poor-man's "clusterssh". I've not needed this one, but it's there
in case you manage clusters or develop/deploy with them.
Those are just a few of the things that come to mind. Some might be
replicated by a tabbed terminal window; others less so.
-tkc
--
http://mail.python.org/mailman/listinfo/python-list
Re: Yet another attempt at a safe eval() call
On 2013-01-04, Chris Angelico wrote: > On Sat, Jan 5, 2013 at 3:38 AM, Grant Edwards wrote: >> I've added equals, backslash, commas, square/curly brackets, colons >> and semicolons to the prohibited character list. I also reduced the >> maximum length to 60 characters. It's unfortunate that parentheses >> are overloaded for both expression grouping and for function >> calling... > > I have to say that an expression evaluator that can't handle parens > for grouping is badly flawed. Indeed. That's why I didn't disallow parens. What I was implying was that since you have to allow parens for grouping, there's no simple way to disallow function calls. > Can you demand that open parenthesis be preceded by an operator (or > beginning of line)? Yes, but once you've parsed the expression to the point where you can enforce rules like that, you're probably most of the way to doing the "right" thing and evaluating the expression using ast or pyparsing or similar. > You can probably recognize the formula I'm working with there, but > it's far less obvious and involves six separate statements rather than > two. And this is a fairly simple formula. It'll get a lot worse in > production. In the general case, yes. For this assembler I could _probably_ get by with expressions of the formwhere op is '+' or '-'. But, whenever I try to come up with a minimal solution like that, it tends to get "enhanced" over the years until it's a complete mess, doesn't work quite right, and took more total man-hours than a general and "permanent" solution would have. Some might argue that repeated tweaking of and adding limitiations to a "safe eval" is just heading down that same road in a different car. They'd probably be right: in the end, it will probably have been less work to just do it with ast. But it's still interesting to try. :) -- Grant Edwards grant.b.edwardsYow! Are you the at self-frying president? gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Yet another attempt at a safe eval() call
On Sat, Jan 5, 2013 at 4:14 AM, Grant Edwards wrote: > On 2013-01-04, Chris Angelico wrote: >> On Sat, Jan 5, 2013 at 3:38 AM, Grant Edwards >> wrote: > >>> I've added equals, backslash, commas, square/curly brackets, colons >>> and semicolons to the prohibited character list. I also reduced the >>> maximum length to 60 characters. It's unfortunate that parentheses >>> are overloaded for both expression grouping and for function >>> calling... >> >> I have to say that an expression evaluator that can't handle parens >> for grouping is badly flawed. > > Indeed. That's why I didn't disallow parens. > > What I was implying was that since you have to allow parens for > grouping, there's no simple way to disallow function calls. Yeah, and a safe evaluator that allows function calls is highly vulnerable. >> Can you demand that open parenthesis be preceded by an operator (or >> beginning of line)? > > Yes, but once you've parsed the expression to the point where you can > enforce rules like that, you're probably most of the way to doing the > "right" thing and evaluating the expression using ast or pyparsing or > similar. > > Some might argue that repeated tweaking of and adding limitiations to > a "safe eval" is just heading down that same road in a different car. > They'd probably be right: in the end, it will probably have been less > work to just do it with ast. But it's still interesting to try. :) Yep, have fun with it. As mentioned earlier, though, security isn't all that critical; so in this case, chances are you can just leave parens permitted and let function calls potentially happen. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
RE: 'subprocess.check_output' extra new line?
Very good point, you are absolutely right: # cygpath C:\\ | od -c 000 / c y g d r i v e / c \n 014 'bash' manual also confirms it: Command Substitution Command substitution allows the output of a command to replace the command name. There are two forms: $(command) or `command` Bash performs the expansion by executing command and replacing the command substitution with the ---> standard output of the command, with any trailing newlines deleted. Embedded newlines are not deleted, but they may be removed during word splitting. The command substitution $(cat file) can be replaced by the equivalent but faster $(< file). When the old-style backquote form of substitution is used, backslash retains its literal meaning except when followed by $, `, or \. The first backquote not preceded by a backslash terminates the command substitution. When using the $(command) form, all characters between the parentheses make up the command; none are treated specially. Command substitutions may be nested. To nest when using the backquoted form, escape the inner back- quotes with backslashes. If the substitution appears within double quotes, word splitting and pathname expansion are not per- formed on the results. Cheers B. > Date: Sat, 5 Jan 2013 03:14:46 +1100 > Subject: Re: 'subprocess.check_output' extra new line? > From: [email protected] > To: [email protected] > > On Sat, Jan 5, 2013 at 2:50 AM, wrote: > > > > Hi > > > > I wonder if the additional new line charachter at the end of the standard > > output capture is on purpose with 'subprocess.check_output'? > > > subprocess.check_output([ 'cygpath', 'C:\\' ]) > > '/cygdrive/c\n' > > > > If I do the same from the shell there is no extra new line (which is > > correct I believe): > > > > $ x=$(cygpath C:\\); echo "_${x}_" > > _/cygdrive/c_ > > > > Surely I have a workaround. I was more interested whether it was a design > > flaw. > > What you may have there is the shell $( ) handling changing the > program's output. Try piping the command into 'hd' or similar to see > what it actually produces; it's entirely possible the \n is there, and > the shell is stripping it. > > In any case, you can easily trim whitespace from inside Python. That > would be your workaround, I think. > > ChrisA > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Evaluate postgres boolean field
Hi,
I'm hoping for some help on a python script I need to query an api. I'm not a
(Python) programmer ordinarily, but do plan to improve!
Specifically I have a for loop evaluating a database row, which I think I can
treat as a list. My [4] is a postgres boolean field, and I'm temporarily stuck
on how to evaluate this to determine if I use the values in [1].
Could I have some advice on what to change? Also do let me know if you can
recommend a good beginners python book.
Data example:
[13, 'Barbican Station', 'Barbican Station, London Underground Ltd., Aldersgate
St, London, EC1A 4JA',
'0101E0E6108851AB9E9803B9BF5BB6972294C24940',
True]
Code:
#!/usr/bin/python
import psycopg2
#note that we have to import the Psycopg2 extras library!
import psycopg2.extras
import sys
def main():
conn_string = "host='localhost' dbname='gisdb' user='postgres'
password='#'"
# print the connection string we will use to connect
print "Connecting to database\n ->%s" % (conn_string)
conn = psycopg2.connect(conn_string)
# HERE IS THE IMPORTANT PART, by specifying a name for the cursor
# psycopg2 creates a server-side cursor, which prevents all of the
# records from being downloaded at once from the server.
cursor = conn.cursor('cursor_tube',
cursor_factory=psycopg2.extras.DictCursor)
cursor.execute('SELECT * FROM tubestations LIMIT 1000')
# Because cursor objects are iterable we can just call 'for - in' on
# the cursor object and the cursor will automatically advance itself
# each iteration.
# This loop should run 1000 times, assuming there are at least 1000
# records in 'my_table'
row_count = 0
for row in cursor:
row_count += 1
if row[4] = True
print row[1]
#print "row: %s%s\n" % (row_count, row)
if __name__ == "__main__":
main()
Thanks!
Andy
--
http://mail.python.org/mailman/listinfo/python-list
Re: Yet another attempt at a safe eval() call
On 2013-01-04, Chris Angelico wrote:
> On Sat, Jan 5, 2013 at 4:14 AM, Grant Edwards wrote:
>> On 2013-01-04, Chris Angelico wrote:
>>> On Sat, Jan 5, 2013 at 3:38 AM, Grant Edwards
>>> wrote:
>>
I've added equals, backslash, commas, square/curly brackets, colons
and semicolons to the prohibited character list. I also reduced the
maximum length to 60 characters. It's unfortunate that parentheses
are overloaded for both expression grouping and for function
calling...
>>>
>>> I have to say that an expression evaluator that can't handle parens
>>> for grouping is badly flawed.
>>
>> Indeed. That's why I didn't disallow parens.
>>
>> What I was implying was that since you have to allow parens for
>> grouping, there's no simple way to disallow function calls.
>
> Yeah, and a safe evaluator that allows function calls is highly vulnerable.
>
>>> Can you demand that open parenthesis be preceded by an operator (or
>>> beginning of line)?
>>
>> Yes, but once you've parsed the expression to the point where you can
>> enforce rules like that, you're probably most of the way to doing the
>> "right" thing and evaluating the expression using ast or pyparsing or
>> similar.
>>
>> Some might argue that repeated tweaking of and adding limitiations to
>> a "safe eval" is just heading down that same road in a different car.
>> They'd probably be right: in the end, it will probably have been less
>> work to just do it with ast. But it's still interesting to try. :)
>
> Yep, have fun with it. As mentioned earlier, though, security isn't
> all that critical; so in this case, chances are you can just leave
> parens permitted and let function calls potentially happen.
An ast-based evaluator wasn't as complicated as I first thought: the
examples I'd been looking at implemented far more features than I
needed. This morning I found a simpler example at
http://stackoverflow.com/questions/2371436/evaluating-a-mathematical-expression-in-a-string
The error messages are still pretty cryptic, so improving
that will add a few more lines. One nice thing about the ast code is
that it's simple to add code to allow C-like character constants such
that ('A' === 0x41). Here's the first pass at ast-based code:
import ast,operator
operators = \
{
ast.Add:operator.iadd,
ast.Sub:operator.isub,
ast.Mult: operator.imul,
ast.Div:operator.idiv,
ast.BitXor: operator.ixor,
ast.BitAnd: operator.iand,
ast.BitOr: operator.ior,
ast.LShift: operator.lshift,
ast.RShift: operator.rshift,
ast.Invert: operator.invert,
ast.USub: operator.neg,
ast.UAdd: operator.pos,
}
def _eval_expr(node):
global symbolTable
if isinstance(node, ast.Name):
if node.id not in symbolTable:
raise ParseError("name '%s' undefined" % node.id)
return symbolTable[node.id]
elif isinstance(node, ast.Num):
return node.n
elif isinstance(node, ast.operator) or isinstance(node, ast.unaryop):
return operators[type(node)]
elif isinstance(node, ast.BinOp):
return _eval_expr(node.op)(_eval_expr(node.left),
_eval_expr(node.right))
elif isinstance(node, ast.UnaryOp):
return _eval_expr(node.op)(_eval_expr(node.operand))
else:
raise ParseError("error parsing expression at node %s" % node)
def eval_expr(expr):
return _eval_expr(ast.parse(expr).body[0].value)
--
Grant Edwards grant.b.edwardsYow! A can of ASPARAGUS,
at 73 pigeons, some LIVE ammo,
gmail.comand a FROZEN DAQUIRI!!
--
http://mail.python.org/mailman/listinfo/python-list
Re: Yet another attempt at a safe eval() call
On Fri, 04 Jan 2013 13:33:41 +, Steven D'Aprano wrote: > On Fri, 04 Jan 2013 07:24:04 -0500, Terry Reedy wrote: > >> On 1/3/2013 6:25 PM, Grant Edwards wrote: >>> >>> I've written a small assembler in Python 2.[67], and it needs to >>> evaluate integer-valued arithmetic expressions in the context of a >>> symbol table that defines integer values for a set of names. The >>> "right" thing is probably an expression parser/evaluator using ast, >>> but it looked like that would take more code that the rest of the >>> assembler combined, and I've got other higher-priority tasks to get >>> back to. >> >> Will ast.literal_eval do what you want? > > No. Grant needs to support variables, not just literal constants, hence > the symbol table. as a thought why not processes the input string by exploding the literal constants into their numerical values as stage 1 this should result in a string that only contains numbers & mathematical symbols then reject any resultant string that contains any alpha characters. I have to agree that it is still a risky process. -- Loneliness is a terrible price to pay for independence. -- http://mail.python.org/mailman/listinfo/python-list
problem with exam task for college
hy everyone, for my exam this year i had to write a computer game on vpython (visualpython).we had to make a lunar lander game where the ship drops by gravity and is able to manouver to safely land on the moon.right now i am completely stuck on trying to make the visual of the ship rotate.i'm new to this forum, i guess i'll just paste my code here. Everything works fine on the game, except the rotation of the ship. however the when you press "up" the after rotating the velocity actually changes direction , but the visual doesn't. i'm getting kinda nervous because due date is coming, any help is appreciated, here is the code: from visual import * import time import math import random from datetime import datetime import operator class lunar_lander(object): def __init__(self): scene.title = 'mini star wars' scene.width = 375 scene.height = 550 scene.center = (0,0) self.pos = (0,0) self.axis = 0 self.brandstofmeter = brandstofmeter() self.ruimteschip = ruimteschip() self.view = game_view(self) def play(self): t=0 dt=0.01 while t<9: time.sleep(0.01) self.brandstofmeter.update self.ruimteschip.update(dt) t = t + dt class game_view(object): def __init__(self,owner): autoscale=True box(pos=( 0, -375, 0), length=500, height=5, width=0, color = color.white) box(pos=(0,375, 0), length=500, height=5, width=0, color = color.white) box(pos=(-250,0, 0), length=5, height=750, width=0, color = color.white) box(pos=(250,0, 0), length=5, height=750, width=0, color = color.white) maan = curve(pos=[(-250,-353),(-240,-341),(-210,-354),(-199.5,-374)],color=color.red) maana = curve(pos=[(-199.5,-374),(-166,-374)],color=color.green) maanb = curve(pos=[(-166,-374),(-140,-357),(-80,-319),(-40,-361),(0,-321),(40,-329),(80,-347)],color=color.red) maanc = curve(pos=[(80,-347),(140,-347)],color=color.green) maand = curve(pos=[(140,-347),(162,-337),(189.5,-365),(210,-355),(240,-372),(250,-338)],color=color.red) for i in random.sample(range (-250,250),20): for j in random.sample(range (-375,375),20): sterren = points(pos = [i,j,0],size = 2, color=color.white) class brandstofmeter(object): def __init__(self): self.size = (25,45) axis = 0 self.pos = (220,345) self.view = brandstofmeter_view(self) def update(self): while True: if scene.kb.keys: s = scene.kb.getkey() if (s == 'up'): self.view.update(self) class brandstofmeter_view(object): def __init__(self,owner): self.owner = owner meter = box(pos = owner.pos,size = owner.size,color = color.green) def update (self,owner): self.size = self.size - (0,0.45) class ruimteschip(object): def __init__(self): self.pos = vector(0,330) self.acceleration = vector(0,-88,0) self.axis = (1,0,0) self.hoek = (90*math.pi)/180 self.graden = math.degrees(self.hoek) self.gas = vector(10 * cos(self.hoek),10 * sin (self.hoek)) self.velocity = vector(0,0,0) self.angle = (1,0,0) self.view = ruimteschip_view(self) self.vlam = self.view.vlam self.frame = self.view.frame def update(self,dt): self.velocity = self.velocity + (self.acceleration * dt) self.pos = self.pos + self.velocity * dt a = 0 b = 0 if scene.kb.keys: a = a + 0.001 s = scene.kb.getkey() if (s == "up"): self.velocity = self.velocity + self.gas self.vlam.visible = True b = b + 2 if (s == "left"): self.gas = rotate(self.gas,angle = math.pi/10, axis = (0,0,1)) c = list(self.frame.axis) c[2] -= 0.1 c = tuple(c) c = self.frame.axis if (s == "right") : self.gas = rotate(self.gas,angle = -(math.pi/10), axis = (0,0,1)) c = list(self.frame.axis) c[2] += 0.1 c = tuple(c) c = self.frame.axis if (a == 0): self.vlam.visible = False if self.pos.x > 250: self.pos.x = -250 if self.pos.x < -250: self.pos.x = 250 self.view.update(self) class ruimteschip_view(object): def __init__(self,owner): self.owner = owner self.frame = frame(pos = owner.pos,axis
Re: Yet another attempt at a safe eval() call
On Sat, Jan 5, 2013 at 5:09 AM, Grant Edwards wrote:
> The error messages are still pretty cryptic, so improving
> that will add a few more lines. One nice thing about the ast code is
> that it's simple to add code to allow C-like character constants such
> that ('A' === 0x41). Here's the first pass at ast-based code:
Looks cool, and fairly neat! Now I wonder, is it possible to use that
to create new operators, such as the letter d? Binary operator, takes
two integers...
ChrisA
--
http://mail.python.org/mailman/listinfo/python-list
Re: Yet another attempt at a safe eval() call
On 2013-01-04, Chris Angelico wrote:
> On Sat, Jan 5, 2013 at 5:09 AM, Grant Edwards wrote:
>> The error messages are still pretty cryptic, so improving
>> that will add a few more lines. One nice thing about the ast code is
>> that it's simple to add code to allow C-like character constants such
>> that ('A' === 0x41). Here's the first pass at ast-based code:
>
> Looks cool, and fairly neat! Now I wonder, is it possible to use that
> to create new operators, such as the letter d? Binary operator, takes
> two integers...
I don't think you can define new operators. AFAICT, the
lexing/parsing is done using the built-in Python grammar. You can
control the behavior of the predefined operators and reject operators
you don't like, but you can't add new ones or change precedence/syntax
or anything like that.
If you want to tweak the grammar itself, then I think you need to use
something like pyparsing.
--
Grant Edwards grant.b.edwardsYow! I own seven-eighths of
at all the artists in downtown
gmail.comBurbank!
--
http://mail.python.org/mailman/listinfo/python-list
Re: Evaluate postgres boolean field
On Friday, January 4, 2013 10:08:22 AM UTC-8, [email protected] wrote: > Hi, > > I'm hoping for some help on a python script I need to query an api. I'm not a > (Python) programmer ordinarily, but do plan to improve! > > Specifically I have a for loop evaluating a database row, which I think I can > treat as a list. My [4] is a postgres boolean field, and I'm temporarily > stuck on how to evaluate this to determine if I use the values in [1]. > > Could I have some advice on what to change? Also do let me know if you can > recommend a good beginners python book. > > Data example: > > [13, 'Barbican Station', 'Barbican Station, London Underground Ltd., > Aldersgate St, London, EC1A 4JA', > '0101E0E6108851AB9E9803B9BF5BB6972294C24940', > True] > > > Code: > > #!/usr/bin/python > import psycopg2 > #note that we have to import the Psycopg2 extras library! > import psycopg2.extras > import sys > > def main(): > conn_string = "host='localhost' dbname='gisdb' user='postgres' > password='#'" > # print the connection string we will use to connect > print "Connecting to database\n->%s" % (conn_string) > > conn = psycopg2.connect(conn_string) > > # HERE IS THE IMPORTANT PART, by specifying a name for the cursor > # psycopg2 creates a server-side cursor, which prevents all of the > # records from being downloaded at once from the server. > cursor = conn.cursor('cursor_tube', > cursor_factory=psycopg2.extras.DictCursor) > cursor.execute('SELECT * FROM tubestations LIMIT 1000') > > # Because cursor objects are iterable we can just call 'for - in' on > # the cursor object and the cursor will automatically advance itself > # each iteration. > # This loop should run 1000 times, assuming there are at least 1000 > # records in 'my_table' > row_count = 0 > for row in cursor: > row_count += 1 > if row[4] = True > print row[1] > #print "row: %s%s\n" % (row_count, row) > > if __name__ == "__main__": > main() > > Thanks! > > > Andy Your code is pretty close to working, you just need to make a couple modifications. You are using the equals sign as an assignment, not a comparison, although the comparison and value are unnecessary since the field's value is either true or false. And you're missing a colon at the end of the condition. Note also that since you are using a DictCursor you can use column names to reference your row's fields, I guessed on the field names, but you should get the idea. for row in cursor: row_count += 1 if row['active']: print row['name'] -- http://mail.python.org/mailman/listinfo/python-list
Re: problem with exam task for college
On Sat, Jan 5, 2013 at 5:23 AM, wrote: > hy everyone, for my exam this year i had to write a computer game on vpython > (visualpython).we had to make a lunar lander game where the ship drops by > gravity and is able to manouver to safely land on the moon.right now i am > completely stuck on trying to make the visual of the ship rotate.i'm new > to this forum, i guess i'll just paste my code here. Everything works fine on > the game, except the rotation of the ship. however the when you press "up" > the after rotating the velocity actually changes direction , but the visual > doesn't. i'm getting kinda nervous because due date is coming, any help is > appreciated, here is the code: Ha, I remember playing a game along those lines that was drawn in pure ASCII text... the visuals change, the concept doesn't :) > self.brandstofmeter = brandstofmeter() > self.ruimteschip = ruimteschip() I'm having trouble understanding these names, and am guessing they're either aggressively abbreviated or not English, but it's hard to tell which. It's conventional in Python code to capitalize separate words in class names, and to either capitalize or use underscores (more usually the latter) between words in instance variables and method names. Google tells me that brandstofmeter might mean "Babylon 9" and ruimteschip is German for "spaceship", but that would be more obvious if I were not trying to figure out what "brands-t-of-meter" might mean. > self.brandstofmeter.update > self.ruimteschip.update(dt) But I'm guessing that this right here is your problem. The second update method is called, but the first one isn't. Python evaluates the name, then does nothing with it. Unlike in BASIC, Python allows you to manipulate functions just like you do integers and strings, so actually _calling_ a function requires the parentheses, empty if you don't need any args: self.brandstofmeter.update() > for i in random.sample(range (-250,250),20): > for j in random.sample(range (-375,375),20): > sterren = points(pos = [i,j,0],size = 2, color=color.white) Without seeing the definition of points() anywhere, I can't say whether this is effective or not; or is that something from module visual? This is where "from x import *" can quickly get confusing - it's not obvious whether the name 'points' has come from your code or someone else's. The result is being put into sterren and then ignored. You can happily omit this if you don't need that return value; Python will quietly do nothing with it: points(pos = [i,j,0],size = 2, color=color.white) > class brandstofmeter_view(object): > def __init__(self,owner): > self.owner = owner > meter = box(pos = owner.pos,size = owner.size,color = color.green) > > def update (self,owner): > self.size = self.size - (0,0.45) Is self.size set anywhere? You may find that, when you fix the above problem with this method not being called, it begins bombing. What data type is self.size supposed to be? If it's a tuple, this won't work, and you'll need to do something like: self.size = (self.size[0], self.size[1]-0.45) Or alternatively, use a mutable type such as a list. (Possibly the vector that you use elsewhere will do. I'm not familiar with that class, so it may be that you can subtract a tuple from it.) > def update(self,dt): > self.velocity = self.velocity + (self.acceleration * dt) > self.pos = self.pos + self.velocity * dt Tip: Use augmented assignment for these sorts of statements. It's clearer what you're doing: self.velocity += self.acceleration * dt self.pos += self.velocity * dt Your class structure feels overengineered, to me. The model/view/controller system is overkill in most of the places it's used. Lots of your code is just passing information around from place to place; instead of the separate _view class, you could simply have a class ruimteschip that knows how to draw itself. Final comment: Your code is fairly well laid out, and your query is clear. Thanks! It's so much easier to read than something that's vague about what's actually wrong :) Just one thing. Your subject line doesn't actually say what's going on (though again, your honesty about it being an exam task is appreciated); something describing the problem would have been helpful. But that's fairly minor. Your post is a joy to answer. Thanks! Chris Angelico -- http://mail.python.org/mailman/listinfo/python-list
Re: Yet another attempt at a safe eval() call
On Sat, Jan 5, 2013 at 5:43 AM, Grant Edwards wrote:
> On 2013-01-04, Chris Angelico wrote:
>> On Sat, Jan 5, 2013 at 5:09 AM, Grant Edwards
>> wrote:
>>> The error messages are still pretty cryptic, so improving
>>> that will add a few more lines. One nice thing about the ast code is
>>> that it's simple to add code to allow C-like character constants such
>>> that ('A' === 0x41). Here's the first pass at ast-based code:
>>
>> Looks cool, and fairly neat! Now I wonder, is it possible to use that
>> to create new operators, such as the letter d? Binary operator, takes
>> two integers...
>
> I don't think you can define new operators. AFAICT, the
> lexing/parsing is done using the built-in Python grammar. You can
> control the behavior of the predefined operators and reject operators
> you don't like, but you can't add new ones or change precedence/syntax
> or anything like that.
>
> If you want to tweak the grammar itself, then I think you need to use
> something like pyparsing.
Oh well, hehe. I've not seen any simple parsers that let you
incorporate D&D-style dice notation ("2d6" means "roll two 6-sided
dice and sum the rolls" - "d6" implies "1d6").
ChrisA
--
http://mail.python.org/mailman/listinfo/python-list
Re: problem with exam task for college
On Sat, Jan 5, 2013 at 5:59 AM, Chris Angelico wrote: > Google tells me that brandstofmeter might mean "Babylon 9" And by the way, in case it didn't come across, I'm jesting there. What I mean is that Google didn't have any useful and obvious results indicating what this actually means. But I'm guessing it's a fuel or altitude gauge. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: Evaluate postgres boolean field
In [email protected] writes: > for row in cursor: > row_count += 1 > if row[4] = True > print row[1] Since row[4] is a boolean value, you should be able to just say: if row[4]: print row[1] -- John Gordon A is for Amy, who fell down the stairs [email protected] B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: problem with exam task for college
On 2013-01-04 18:59, Chris Angelico wrote: On Sat, Jan 5, 2013 at 5:23 AM, wrote: hy everyone, for my exam this year i had to write a computer game on vpython (visualpython).we had to make a lunar lander game where the ship drops by gravity and is able to manouver to safely land on the moon.right now i am completely stuck on trying to make the visual of the ship rotate.i'm new to this forum, i guess i'll just paste my code here. Everything works fine on the game, except the rotation of the ship. however the when you press "up" the after rotating the velocity actually changes direction , but the visual doesn't. i'm getting kinda nervous because due date is coming, any help is appreciated, here is the code: Ha, I remember playing a game along those lines that was drawn in pure ASCII text... the visuals change, the concept doesn't :) self.brandstofmeter = brandstofmeter() self.ruimteschip = ruimteschip() I'm having trouble understanding these names, and am guessing they're either aggressively abbreviated or not English, but it's hard to tell which. It's conventional in Python code to capitalize separate words in class names, and to either capitalize or use underscores (more usually the latter) between words in instance variables and method names. Google tells me that brandstofmeter might mean "Babylon 9" and ruimteschip is German for "spaceship", but that would be more obvious if I were not trying to figure out what "brands-t-of-meter" might mean. [snip] Google Translate says it's Dutch: ruimteschip -> spaceship brandstofmeter -> fuel gauge -- http://mail.python.org/mailman/listinfo/python-list
Re: problem with exam task for college
On 4 January 2013 19:00, Chris Angelico wrote: > On Sat, Jan 5, 2013 at 5:59 AM, Chris Angelico wrote: > > Google tells me that brandstofmeter might mean "Babylon 9" > > And by the way, in case it didn't come across, I'm jesting there. What > I mean is that Google didn't have any useful and obvious results > indicating what this actually means. But I'm guessing it's a fuel or > altitude gauge. > It might measure a brand in femtometers ;). But, seriously, it's Dutch for Fuel Gauge. Google told me, in case you think I know Dutch, but it's in the Python Spirit either way. ruimteschip -> Spaceship hoek -> angle sterren -> stars poot -> leg vlam -> flame graden -> degrees maan -> moon I'd say they'd be good names if you're in the Netherlands. -- http://mail.python.org/mailman/listinfo/python-list
Re: problem with exam task for college
On Sat, Jan 5, 2013 at 6:18 AM, Joshua Landau wrote: > It might measure a brand in femtometers ;). LOL! > But, seriously, it's Dutch for Fuel Gauge. Google told me, in case you think > I know Dutch, but it's in the Python Spirit either way. > > ruimteschip -> Spaceship > hoek -> angle > sterren -> stars > poot -> leg > vlam -> flame > graden -> degrees > maan -> moon > > I'd say they'd be good names if you're in the Netherlands. Yep, I'd agree, those are fine names. I still would expect to see the class names in uppercase though; a single leading capital letter strongly suggests that it's a single-word name, where all-lowercase could just be rammed up together non-delimited. But yeah, that's a pretty minor point. Those name are well suited to their tasks. (And quite a few of them can be figured out from context without even turning to the translator, like hoek == angle.) ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: problem with exam task for college
woow jeezes, thanks for the amazingly fast and detailed response, you guys are amazing. let's clear a few things up : 1) points is a module in vpython to make points, the points do in fact appear although its not really the effect i intended to have, the points are "lined up" in stead of randomly separated, if you know what i mean 2) sorry for the dutch names :) 3) i put the parenteces there and then i got a bunch of errors which i fixed 2 problems: a) my program seems to be stuck in the update phase of brandstoftank(=fuel tank), it doesnt get to the update of the spaceship b) the problem i originally described in my first post was not resolved, by means of elimination i could conclude that the problem situates itself in this lines : if (s == "left"): self.gas = rotate(self.gas,angle = math.pi/10, axis = (0,0,1)) c = list(self.frame.axis) c[2] -= 0.1 c = tuple(c) c = self.frame.axis if (s == "right") : self.gas = rotate(self.gas,angle = -(math.pi/10), axis = (0,0,1)) c = list(self.frame.axis) c[2] += 0.1 c = tuple(c) c = self.frame.axis i will put the full revisited code here : from visual import * import time import math import random from datetime import datetime import operator class lunar_lander(object): def __init__(self): scene.title = 'mini star wars' scene.width = 375 scene.height = 550 scene.center = (0,0) self.pos = (0,0) self.axis = 0 self.brandstofmeter_view = brandstofmeter_view() self.ruimteschip = ruimteschip() self.view = game_view(self) def play(self): t=0 dt=0.01 while t<9: time.sleep(0.01) self.brandstofmeter_view.update() self.ruimteschip.update(dt) t = t + dt class game_view(object): def __init__(self,owner): autoscale=True box(pos=( 0, -375, 0), length=500, height=5, width=0, color = color.white) box(pos=(0,375, 0), length=500, height=5, width=0, color = color.white) box(pos=(-250,0, 0), length=5, height=750, width=0, color = color.white) box(pos=(250,0, 0), length=5, height=750, width=0, color = color.white) maan = curve(pos=[(-250,-353),(-240,-341),(-210,-354),(-199.5,-374)],color=color.red) maana = curve(pos=[(-199.5,-374),(-166,-374)],color=color.green) maanb = curve(pos=[(-166,-374),(-140,-357),(-80,-319),(-40,-361),(0,-321),(40,-329),(80,-347)],color=color.red) maanc = curve(pos=[(80,-347),(140,-347)],color=color.green) maand = curve(pos=[(140,-347),(162,-337),(189.5,-365),(210,-355),(240,-372),(250,-338)],color=color.red) for i in random.sample(range (-250,250),20): for j in random.sample(range (-375,375),20): sterren = points(pos = [i,j,0],size = 2, color=color.white) class brandstofmeter_view(object): def __init__(self): axis = 0 self.pos = (220,345) self.meter = box(pos = self.pos, lenght = 25, height = 45,color = color.green) def update (self): s = scene.kb.getkey() if (s == "up"): self.meter.height = self.meter.height - 1 class ruimteschip(object): def __init__(self): self.pos = vector(0,330) self.acceleration = vector(0,-88,0) self.axis = (1,0,0) self.hoek = (90*math.pi)/180 self.graden = math.degrees(self.hoek) self.gas = vector(10 * cos(self.hoek),10 * sin (self.hoek)) self.velocity = vector(0,0,0) self.angle = (1,0,0) self.view = ruimteschip_view(self) self.vlam = self.view.vlam self.frame = self.view.frame def update(self,dt): self.velocity = self.velocity + (self.acceleration * dt) self.pos = self.pos + self.velocity * dt a = 0 b = 0 if scene.kb.keys: a = a + 0.001 s = scene.kb.getkey() if (s == "up"): self.velocity = self.velocity + self.gas self.vlam.visible = True b = b + 2 if (s == "left"): self.gas = rotate(self.gas,angle = math.pi/10, axis = (0,0,1)) c = list(self.frame.axis) c[2] -= 0.1 c = tuple(c) c = self.frame.axis if (s == "right") : self.gas = rotate(self.gas,angle = -(math.pi/10), axis = (0,0,1)) c = list(self.frame.axis) c[2] += 0.1 c = tuple(c) c = self.frame.axis if (a == 0): self.vlam.visible = Fals
Re: problem with exam task for college
On Sat, Jan 5, 2013 at 7:01 AM, wrote: > woow jeezes, thanks for the amazingly fast and detailed response, you guys > are amazing. > > thanks again, are you guys getting paid for this or is this voluntarily? > either way i really appreciate it We're all volunteers (and it's now 7:30AM Saturday and I've been up all night, so this post quite probably doesn't carry the hallmarks of intelligence). To be more strictly correct, we are members of a community - people helping people. Far as I know, there's not one person here who has never asked a question. I tend to join a mailing list to ask one or more questions, and hang around answering them long after my personal needs are satisfied, kinda like seeding back a torrent after you've downloaded it. We answer questions for a variety of reasons. Partly, because this is one of the best forms of help that the Python community can offer, which means that supporting Python in this way strengthens the language. Partly, because our names are connected to our posts, and we are seen to be helpful people (and, since the list/newsgroup is archived on the web, potential employers who search the web for our names will see us being helpful and knowledgeable). Partly, because we're repaying the community for the benefits we've gained from it. Partly, because in answering questions, we ourselves learn. And there are other reasons too. > 2) sorry for the dutch names :) No probs; as was said in several follow-ups, those are well-chosen names. > b) the problem i originally described in my first post was not resolved, by > means of elimination i could conclude that the problem situates itself in > this lines : > > c = list(self.frame.axis) > c[2] -= 0.1 > c = tuple(c) > c = self.frame.axis This code is looking quite messy, here. But the most obvious problem is that you're setting up 'c' to be the modified axis, and then... overwriting c with the old axis. Try doing the assignment the other way in the last line: self.frame.axis = c Alternatively, you could do the whole thing more cleanly by unpacking and then repacking the tuple: (x, y, z) = self.frame.axis self.frame.axis = (x, y, z-0.1) Two lines that do the job of the above four. Note that the parentheses are optional here; they look nice since axis is holding coordinates, but Python doesn't care. Hope that helps! ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: pylint, was Re: pygame - importing GL - very bad...
On 01/03/2013 05:52 PM, Terry Reedy wrote: That seems like a improper error message from the tool. "Invalid name" does *not* properly describe that situation. The name is *not* "Invalid" in any sense of the word, and a "checker" that tells you it is is creating needless false-positives. An error checker should be saying something like: "self.lightDone: Does not match PEP8 recommended style" making it clear that this is *not* an error, it is a *style* related *warning*. I quite agree. Wanting 3 chars for attribute names is not even PEP-8 style but pylint-author style. I was really surprised at that. In that case, 'Does not match pylint recommended style.' or even 'configured styles'. I have not used pylint or pychecker as of yet. I agree with you all... Thanks, everyone - now I shall investigate pylint and friends in more detail on my own :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: pygame - importing GL - very bad...
On 01/03/2013 03:09 PM, Mike C. Fletcher wrote: On 13-01-02 08:53 PM, someone wrote: So this solution is not something I like too... But I can see some other people came up with good solutions, which I didn't knew about.. Why is this solution not to your liking? Python has namespaces for a Because the amount of opengl-functions is HUGE, many people (at least on the internet) do as I and (IMHO) it takes up too much time to change a lot of code plus sometimes I grab/modify small code pieces from the internet and it makes my development SO MUCH faster just to make an exception here with star-import for opengl-commands. I'd agree on it being rather impractical/pointless/verbose to have every single OpenGL entry point and constant have an extra gl. or glu. or glut. added to the front. OpenGL/GLU/GLUT is already namespaced, but Good to hear, I'm not alone, thanks. using C-style prefix namespacing (that is gl* glu* glut* and GL_*, GLU_*, GLUT_*), so adding Python style namespacing to the front of that makes it very verbose. OpenGL-using code is *littered* with OpenGL entry points and constants (and yes, I intend the slight slight), so that's going to make it rather annoying to work with. PyOpenGL's current approach is mostly attempting to maintain backward compatibility with the older revisions. wxPython actually rewrote its whole interface to go from * imports into namespaced lookups and then wrote a little migration tool that would attempt to rewrite your code for the new version. They also provided a transitional API so that code could mix-and-match the styles. For PyOpenGL that would look something like this: from OpenGL import gl, glu, glut gl.Rotate(...) gl.Clear(gl.COLOR_BUFFER_BIT) Ok, that's interesting. However, I like it the way it is, where I can copy/paste C-code from the web and change some small things and it'll work and fit into my needs. BUT I didn't know there was such a transitional API - interesting. I however don't want to be a first-mover - let's see if sufficiently many people will use this and then I'll consider doing it too. At the moment, I still think the star-import is good because it makes it easy to look for C-code and program it (=do it) like people would do it in C. or, if you really needed PEP-8 compliance, and don't mind making the API look nothing like the original, we might even go to: from opengl import gl, glu, glut gl.rotate(...) gl.clear(gl.COLOR_BUFFER_BIT) Erhm, that's the same as above. Is that what you meant to write? Either of which would *also* make it possible for us to lazy-load the entry points and symbols (that would save quite a bit of ram). But I'm not actually likely to do this, as it makes it far more annoying to work with C-oriented references (and since PyOpenGL is primarily used by new OpenGL coders who need to lean heavily on references, that's a big deal). Currently you can often copy-and-paste C code into PyOpenGL and have it work properly as far as the OpenGL part is concerned (arrays and the like need to be rewritten, but that's not something I can control, really). People are already confused by the small variations Agree - that's something I like. from C OpenGL, making the API look entirely different wouldn't be a good direction to move, IMO. Well, I'm sometimes a bit annoyed that python doesn't give as many warnings/errors as one gets in C - for instance sometimes I copy/paste and forget to remove the trailing semi-colons. However after I began to use pylint and friends, this error will be caught. Then sometimes I forgot to add () for function calls, which in C would cause an error by the compiler but which python allows so one can get the object (which maybe is also a good reason, but at least in the beginning when I learned python, this was very annoying + confusing to me). Thanks for the comments about this transitional opengl-stuff - I was unaware of that. Currently it's not so interesting to me, I like it the way I do it now so I can quickly grab code pieces from C/C++ from the web and change it to suit my needs... -- http://mail.python.org/mailman/listinfo/python-list
Re: pylint, was Re: pygame - importing GL - very bad...
On 01/03/2013 12:27 PM, Chris Angelico wrote:
On Thu, Jan 3, 2013 at 10:19 PM, someone wrote:
Doesn't this "[ ... ]" mean something optional?
What does {2,30}$ mean?
I think $ means that the {2,30} is something in the end of the sentence...
You can find regular expression primers all over the internet, but to
answer these specific questions: [...] means any of the characters in
the range; the $ means "end of string"; and {2,30} means at least two,
and at most thirty, of the preceding character. So you have to have
one from the first group, then 2-30 from the second, for a total of
3-31 characters in your names.
Got it, thanks!
--
http://mail.python.org/mailman/listinfo/python-list
Re: Regular expression syntax, was Re: pylint, was Re: pygame - importing GL - very bad...
On 01/03/2013 12:39 PM, Peter Otten wrote:
someone wrote:
On 01/03/2013 10:00 AM, Peter Otten wrote:
Terry Reedy wrote:
[a-z_][a-z0-9_]{2,30}$) - so I suppose it wants this name to end with
[an
underscore ?
No, it allows underscores. As I read that re, 'rx', etc, do match. They
No, it's one leading letter or underscore [a-z_] plus at least two
letters, underscores or digits [a-z0-9_]{2,30}
Ah, [a-z0-9_]{2,30} means there should be at least two characters and
maximum 30 characters here ?
Yes. See
http://docs.python.org/2/library/re.html#regular-expression-syntax
Thanks - it's on my TODO-list to learn more about how to use these
regexps...
--
http://mail.python.org/mailman/listinfo/python-list
Re: pylint, was Re: pygame - importing GL - very bad...
On 01/03/2013 03:56 AM, Dave Angel wrote: The first lint program I recall hearing of was available in the early 1980's, and was for the C language. At the time, the C language was extremely flexible (in other words, lots of ways to shoot yourself in the foot) and the compiler was mostly of the philosophy - if there's a way to make sense of the statement, generate some code, somehow. Anyway, lint made sense to me as the crud that gets mixed in with the real fabric. And a linter is a machine that identifies and removes that crud. Well, the lint program didn't remove anything, but it identified a lot of it. I didn't hear the term linter till decades later. Aah, now I understand this "lintering" and where it came from - thanks a lot! :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: pygame - importing GL - very bad...
On 01/04/2013 08:10 PM, someone wrote: > On 01/03/2013 03:09 PM, Mike C. Fletcher wrote: >> > >> PyOpenGL's current approach is mostly attempting to maintain backward >> compatibility with the older revisions. wxPython actually rewrote its >> whole interface to go from * imports into namespaced lookups and then >> wrote a little migration tool that would attempt to rewrite your code >> for the new version. They also provided a transitional API so that code >> could mix-and-match the styles. For PyOpenGL that would look something >> like this: >> >> from OpenGL import gl, glu, glut >> >> gl.Rotate(...) >> gl.Clear(gl.COLOR_BUFFER_BIT) > > Ok, that's interesting. However, I like it the way it is, where I can > copy/paste C-code from the web and change some small things and it'll > work and fit into my needs. BUT I didn't know there was such a > transitional API - interesting. I however don't want to be a > first-mover - let's see if sufficiently many people will use this and > then I'll consider doing it too. At the moment, I still think the > star-import is good because it makes it easy to look for C-code and > program it (=do it) like people would do it in C. > >> or, if you really needed PEP-8 compliance, and don't mind making the API >> look nothing like the original, we might even go to: >> >> from opengl import gl, glu, glut >> >> gl.rotate(...) >> gl.clear(gl.COLOR_BUFFER_BIT) > > Erhm, that's the same as above. Is that what you meant to write? > No, it's not the same; here he did not capitalize the function names. Previously they look like class instantiations. > > > Well, I'm sometimes a bit annoyed that python doesn't give as many > warnings/errors as one gets in C - for instance sometimes I copy/paste > and forget to remove the trailing semi-colons. Trailing semi colons are legal in most cases. The semi-colon is a separator between statements, when one wants to put multiple statements on one line. > However after I began to use pylint and friends, this error will be > caught. Then sometimes I forgot to add () for function calls, which in > C would cause an error by the compiler Actually no. In C, a function name without parentheses is also a function pointer. Not exactly the same as a function object, though C++ gets a lot closer. But the real reason C catches that typo is that the types most likely don't match, depending on what you meant to do with the return value. > but which python allows so one can get the object (which maybe is also > a good reason, but at least in the beginning when I learned python, > this was very annoying + confusing to me). > Function objects are enormously useful, as you get more adept at using Python. -- DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: New to python, do I need an IDE or is vim still good enough?
On 01/04/13 01:34, Anssi Saari wrote: | Just curious since I read the same thing in a programming book recently | (21st century C). So what's the greatness that terminal multiplexors | offer over tabbed terminals? Especially for software development? Do you include tiling terminal emulators? I user iTerm2 a lot on Macs, and it does both tabs (one terminal visible at a time, switch sideways to change terminals) and tiling/panes: multiple terminals visible in split panes within the current window. So I have distinct windows, generally full screen, one per desktop, with desktops for work zones. One a given desktop, just the one window with a few panes panes and sometimes more tabs-with-panes. So superficially, little need for screen or tmux. However I use screen (tmux some time when I have time to learn to use it) for the following: - named sessions: I've a small shell script called "scr" to do some common things with "screen". With no arguments: [/Users/cameron]fleet*> scr 13455.ADZAPPER 2 59094.CONSOLE_FW1 3 28691.MACPORTS 43649.PORTFWD So 4 named screen sessions. To join one "scr ADZAPPER", for example. - detached or at any rate detachable mail editing I've got my mutt editor set to a script that forked the new message editing in screen session named after the subject line. Normally I just compose and send, and that is seamless. But if I have to put things off for a complex or delayed message, I can just detahc from the session and be back in mutt to get on with other things. I imagine I could apply this more widely in some contexts. Plenty of people use the split screen modes in screen or tmux; personally I find this a little fiddly because focus-follows-mouse doesn't work there (though I discovered the other day that vim's split modes can do focus follow mouse:-) But in a restricted environment (eg some hostile one with a crude terminal emulator without these nice tabs/panes) the splitting can be useful. On 04Jan2013 10:59, Tim Chase wrote: | - the ability to monitor windows for activity/silence (at least GNU | Screen offered this; I haven't dug for it yet in tmux which I'm | learning). This is nice for backgrounding a compile and being | notified when it goes silent (usually means it's done) or watching a | long-running quiet process to get notification when it finally has | some output. I used this feature a LOT back when I did C/C++ work. I used to do this: make foo; alert "MADE FOO (exit=$?)" where "alert" is a personal script to do the obvious. On a Mac it pops up a notification. Of course I need to do that at the start, alas. I used to use iTerm's tab header colouring to notice idleness, and it was very useful in certain circumstances, generally wordy and slow startups of multiple things. Don't seem to do it much at present. Cheers, -- Cameron Simpson Having been erased, The document you're seeking Must now be retyped. - Haiku Error Messages http://www.salonmagazine.com/21st/chal/1998/02/10chal2.html -- http://mail.python.org/mailman/listinfo/python-list
Re: New to python, do I need an IDE or is vim still good enough?
In article , Cameron Simpson wrote: > On 01/04/13 01:34, Anssi Saari wrote: > | Just curious since I read the same thing in a programming book recently > | (21st century C). So what's the greatness that terminal multiplexors > | offer over tabbed terminals? Especially for software development? There's no doubt that you need access to multiple terminal sessions. Whether you achieve that with multiple terminal windows on your desktop, multiple desktops, tabbed terminals, or something like screen is entirely personal preference. -- http://mail.python.org/mailman/listinfo/python-list
import of ttk
In reading through one of the learning articles, I have a bit of code that imports ttk, but I apparently don't have this installed. I've looked up the svn checkout for python-tk, and have checked it out (read-only), but still get the same error. I'm running 2.6.6 python, if that helps. The article I'm looking at is here - http://www.zetcode.com/gui/tkinter/introduction/ Any input is appreciated. -- http://mail.python.org/mailman/listinfo/python-list
Re: import of ttk
On 1/4/2013 11:02 PM, Verde Denim wrote: In reading through one of the learning articles, I have a bit of code that imports ttk, but I apparently don't have this installed. I've looked up the svn checkout for python-tk, and have checked it out (read-only), but still get the same error. I'm running 2.6.6 python, if that helps. Show the line of code that did not work and the traceback. What system are you running on and what tcl/tk installation does it have? ttk is included with any 8.5 installation. tile is often included with 8.4 installations and should be picked up as well. The article I'm looking at is here - http://www.zetcode.com/gui/tkinter/introduction/ -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
